var Prototype = {
  Version: '1.5.0',
  BrowserFeatures: {
    XPath: !!document.evaluate
  },
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
  emptyFunction: function() {},
  K: function(x) { return x }
}
var Class = {
  create: function() {
    return function() { 
      this.initialize.apply(this, arguments);
    }
  }
}
var Abstract = new Object();
Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}
Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object === undefined) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },
  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },
  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },
  clone: function(object) {
    return Object.extend({}, object);
  }
});
Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}
Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
  }
}
Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },
  succ: function() {
    return this + 1;
  },
  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});
var Try = {
  these: function() {
    var returnValue;
    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }
    return returnValue;
  }
}
var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;
    this.registerCallback();
  },
  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },
  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },
  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
String.interpret = function(value){
  return value == null ? '' : String(value);
}
Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);
    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },
  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;
    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },
  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },
  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ? 
      this.slice(0, length - truncation.length) + truncation : this;
  },
  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },
  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },
  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },
  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },
  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },
  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },
  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ? 
      $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) : 
      div.childNodes[0].nodeValue) : '';
  },
  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return {};
    return match[1].split(separator || '&').inject({}, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var name = decodeURIComponent(pair[0]);
        var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
        if (hash[name] !== undefined) {
          if (hash[name].constructor != Array)
            hash[name] = [hash[name]];
          if (value) hash[name].push(value);
        }
        else hash[name] = value;
      }
      return hash;
    });
  },
  toArray: function() {
    return this.split('');
  },
  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },
  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];
    var camelized = this.charAt(0) == '-' 
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];
    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
    return camelized;
  },
  capitalize: function(){
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },
  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },
  dasherize: function() {
    return this.gsub(/_/,'-');
  },
  inspect: function(useDoubleQuotes) {
    var escapedString = this.replace(/\\/g, '\\\\');
    if (useDoubleQuotes)
      return '"' + escapedString.replace(/"/g, '\\"') + '"';
    else
      return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  }
});
String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}
String.prototype.parseQuery = String.prototype.toQueryParams;
var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },
  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + String.interpret(object[match[3]]);
    });
  }
}
var $break    = new Object();
var $continue = new Object();
var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },
  eachSlice: function(number, iterator) {
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.map(iterator);
  },
  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },
  any: function(iterator) {
    var result = false;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index)) 
        throw $break;
    });
    return result;
  },
  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push((iterator || Prototype.K)(value, index));
    });
    return results;
  },
  detect: function(iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },
  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },
  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },
  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },
  inGroupsOf: function(number, fillWith) {
    fillWith = fillWith === undefined ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },
  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },
  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },
  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },
  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },
  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ? 
        trues : falses).push(value);
    });
    return [trues, falses];
  },
  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },
  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },
  sortBy: function(iterator) {
    return this.map(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },
  toArray: function() {
    return this.map();
  },
  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();
    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },
  size: function() {
    return this.toArray().length;
  },
  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}
Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0, length = iterable.length; i < length; i++)
      results.push(iterable[i]);
    return results;
  }
}
Object.extend(Array.prototype, Enumerable);
if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;
Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },
  clear: function() {
    this.length = 0;
    return this;
  },
  first: function() {
    return this[0];
  },
  last: function() {
    return this[this.length - 1];
  },
  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },
  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },
  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },
  indexOf: function(object) {
    for (var i = 0, length = this.length; i < length; i++)
      if (this[i] == object) return i;
    return -1;
  },
  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },
  reduce: function() {
    return this.length > 1 ? this : this[0];
  },
  uniq: function() {
    return this.inject([], function(array, value) {
      return array.include(value) ? array : array.concat([value]);
    });
  },
  clone: function() {
    return [].concat(this);
  },
  size: function() {
    return this.length;
  },
  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});
Array.prototype.toArray = Array.prototype.clone;
function $w(string){
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}
if(window.opera){
  Array.prototype.concat = function(){
    var array = [];
    for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
    for(var i = 0, length = arguments.length; i < length; i++) {
      if(arguments[i].constructor == Array) {
        for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++) 
          array.push(arguments[i][j]);
      } else { 
        array.push(arguments[i]);
      }
    }
    return array;
  }
}
var Hash = function(obj) {
  Object.extend(this, obj || {});
};
Object.extend(Hash, {
  toQueryString: function(obj) {
    var parts = [];
	  this.prototype._each.call(obj, function(pair) {
      if (!pair.key) return;
      if (pair.value && pair.value.constructor == Array) {
        var values = pair.value.compact();
        if (values.length < 2) pair.value = values.reduce();
        else {
        	key = encodeURIComponent(pair.key);
          values.each(function(value) {
            value = value != undefined ? encodeURIComponent(value) : '';
            parts.push(key + '=' + encodeURIComponent(value));
          });
          return;
        }
      }
      if (pair.value == undefined) pair[1] = '';
      parts.push(pair.map(encodeURIComponent).join('='));
	  });
    return parts.join('&');
  }
});
Object.extend(Hash.prototype, Enumerable);
Object.extend(Hash.prototype, {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (value && value == Hash.prototype[key]) continue;
      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },
  keys: function() {
    return this.pluck('key');
  },
  values: function() {
    return this.pluck('value');
  },
  merge: function(hash) {
    return $H(hash).inject(this, function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },
  remove: function() {
    var result;
    for(var i = 0, length = arguments.length; i < length; i++) {
      var value = this[arguments[i]];
      if (value !== undefined){
        if (result === undefined) result = value;
        else {
          if (result.constructor != Array) result = [result];
          result.push(value)
        }
      }
      delete this[arguments[i]];
    }
    return result;
  },
  toQueryString: function() {
    return Hash.toQueryString(this);
  },
  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
});
function $H(object) {
  if (object && object.constructor == Hash) return object;
  return new Hash(object);
};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },
  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },
  include: function(value) {
    if (value < this.start) 
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});
var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}
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) {
  if (Prototype.BrowserFeatures.XPath) {
    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
    return document._getElementsByXPath(q, parentElement);
  } else {
    var children = ($(parentElement) || document.body).getElementsByTagName('*');
    var elements = [], child;
    for (var i = 0, length = children.length; i < length; i++) {
      child = children[i];
      if (Element.hasClassName(child, className))
        elements.push(Element.extend(child));
    }
    return elements;
  }
};
if (!window.Element)
  var Element = new Object();
Element.extend = function(element) {
  if (!element || _nativeExtensions || element.nodeType == 3) return element;
  if (!element._extended && element.tagName && element != window) {
    var methods = Object.clone(Element.Methods), cache = Element.extend.cache;
    if (element.tagName == 'FORM')
      Object.extend(methods, Form.Methods);
    if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName)) 
      Object.extend(methods, Form.Element.Methods);
    Object.extend(methods, Element.Methods.Simulated);
    for (var property in methods) {
      var value = methods[property];
      if (typeof value == 'function' && !(property in element))
        element[property] = cache.findOrStore(value);
    }
  }
  element._extended = true;
  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) {
    $(element).style.display = '';
    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('*'));
  },
  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) {
    return Selector.findElement($(element).ancestors(), expression, index);
  },
  down: function(element, expression, index) {
    return Selector.findElement($(element).descendants(), expression, index);
  },
  previous: function(element, expression, index) {
    return Selector.findElement($(element).previousSiblings(), expression, index);
  },
  next: function(element, expression, index) {
    return Selector.findElement($(element).nextSiblings(), expression, index);
  },
  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 (document.all && !window.opera) {
      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];
      if(attribute) return attribute.nodeValue;
    }    
    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();
  },
  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.match(/^\s*$/);
  },
  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);
    if (['float','cssFloat'].include(style))
      style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
    style = style.camelize();
    var value = element.style[style];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css[style] : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style];
      }
    }
    if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none'))
      value = element['offset'+style.capitalize()] + 'px';
    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';
    if(style == 'opacity') {
      if(value) return parseFloat(value);
      if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))  
        if(value[1]) return parseFloat(value[1]) / 100;  
      return 1.0; 
    }
    return value == 'auto' ? null : value;
  },
  setStyle: function(element, style) {
    element = $(element);
    for (var name in style) {
      var value = style[name];
      if(name == 'opacity') {
        if (value == 1) {
          value = (/Gecko/.test(navigator.userAgent) &&
            !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
        } else if(value == '') {
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
        } else {
          if(value < 0.00001) value = 0;  
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
              'alpha(opacity='+value*100+')';
        }
      } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat';
      element.style[name.camelize()] = 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};
    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';
      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});
Element._attributeTranslations = {};
Element._attributeTranslations.names = {
  colspan:   "colSpan",
  rowspan:   "rowSpan",
  valign:    "vAlign",
  datetime:  "dateTime",
  accesskey: "accessKey",
  tabindex:  "tabIndex",
  enctype:   "encType",
  maxlength: "maxLength",
  readonly:  "readOnly",
  longdesc:  "longDesc"
};
Element._attributeTranslations.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;
  }
};
Object.extend(Element._attributeTranslations.values, {
  href: Element._attributeTranslations.values._getAttr,
  src:  Element._attributeTranslations.values._getAttr,
  disabled: Element._attributeTranslations.values._flag,
  checked:  Element._attributeTranslations.values._flag,
  readonly: Element._attributeTranslations.values._flag,
  multiple: Element._attributeTranslations.values._flag
});
Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
    var t = Element._attributeTranslations;
    attribute = t.names[attribute] || attribute;
    return $(element).getAttributeNode(attribute).specified;
  }
};
if (document.all && !window.opera){
  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;
  }
};
Object.extend(Element, Element.Methods);
var _nativeExtensions = false;
if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
  ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
    var className = 'HTML' + tag + 'Element';
    if(window[className]) return;
    var klass = window[className] = {};
    klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
  });
Element.addMethods = function(methods) {
  Object.extend(Element.Methods, 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);
    }
  }
  if (typeof HTMLElement != 'undefined') {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
    copy(Form.Methods, HTMLFormElement.prototype);
    [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
      copy(Form.Element.Methods, klass.prototype);
    });
    _nativeExtensions = true;
  }
}
var Toggle = new Object();
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);
var Selector = Class.create();
Selector.prototype = {
  initialize: function(expression) {
    this.params = {classNames: []};
    this.expression = expression.toString().strip();
    this.parseExpression();
    this.compileMatcher();
  },
  parseExpression: function() {
    function abort(message) { throw 'Parse error in selector: ' + message; }
    if (this.expression == '')  abort('empty expression');
    var params = this.params, expr = this.expression, match, modifier, clause, rest;
    while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
      params.attributes = params.attributes || [];
      params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
      expr = match[1];
    }
    if (expr == '*') return this.params.wildcard = true;
    while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
      modifier = match[1], clause = match[2], rest = match[3];
      switch (modifier) {
        case '#':       params.id = clause; break;
        case '.':       params.classNames.push(clause); break;
        case '':
        case undefined: params.tagName = clause.toUpperCase(); break;
        default:        abort(expr.inspect());
      }
      expr = rest;
    }
    if (expr.length > 0) abort(expr.inspect());
  },
  buildMatchExpression: function() {
    var params = this.params, conditions = [], clause;
    if (params.wildcard)
      conditions.push('true');
    if (clause = params.id)
      conditions.push('element.readAttribute("id") == ' + clause.inspect());
    if (clause = params.tagName)
      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    if ((clause = params.classNames).length > 0)
      for (var i = 0, length = clause.length; i < length; i++)
        conditions.push('element.hasClassName(' + clause[i].inspect() + ')');
    if (clause = params.attributes) {
      clause.each(function(attribute) {
        var value = 'element.readAttribute(' + attribute.name.inspect() + ')';
        var splitValueBy = function(delimiter) {
          return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
        }
        switch (attribute.operator) {
          case '=':       conditions.push(value + ' == ' + attribute.value.inspect()); break;
          case '~=':      conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
          case '|=':      conditions.push(
                            splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
                          ); break;
          case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
          case '':
          case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break;
          default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
        }
      });
    }
    return conditions.join(' && ');
  },
  compileMatcher: function() {
    this.match = new Function('element', 'if (!element.tagName) return false; \
      element = $(element); \
      return ' + this.buildMatchExpression());
  },
  findElements: function(scope) {
    var element;
    if (element = $(this.params.id))
      if (this.match(element))
        if (!scope || Element.childOf(element, scope))
          return [element];
    scope = (scope || document).getElementsByTagName(this.params.tagName || '*');
    var results = [];
    for (var i = 0, length = scope.length; i < length; i++)
      if (this.match(element = scope[i]))
        results.push(Element.extend(element));
    return results;
  },
  toString: function() {
    return this.expression;
  }
}
Object.extend(Selector, {
  matchElements: function(elements, expression) {
    var selector = new Selector(expression);
    return elements.select(selector.match.bind(selector)).map(Element.extend);
  },
  findElement: function(elements, expression, index) {
    if (typeof expression == 'number') index = expression, expression = false;
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },
  findChildElements: function(element, expressions) {
    return expressions.map(function(expression) {
      return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) {
        var selector = new Selector(expr);
        return results.inject([], function(elements, result) {
          return elements.concat(selector.findElements(result || element));
        });
      });
    }).flatten();
  }
});
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 != undefined) {
          if (result[key]) {
            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().each(function(element) {
      element.blur();
      element.disabled = 'true';
    });
    return form;
  },
  enable: function(form) {
    form = $(form);
    form.getElements().each(function(element) {
      element.disabled = '';
    });
    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;
  }
}
Object.extend(Form, Form.Methods);
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);
    element.focus();
    if (element.select && ( element.tagName.toLowerCase() != 'input' ||
      !['button', 'reset', 'submit'].include(element.type) ) )
      element.select();
    return element;
  },
  disable: function(element) {
    element = $(element);
    element.disabled = true;
    return element;
  },
  enable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = false;
    return element;
  }
}
Object.extend(Form.Element, Form.Element.Methods);
var Field = Form.Element;
var $F = Form.Element.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) {
    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;
    }
  },
  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' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';
    Event._observeAndCache(element, name, observer, useCapture);
  },
  stopObserving: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;
    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';
    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      try { 
        element.detachEvent('on' + name, observer); 
      } catch (e) {}
    }
  }
});
if (navigator.appVersion.match(/\bMSIE\b/))
  Event.observe(window, 'unload', Event.unloadCache, false);
window._alert = window.alert;
window.$Debug = true;
if (window == window.scope && $Debug) {
  window.scope.logCache= "";
  window.scope.createDebugDom = function (){
    var c = scope.$("special"); 
    if (!c) return false;
    var lg = document.createElement("textarea");
  };
  window.scope.log= function (m) {
    return;
    var e = window.scope.$("debug");
    e.style.display="block";
    e.clr = !e.clr;
    var s = $A(arguments).join("\n") + "\n";
    if (e == null) {
      window.scope.logCache += s;
    } else {
      $("debug").style.display="block";
      e.innerHTML += window.scope.logCache + s;
      window.scope.logCache= "";
    }
  };
}
window.ArrayWithout = function(){
  if(arguments.length < 2) return arguments.length == 1 ? arguments[0] : null;
  var results = [];
  var aa = arguments[0];
  if(aa == null || aa.constructor != Array) return null;
  for(var i=0;i<aa.length;i++){
    var isWithout = true;
    for(var j=1;j<arguments.length;j++){
      if(aa[i] == arguments[j]){
        isWithout = false;
        break;
      }
    }
    if(isWithout) results.push(aa[i]);
  }
  return results;
}
window.each = function (ar, insp){
  var r = [];
  for(var i=0;i<ar.length;i++){
    var x = insp(ar[i], i);
    if (x != null) r.push(x);
  }
  return r;
}
window.foreach = function (ar, insp){
	var i=0, len = ar.length, r = [];
	while(i<len){
		var x = insp(ar[i], i);
		if(x != null)	r[r.length] = x;
		i++;
	};
	return r;
};
window.byId = function (id){ return document.getElementById(id); }
window.getElementsByClass = function(el, tg, clz){
  el = el || document;
  var rs = [];
  clz = " "+clz+" ";
  var cldr = el.getElementsByTagName(tg), len = cldr.length;
  for (var i=0; i<len; ++i){
    var o = cldr[i];
    if (o.nodeType == 1){
      var ecl = " "+o.className+" ";
      if (ecl.indexOf(clz) != -1)
        rs[rs.length] = o;
    }
  }
  return rs;
}
window.byClz = window.getElementsByClass;
window.getChildrenByClass = function(el, clz){
  var rs = [];
  clz = " "+clz+" ";
  var cldr = el.childNodes, len = cldr.length;
  for (var i=0; i<len; ++i){
    var o = cldr[i];
    if (o.nodeType == 1){
      var ecl = " "+o.className+" ";
      if (ecl.indexOf(clz) != -1)
        rs[rs.length] = o;
    }
  }
  return rs;
}
window.getElementByClassAttr = function(el, clz){
  var clazz,attr,value;
  clz.replace(/(\w+)\[(\w+)\=(\w+)\]/g,function (a0,b1,b2,b3){
    clazz = b1;
    attr  = b2;
    value = b3;
  });
  var Elements = window.getChildrenByClass(el, clazz);
  var len = Elements.length;
  for(var i=0;i<len;i++){
    if(Elements[i][attr] == value)
      return Elements[i];
  }
  return null;
}
window.childById = function(el, id){
  if (el == null) return null;
  var cld = el.childNodes;
  for (var i=0; i<cld.length; ++i){
    var o = cld[i];
    if (o.nodeType == 1 && o.id == id){   //Element and id is correct
      return o;
    }
  }
}
window.descByIds = function (el, ids){
  if (el == null) el = document;
  if (typeof el == "string") {     
    ids = el; el = document;
  }
  if (typeof ids == "string") {
    ids = ids.split("#");
    if (ids[0] == "") ids.shift();                   
  }
  if (el.nodeType == 9 && ids[0].indexOf(">") == -1){ 
    el = el.getElementById(ids[0]);
    ids.shift();
  }
  if (el == null) return null;     
  for (var si=0; si<ids.length; ++si){
    var id = ids[si];
    if (id.indexOf(">") >= 0){
      var tn = id.split(">");
      var cld = el.getElementsByTagName(tn[0] || "*"), len = cld.length;
      id = tn[1];
    } else {
      var cld = el.childNodes, len = cld.length;
    }
    for (var i=0; i<len; ++i){
      var e = cld[i];
      if (e.nodeType == 1 && e.id == id){
        el = e;
        break;
      }
    }
    if (i == len) return null;  
  }
  return el;
}
window.removeClassName = function (obj, _className){
  obj = typeof(obj) == "string" ? byId(obj) : obj;
  obj.className = (" " + obj.className + " ").replace(" "+_className+" ","");
}
window.elementMethods = {
  $$ : Element.getElementsBySelector,
  childArray : Element.immediateDescendants,
  childById : window.childById,
  getChildrenByClass : window.getChildrenByClass,
  getElementByClassAttr : window.getElementByClassAttr,
  middle : function (el){   
    var ew = el.getWidth();
    var eh = el.getHeight();
    var p = $(el.parentNode);
    var pw = p.getWidth();
    var ph = p.getHeight();
    el.setStyle({
      left : (pw-ew)/2 +"px",
      top : (ph-eh)/2 +"px"
    });
    return el;
  }, 
  showBlock : function (el){
    el.style.display="block";
    return el;
  },
  opacity : function(el, value) {
    value = parseInt(value);
    if (isNaN(value)) throw new Error("not a number");
    value > 100 && (value = 100);
    value < 0 && (value = 0);
    el.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity = " + value + ")";
    el.style.MozOpacity = value / 100;
    el.style.Opacity = value / 100;
    return el;
  },
  nearest : function (el, css) {
    var id = css;
    var parent = el, target = childById(parent, id);
    while (!target && parent) {
      parent = parent.parentNode;
      target = childById(parent, id); 
    }
    if (target)
      return {parent:parent,target:target};
    else
      return {};
  },
   displayToggle : function(clickEl,type) {
     type = type || "mousedown";
     try{
       clickEl = $(clickEl);
       var ids = clickEl.readAttribute("toggle").split(" "), len = ids.length;
       var displayEl = [];
       for (var i=0; i<len; ++i){
         var id = ids[i];
         var tar = elementMethods.nearest(clickEl, id).target;
         if (tar != null) displayEl.push(tar);
       }
       if (displayEl.length==0){
       }
       Event.observe(clickEl, type, function (event) {
         clickEl.toggleClassName("collapsed");
         displayEl.each(Element.toggle);
         Event.stop(event);
         autoSize();
       });
       return clickEl;
     } catch (e){
       window.scope.log(e);
     }
   },
  hoverToggle : function (el){
    var o = el.nearest(".hoverView");
    el.observe("mouseover",function (){
      o.target.show();
      autoSize();
    });
    o.parent.observe("mouseout",function (){
      o.target.hide();
      autoSize();
    });
    return el;
  },
  slideControl : function (el){ 
    try{
      var tar = descByIds(el.getChildrenByClass("componentInnderBorder")[0], "#componentContent#slideContent");
      var slides = [];
      slides.index = 0;
      var clds = tar.childNodes, len = clds.length;
      for (var i=0; i<len; ++i){
        var e = clds[i];
        if (e.nodeType == 1) {
          e.style.display = "none"; 
          slides.push(e);
        }
      }
      slides[0].style.display = "";
      if(slides.length>1){
        var ll = descByIds(el.getChildrenByClass("componentInnderBorder")[0], "#componentContent#slideButtonArea");
        var prev = childById(ll,"prev");
        var next = childById(ll,"next");
        prev.style.display = "none";
        Event.observe(next,"click",function (){
          slides[slides.index].style.display = "none";
          slides[++slides.index].style.display = "";
          prev.style.display = "";
          next.style.display = "";
          if (slides.index == slides.length - 1){
            next.style.display = "none";
          }
        });
        Event.observe(prev,"click",function (){
          slides[slides.index].style.display = "none";
          slides[--slides.index].style.display = "";
          prev.style.display = "";
          next.style.display = "";
          if (slides.index == 0) {
            prev.style.display = "none";
          }
        });
      }
    }catch (e){}
  },
  getWin : function (iframeElement) {
    iframeElement = $(iframeElement);
    if (iframeElement.contentWindow)
      return iframeElement.contentWindow;
    else {
      var ifm = iframeElement.down("iframe");
      if (ifm) return ifm.contentWindow;
      else return null;
    }
  },
  advLayout : function (el) {
    var html =
    '<div class="layout3by3_bound"><table id="' + el.id + '_layout_1" class="layout3by3">\
      <tr>\
        <td id="c7">\
          <div/>\
        <\/td>\
        <td id="c8"><\/td>\
        <td id="c9">\
          <div/>\
        <\/td>\
      <\/tr>\
    <\/table>' +
    '<table id="' + el.id + '_layout_2" class="layout3by3">\
    <tr>\
        <td id="c4"><\/td>\
        <td id="c5">\
          <div id="layoutContent">'
          +
        '<\/div>\
        <\/td>\
        <td id="c6"><\/td>\
      <\/tr>\
    <\/table>' +
    '<table id="' + el.id + '_layout_2" class="layout3by3">\
      <tr>\
        <td id="c1">\
          <div/>\
        <\/td>\
        <td id="c2"><\/td>\
        <td id="c3">\
          <div/>\
        <\/td>\
      <\/tr>\
    <\/table><\/div>';
    var children = $A(el.childNodes);
    new Insertion.Top(el, html);
    var container = el.down("#layoutContent");
    children.each(function (child) {
      container.appendChild(child);
    });
    return el;
  },
  getLeft : function (element) {
    var left = 0;
    var el = $(element);
    if (el.offsetParent) {
      while (el.offsetParent) {
        left += el.offsetLeft;
        el = el.offsetParent;
      }
    } else if (el.x) left += el.x;
    return left;
  },
  getTop : function (element) {
    var top = 0;
    var el = $(element);
    if (el.offsetParent) {
      while (el.offsetParent) {
        top += el.offsetTop;
        el = el.offsetParent;
      }
    } else if (el.y) top += el.y;
    return top;
  }
}
Element.addMethods(window.elementMethods);
Class.AsPrototype = {};
Class.create = function (){
  return function (t){
    if (t != Class.AsPrototype)
      this.initialize.apply(this, arguments);
  }
}
Class.define = function (init, superClz, methods) {
  if (init && init.__isClass && init.__isClass()) throw new Error("class cnt be used as another class' constructor : " + init);
  superClz = superClz || Object;
  methods = methods || {};
  methods.initialize = init || methods.initialize || superClz.prototype.initialize || (function (){});
  if (typeof(methods.initialize) != "function") throw new Error("only function can be used as constructor");
  methods.__isClass = function (){return true;};
  var clz = Class.create();
  clz.__isClass = methods.__isClass;
  var proto = superClz == Object ? {} : new superClz(Class.AsPrototype);
  clz.prototype = Object.extend(proto, methods);
  return clz;
}
Array.prototype.foreach = function (insp){
	var i=0, len = this.length, r = [];
	while(i<len){
		var x = insp(this[i], i);
		if(x != null)	r[r.length] = x;
		i++;
	};
	return r;
};
Array.prototype.toInt = function (i){
  return this.join("").toInt(i);
}
Array.prototype.hashBy = function(id){
  var o = {};
  this.each(function (e){
    o[e[id]] = e;
  });
  return o;
}
Array.prototype.up = function (index, num) {
  num = num > index ? index : num;
  return this.slice(0, index-num).concat(this[index],this.slice(index-num, index),this.slice(index+1));
}
Array.prototype.down = function (index, num) {
  num = num > this.length - index ? this.length - index  : num;
  return this.slice(0, index).concat(this.slice(index+1, index+num+1),this[index],this.slice(index+num+1));
}
Array.prototype.findit = function (v) {
  var flag;
  this.each(function (value,index){
    if(v == value)  {
      flag = index;
      throw $break;
    }
  });
  return flag;
}
String.prototype.a2u = function (){
  return this.replace(/\\u[\da-fA-F]{4}/gi,function (a){
    a = a.substr(2).toInt(16);
    return String.fromCharCode(a);
  });
}
String.prototype.expand = function (){
 var r= this.replace(/([\u00ff-\ufffe])/gi,"\uffff$1");
 return r;
}
String.prototype.collapse = function (){
 return this.replace(/\uffff/gi,"");
}
String.prototype.shorten = function (len, suffix){
  suffix = suffix || "..";
  return this.expand().substr(0,len).collapse() +
      suffix;
}
String.prototype.trim = function () {
  return this.trimTail().trimHead();
};
String.prototype.trimHead = function () {
  return this.replace(/^(\u3000|\s|\t)*/gi, "");
};
String.prototype.trimTail = function () {
  return this.replace(/(\u3000|\s|\t)*$/gi, "");
};
String.prototype.j2o = function (){
  try{
    var o = eval("(" + this + ")");
    return o;
  } catch (e){
    return null;
  }
}
String.prototype.toInt = function (i){
  return parseInt(this,i);
}
String.prototype.toArray = function(n){
  n = n || 1;
  if (n == 1) return this.split("");
  var reg = new RegExp(".{1," + n + "}","gim");
  return this.match(reg);
}
Function.prototype.delay = function (time){
  time = time || 10;
  var func = this;
  return function (){
    window.setTimeout(func, time);
  }
}
Function.prototype.when = function (tar, evt, once){
  once = !!once;
  var func = this;
  var observer = function (){
    func.apply();
    if (once) tar.stopObserving(evt, observer);
  }
  tar.observe(evt, observer);
  return observer;
}
Function.prototype.delayed = function (time){
  time = time || 10;
  window.setTimeout(this, time);
}
Function.prototype.times = function (n){
  for (var i=0;i<n;i++){
    this();
  }
}
Function.prototype.asCall = function (){
  var func = this;
  var args = $A(arguments);
  return function (t){
    return func.apply(t,args);
  }
}
Function.prototype.Try = function (){
  try{
    this();
  } catch (e){}
}
Function.prototype.protect = function (){
 var name = this.toString().match(/function[\s\t]+([^\(\s\t]*)/)[1];
 var thiz = this;
 var func = function (){
   try{
     thiz();
   } catch (e) {
   }
 }
 return func;
}
Function.prototype.once = function (){
  if (this.__$$alreadyInvokded == true) return;
  this();
  this.__$$alreadyInvokded = true;
}
Function.prototype.combine = function (){
  return $combine.apply(null,[this].concat($A(arguments)));
}
var $combine = function (){
  var funcArray = $A(arguments);
  return function (){
    var args = arguments;
    funcArray.each(function (f){
      f.apply(this,args);
    });
  }
}
function isMainFrame() {
  return this.scope == this;
}
function autoSize(ifm, resizeAncestor) {
  if (ifm == null){
    if (resizeAncestor != false && parent.autoSize && this.frameElement){
      autoSize.apply(parent, [this.frameElement]);
      return;
    } else
      return;
  }
  window.scope.$iframeResizeQueue = window.scope.$iframeResizeQueue || [];
  var queue = window.scope.$iframeResizeQueue;
  queue.push([this, ifm]);
  while (queue.length > 0){
    try{
      var item = queue.shift();
      var hostWin = item[0];
      var iframe = $(item[1]);
      var iframeWin = iframe.contentWindow;
      var lstn = scope.$IF.autoSizeMe.bind(hostWin.frameElement);
      lstn = lstn.combine((function (){
        var bd = iframeWin.document.body;
        var t = bd.style.display;
        bd.style.display = "none";
        bd.style.display = t;
      }).protect());
      if ($Br.$IE7 || $Br.Gecko) {
        iframeWin.onresize = lstn;
      } else if ($Br.$IE6){
        iframeWin.frameElement.onresize = lstn;
      }
      var innerEl  = iframeWin.document.getElementById("innerBound");
      var scrollEl = iframeWin.document.getElementById("outBound");
      iframe.style.display = "block";
      if (innerEl && scrollEl) {
        scrollEl.style.height = innerEl.scrollHeight + "px";
        iframe.style.height   = innerEl.scrollHeight + 1 + "px";
      } else {
        innerEl = iframeWin.document.body;
        scrollEl = innerEl ? innerEl.parentNode : null;
        if (innerEl && scrollEl) {
          iframe.style.height = "10px";
          var h1 = innerEl.scrollHeight, h2 = scrollEl.scrollHeight;
          var ht = h1 > h2 ? h1 : h2
          scrollEl.style.height = ht + "px";
          iframe.style.height   = ht + 1 + "px";
        } else {
        }
      }
	  var stl = iframe.contentWindow.document.body.style;
      var __bkp = stl.display;
      stl.display="none";
      stl.display=__bkp;
    } catch (e){
      try{} catch (e){}
    }
  }
}
function autoSizeAllIframe() {
  $$("iframe").each(autoSize, false);
  autoSize();
}
function addClickToggle(css) {
  var styles = css || [
      "a.toggleLink",
      "legend.toggleLink",
      "table.toggleLink",
      "div.toggleLink"];
  $$.apply(null, styles).each(elementMethods.displayToggle)
}
function addHoverToggle() {
}
function addAdvLayout(csses) {
  return;
  csses.each(function (css) {
    $$(css).each(elementMethods.advLayout);
  });
}
function createIframeByA(a) {
  if (a.className.indexOf("iframeUrlHolder") >=0 && /^http:\/\/blog\.sina\.com\.cn/.test(a.href)) {
    $(a).replace('<iframe id="' + a.id + '" name="' + a.id + '" class="subContent"\
              scrolling="no"\
              allowTransparency="true" frameborder="0"\
              src="' + a.href + '"\
              style="height:0px"\
              ><\/iframe>');
  }
}
function createIframes() {
  var ifms = getElementsByClass(document, "a", "iframeUrlHolder");
  each(ifms, createIframeByA);
}
function resizeOutBound() {
  var outBound = byId("outBound");
  var sysBar = byId("system");
  outBound.style.top = sysBar.clientHeight + "px";
  outBound.style.height = document.body.clientHeight - sysBar.clientHeight + "px";
}
function addBannerFunction(){
  var linkHolder = scope.descByIds("#bannerContent#div>blogLink");
  var linkUrl = descByIds(linkHolder, "#blogURL").innerHTML;
  var blogName = descByIds("#blogContent#div>blogName");
  if ($Br.$IE) {
    var cp = childById(linkHolder, "copyBlogURL");
    Event.observe(cp, "click", function(){
        setClipBoard(linkUrl);
      });
    var fv = childById(linkHolder, "toFavorite");
    Event.observe(fv, "click",function(){
        addToFavorites(linkUrl, blogName);
      });
  }
}
function runAnchorCommandInMainFrame(win){
  win = win || scope;
  var subContentManager = function(url){
    var ifm = scope.getConIF();
    var subWin = ifm.contentWindow;
    subWin.location.href = url;
  }
  var cmd = createAnchorCommand();
  cmd.setExecutor("asc", subContentManager);   
  cmd.runCommands(false);
}
function fixMenuLink(con, isMain){
  var as = con.getElementsByTagName("a");
  for (var i=0; i<as.length; ++i){
    var a = as[i];
    var tar = a.target;
    if (tar == "Content_ArticlePreview"){
      if (isMain){
        var hr = a.href.match(/cmd:asc\(([^)]*)\)/) || [];
        hr = hr[1];
        a.href = hr;
      } else {
        a.target = "_blank";
      }
    }
  }
}
function fixGbookUrl(url, replaceAll){
  if (! scope.$isAdmin) return url;
  var uid = url.match(/gbook_(\d*)_(\d*)\.html/) || [];
  var page = uid[2];
  uid = uid[1];
  var admUrl = scope.$Url("gbookAdmin", {uid:uid, page:page});
  if (replaceAll || url.indexOf("#cmd:") == -1) return admUrl;
  return url.replace(/\([^\)]*\)/g, "(" + admUrl + ")");
}
function autoSizeIframe5Times(ifm){
  if (!ifm) return;
  var times = 5;
  var handler = window.setInterval(function (){
    times --;
    if (times == 0) window.clearInterval(handler);
    ifm.style.display="block";
    scope.autoSize(ifm);
  }, 2000);
  var lastAutoSize = function (){
    Event.stopObserving(ifm, "load", lastAutoSize);
    window.clearInterval(handler);
    autoSize();
  }
  Event.observe(ifm, "load", lastAutoSize);
}
function checkLogin(){
  var message=$("message");
  var postform=$("postform");
  var bakStr='<input type="button" id="bakBut" value="确认" class="bakBut"/>'
  $("frmh").observe("load",(function(){
    var win = this.contentWindow; 
    var doc=win.document;
    var instruction=doc.getElementById("instruction");
        if (!instruction) return;
    if(instruction.getAttribute("result")=="fail"){
      message.innerHTML = doc.getElementById("text").innerHTML+bakStr;
      $("bakBut").observe("click",function(){
        message.hide();
        load_chk_img('chk_img');
        postform.show();
        win.parent.check_error(); 
      });
      message.show();
      postform.hide();
    }else{
      parent.window.location.reload()
    }
  }).bind($("frmh")));
}
function init_sinaMessage(){
  $("global_links").innerHTML=getHeadHot();
  headMenu=getHeadMenu();
  headMenu=headMenu.replace("search?q=","search?q="+$author);
  $("personal_link").innerHTML=headMenu;
  $("footerContent").innerHTML=getFoot();
}
function viewMessageReplay (sURL, oNode, nGID) {
  var actionStr = "http://my.blog.sina.com.cn/myblog/gbook/newgbookpostreply.php?uid="+scope.uid;
  var msgContainer = $(oNode.parentNode.parentNode);
  var replyDiv = msgContainer.down("#messageReplyForm");
  if(replyDiv.className == "invisible") {
    replyDiv.className = "";
    msgContainer.down("#messageReply").className = "invisible";
    if(replyDiv.innerHTML.length < 10) {
      var str = msgContainer.down("#messageReplyContent").innerHTML;
      str = str.length > 0 ? str: "";
      var formStr = "\
      <form action='"+actionStr+"' method='post' target='messageReplyProxy'>\
        <textarea name='content' class='messageReplyFormArea'>"+str+"<\/textarea>\
        <input type='hidden' value='"+nGID+"' name='gid' \/>\
        <div class='messageReplyFormSubmitDiv'>\
          <input type='submit' value='&nbsp;' class='icon messageReplyFormSubmit' \/>\
         <\/div>\
      <\/form>\
      <iframe id='messageReplyProxy' name ='messageReplyProxy' style='display:none;'><\/iframe>\
      ";
      replyDiv.innerHTML = formStr;
      scope.$IF.watchIframe(childById(replyDiv, "messageReplyProxy"), {
        gbook_reply : {
          succ : function (rs){
            alert(rs.text);
            try{
              var win = this.getWin().parent;
              win.location.reload();
            } catch (e){
            }
          },
          fail : function (rs){
            alert(rs.text);
          }
        }
      });
    }
  }
  else {
    msgContainer.down("#messageReply").className = "";
    replyDiv.className = "invisible";
    replyDiv.innerHTML = "";
  }
}
function createAnchorCommand(){
  window.acmd = window.acmd || new AnchorCommand(window);
  return window.acmd;
}
function createAssistants(){
  addClickToggle([
      "legend.toggleLink",
      "div.toggleLink"]);
  addSlide();
}
function informIframeReady(subWin){
  if (subWin != scope 
  && subWin.frameElement 
  && subWin.frameElement == scope.byId("Content_ArticlePreview")) 
    scope.switchContainerToIframe.Try();
  try{ autoSizeIframe5Times(subWin.frameElement);} catch (e){}
}
function generatePagingForSubpage(iMaxPage, ptn, containerId, winId){
  iMaxPage = Math.ceil(iMaxPage);
  winId         = winId || "Content_ArticlePreview";
  var win       = scope.byId(winId).contentWindow;
  var container = win.byId(containerId);
  var urlData   = location.href.match(/_([\d\w]+)_([\d]+)\.html/) || [];
  var id        = urlData[1];
  var cur       = urlData[2].toInt();
  var html = generatePagingHtml(cur, iMaxPage, ptn, {id:id}, "_self");
  container.innerHTML = html;
}
function createPageing(curPage, iMaxPage, ptn, data, container){
  data.page = "@page@"; 
  container.innerHTML =  generatePagingHtml(curPage, iMaxPage, ptn, data);
}
function generatePagingHtml(curPage, maxPage, urlPtn, data, target){
  data.page = "@page@"; 
  var html = PagingLine.Create(curPage, maxPage, scope.$Url(urlPtn, data), target)
                       .ToggleEndpoint(true)
                       .Render("zh-cn");
  return html;
}
var URL = Class.define(function (url){
    url = url || "";
    this.url = url;
    this.parse();
},Object, {
  parse : function (){
    this.parseAnchor();
    this.parseParam();
  },
  parseAnchor : function (){
    var anchor = this.url.match(/\#(.*)/);
    anchor = anchor ? anchor[1] : null;
    this._anchor = anchor;
    if (anchor != null){
      this.anchor = this.getNameValuePair(anchor);
      this.url = this.url.replace(/\#.*/,"");
    }
  },
  parseParam : function (){
    var query = this.url.match(/\?([^\?]*)/);
    query = query ? query[1] : null;
    if (query != null){
      this.url = this.url.replace(/\?([^\?]*)/,"");
      this.query = this.getNameValuePair(query);
    }
  },
  getNameValuePair : function (str){
    var o = {};
    str.replace(/([^&=]*)(?:\=([^&]*))?/gim, function (w, n, v) {
      if (n == "") return;
      v = v || "";
      o[n] = v.j2o() ? v.j2o() : v;
    });
    return o;
  },
  clearParam : function (){
    this.query = {};
  },
  setParam : function (name, value) {
    if (name == null || name == "" || typeof(name) != "string")
      throw new Error("no param name set");
    this.query = this.query || {};
    this.query[name]=value;
  },
  setParams : function (o){
    this.query = o;
  },
  serialize : function (o){
    var ar = [];
    for (var i in o){
      if (i != null && i != "") {
        if (o[i] == null || o[i] == "")
          ar.push(i);
        else
          ar.push(i + "=" + o[i]);
      }
    }
    return ar.join("&");
  },
  toStr : function (){
    return this.url + (this.query ? "?" + this.serialize(this.query) : "") 
                    + (this.anchor ? "#" + this.serialize(this.anchor) : "");
  }, 
  getHashStr : function (forceSharp){
    return this.anchor ? "#" + this.serialize(this.anchor) : (forceSharp ? "#" : "");
  }
});
window.AnchorCommand = Class.define(
  function (win) {
    win = win || window.scope || window;
    this.init();
    this.win = win;
    this.setUrl(win.location.href);
  },
  null, {
    init : function (win) {
      this.commands = {};
      this.executor = {};
      this.win = null;
      this.url = null;
      this.cmdPattern = "cmd:{$cmdName}({$param})";
    },
    setCommand : function (cmd, params) {
      this.storeCommand({
        cmdName : cmd,
        param : params
      });
    },
    storeCommand : function (cmd) {
      this.commands[cmd.cmdName] = cmd;
    },
    setUrl : function (url) {
      this.url = new URL(url);
      this.parseAnchorCommands();
    },
    getUrlObject : function () {
      return this.url;
    },
    serializeCmdToUrl : function () {
      for (var i in this.commands) {
        var tmp = this.commands[i];
        var cmd = {
          cmdName : tmp.cmdName,
          param   : (tmp.param || []).join(",")
        };
        var cmdStr = this.cmdPattern.replace(/\{\$(\w+)\}/g, function (a, b) {
          return cmd[b];
        });
        this.url.anchor = this.url.anchor || {};
        this.url.anchor[cmdStr] = null;
      }
    },
    getUrlStr : function () {
      this.serializeCmdToUrl();
      var str = this.getUrlObject().toStr();
      this.setUrl(str);
      return str;
    },
    parseAnchorCommands : function () {
      if (!this.url) return;
      var anchors = this.url._anchor;
      if (anchors == null) return;
      var cmds = anchors.match(/cmd\:(\w+)\(([^)]*)\)/);
      if (cmds == null) return;
      var cmd = cmds[1];
      var params = cmds[2];
      this.setCommand(cmd, params.split(","));
    },
    hasCommand : function (cmdName) {
      return this.commands[cmdName] != null;
    },
    hasOneOfCommands : function(names) {
      if (typeof names == "string") names = names.split(",");
      for (var i = 0; i < names.length; ++i) {
        if (this.hasCommand(names[i])) return true;
      }
      return false;
    },
    clearCommand : function (name) {
      if (this.commands[name])
      delete this.commands[name];
    },
    clearAllCommands : function () {
      this.commands = {};
    },
    refreshUrl : function () {
      this.win.location.hash = this.url.getHashStr(true);
    },
    runCommands : function (autoClear) {
      autoClear = autoClear == true;
      for (var i in this.commands) {
        var cmd = this.commands[i];
        if (this.executor[i]) {
          try {
            this.executor[i].apply(null, cmd.param);
            if (autoClear) this.clearCommand(i);
          } catch (err) {
          }
        }
      }
      if (autoClear) this.refreshUrl();
    },
    setExecutor : function (cmdName, func) {
      this.executor[cmdName] = func;
    },
    getExecutor : function (cmdName) {
      return this.executor[cmdName];
    }
  });
if (window == window.scope) {
  window.scope.Ijax = function (url, option) {
    this.url = url;
    this.option = option;
    var ifm = $("loadingIframe");
    if (ifm == null) {
      this.createLoadingIframe();
      Ijax.bind(this, url, option).delayed(100);
    } else if (!ifm.isReady || ifm.busy) {
      Ijax.bind(this, url, option).delayed(100);
    } else {
      ifm.listener = this.IjaxRespond.bind(this).delay(10);
      Event.observe(ifm, "load", ifm.listener);
      if(option.post){
        var s = $C("form");
        s.action = url;
        s.method = "post";
        s.target = "loadingIframe"; 
        document.body.appendChild(s);
        for(var i in option.post) {
          var input = $C("input");
          input.type = "hidden";
          input.name = i;
          input.value = option.post[i];
          s.appendChild(input);
        }
        s.submit();
      }else{
	  try{
        ifm.getWin().location.href = url;
	}catch(e){
		ifm.src = url;
	}
      }
      ifm.busy = true;
    }
    var onStart = this.option.onStart;
    try {
      onStart && onStart();
    } catch (err) {
    }
  }
  Ijax.prototype.createLoadingIframe = function () {
    var container = $("special");
    var html = '<iframe id="loadingIframe" name="loadingIframe" class="invisible"\
              scrolling="no"\
              src=""\
              allowTransparency="true" frameborder="0"\
              ><\/iframe>';
    new Insertion.Bottom(container, html);
    var ifm = descByIds(container, "#iframe>loadingIframe");
    function init() {
      ifm.isReady = true;
      Event.stopObserving(ifm, "load", init);
    }
    Event.observe(ifm, "load", init.bind(this));
  }
  Ijax.prototype.IjaxRespond = function() {
    var ifm = $("loadingIframe");
    try {
      var body = ifm.getWin().document.body;
      var text = body.innerHTML;
      var onComplete = this.option.onComplete;
      try {
        onComplete && onComplete(text, body);
      } catch (err) {
      }
    } catch (err) {
      var excp = this.option.onException;
      if (excp)
        excp(this, err);
      else {
      }
    } finally {
      ifm.busy = false;
      ifm.stopObserving("load", ifm.listener);
    }
  }
}
var Ijax = Class.create();
Ijax.prototype = {
    initialize : function (url, option) {
		if(!scope.IjaxQ) scope.IjaxQ = new IjaxQueue();	
		scope.IjaxQ.insertQueue(url, option);
    }	     
};
var IjaxQueue = Class.create();
IjaxQueue.prototype = {
    _queue : [],
	deleyTime : 1,//second
    initialize : function () {
		this.createLoadingIframe();
    },
    createLoadingIframe : function () {
    var container = $("special");
    var html = '<iframe id="loadingIframe" name="loadingIframe" class="invisible"\
              scrolling="no"\
              src=""\
              allowTransparency="true" frameborder="0"\
              ><\/iframe>';
    new Insertion.Bottom(container, html);
    this.ifm = descByIds(container, "#iframe>loadingIframe");
    },
    IjaxRespond : function () {
		var ifm = this.ifm;
		try{	    
			var body = ifm.getWin().document.body;
			var text = body.innerHTML;
			var onComplete = this.option.onComplete;
			try {
				onComplete && onComplete(text, body);
			} catch (err) {
			}    
		}catch(err){
			var excp = this.option.onException || null;
			if (excp)
				excp(this, err);
			else {
			};
		}finally{
			Event.stopObserving(ifm, "load", ifm.listener);
			if(this.option.post)	removeNode("IjaxForm");
			setTimeout(this.loadNext.bind(this), this.deleyTime*1000);
		};
    },
    insertQueue : function (url, option) {
		var urlData = {};
		urlData.url = url;
		urlData.option = option;
		this._queue.push(urlData);
		if(this._queue.length == 1) {
			this.loadQueue();	
		}
    },
	loadNext : function (){
		this._queue.shift();	
		this.loadQueue();
	},
    loadQueue : function () {
		var urlData = this._queue[0];
		if(!urlData){
			return ;
		};
		var nextData = this._queue[1];
		if(nextData && urlData.url == nextData.url){
			this.loadNext();
		}
		var ifm = this.ifm;
		var option = this.option;
		ifm.listener = this.IjaxRespond.bind(this);
		this.url = urlData.url;
		this.option = urlData.option;
		Event.observe(ifm, "load", ifm.listener);	
		var onStart = this.option.onStart;
		onStart && onStart();
		if(this.option.post){
			var s = $C("form");
			s.id = "IjaxForm";
			s.action = this.url;
			s.method = "post";
			s.target = "loadingIframe"; 
			document.body.appendChild(s);
			for(var i in this.option.post) {
				var input = $C("input");
				input.type = "hidden";
				input.name = i;
				input.value = this.option.post[i];
				s.appendChild(input);
			};
			s.submit();
		}else{
			try{
				ifm.getWin().location.href = this.url;
			}catch(e){
				ifm.src = this.url;
			};
		};
    }
};
window.scope.$Xml = scope.$Xml || {};
window.scope.$Xml.Parser = scope.$Xml.Parser || {
  fromString : function (str){
    var xdoc;
    if (str.indexOf("<?xml") != 0) return null;
    try{
      if ($Br.$IE){
        xdoc = new ActiveXObject("Microsoft.XMLDOM");
        xdoc.async = "false";
        xdoc.loadXML(str);
      } else if ($Br.$Gecko){
        var p = new DOMParser();
        xdoc = p.parseFromString(str, "application/xml");
      }   
    } catch (e){
    }
    return xdoc;
  },
  serialize : function (xmldoc){
    throw new Error("unimplement");
    var str="";
    return str;
  }
}
window.$ScriptLoader = {
  requestTable : {},
  request : function (url, option){
    option = option || {};
    option.charset = option.charset || "utf-8";
    var id = "scriptId_" + Math.random();
    url = new URL(url);
    url.setParam("requestId",id);
    url = url.toStr();
    this.requestTable[id] = {
      id : id,
      url : url,
      option : option
    };
    var sTag = document.createElement("script");
    sTag.id = id;
    sTag.src = url;
    sTag.charset = option.charset;
    document.body.appendChild(sTag);
  },
  response : function (id, txt){
    var entity = this.requestTable[id];
    if (entity){
      var doc = window.scope.$Xml.Parser.fromString(txt);
      try {
        entity.option.onComplete(txt, doc);
      } catch (err) {
        var oe = entity.option.onException;
        try {
          if(oe) 
            oe(txt, doc, err);
          else {
          }
        } catch (err) {}
      } finally {}
    }
  }
}
PagingLine = {
	"_instances"  : {},
	"_language"   : "",
	"_resource"   : {
		"en" : [
			"Pages (@data@) : ",
			"Go to First Page",
			"Go to Previous Page (@data@)",
			"Go to Page @data@",
			"Go to Next Page (@data@)",
			"Go to Last Page",
			"Current Page in View"
		],
		"zh-cn" : [
			"第 (@data@) 页",
			"跳转至第一页",
			"跳转至第 @data@ 页",
			"跳转至第 @data@ 页",
			"跳转至第 @data@ 页",
			"跳转至最后一页",
			"当前所在页"
		]
	},
	"Create"             : function PagingLine_Create(curPage, maxPage, lnkTpl, target) {
		function PagingLineRender(curPage, maxPage, lnkTpl, target) {
      this._target     = target || "_self";
      this._curPage    = curPage;
      this._maxPage    = maxPage;
      this._lnkTpl     = lnkTpl;
      this._style      = "default";
      this._avStyles   = ["default"];
      this._distance   = true;
      this._endpoint   = true;
      this._viewSize   = 4;
      this._viewLsPage = 0;
      this._viewRsPage = 0;
      this.SetStyle    = function PagingLineRender_SetStyle(style) {
				for (var i = 0; i < this._avStyles.length; i++) {
					if (style == this._avStyles[i]) {
						this._style = style;
						return this;
					}
				}
				return this;
			}
			this.MarkDistance = function PagingLineRender_MarkDistance(yn) {
				this._distance = yn;
				return this;
			}
			this.ToggleEndpoint=function PagingLineRender_Toggle(yn) {
				this._endpoint = yn;
				return this;
			}
			this.SetViewSize  = function PagingLineRender_SetViewSize(size) {
				size = parseInt(size);
				if (8 > size) {
					size = 8;
				} else if (size % 2) {
					size--;
				}
				this._viewSize = Math.floor(size / 2);
				return this;
			}
			this.SetRangeSize = function PagingLineRender_SetRangeSize(size) {
				return this.SetViewSize(size);
			}
			this.Render       = function PagingLineRender_Render(lang) {
				if (!arguments.length || !arguments[0].length) {
					lang = PagingLine.GetBrowserLanguage();
				} else {
					lang = lang.toLowerCase().replace(/_/g, "-");
				}
				this._viewLsPage = Math.max(1, this._curPage - this._viewSize);
				this._viewRsPage = Math.min(this._maxPage, this._curPage + this._viewSize);
				if (2 * this._viewSize + this._viewLsPage > this._viewRsPage) {
					if (1 == this._viewLsPage) {
						this._viewRsPage = Math.min(this._maxPage, 2 * this._viewSize + this._viewLsPage);
					} else if (this._maxPage == this._viewRsPage) {
						this._viewLsPage = Math.max(1, this._viewRsPage - 2 * this._viewSize);
					}
				}
				var sHTML = "<DIV" + this._getStyle() + ">" +
					this._getSummary(lang) +
					this._getFirstBtn(lang) +
					this._getPrevBtn(lang) +
					this._getContexts(lang) +
					this._getNextBtn(lang) +
					this._getLastBtn(lang) +
					"</DIV>";
				return sHTML;
			}
			this._getSummary  = function PagingLineRender__getSummary(lang) {
				if (!this._endpoint) {
					return "";
				}
				return "<LABEL" + this._getStyle("label") + ">" +
					this._getMeta(this._curPage+"/"+this._maxPage, 0, lang) +
					"</LABEL>";
			}
			this._getFirstBtn = function PagingLineRender__getFirstBtn(lang) {
				if (!this._endpoint) {
					return "";
				}
				if (1 < this._viewLsPage) {
					return "<A" + this._getURL(1) + this._getStyle("link") +
						" title='" + this._getMeta("", 1, lang) + "'>" +
						"|&lt;" +
						"</A>" + (this._distance ? "..." : "");
				}
				return "";
			}
			this._getLastBtn  = function PagingLineRender__getFirstBtn(lang) {
				if (!this._endpoint) {
					return "";
				}
				if (this._viewRsPage < this._maxPage) {
					return (this._distance ? "..." : "") +
						"<A" + this._getURL(this._maxPage) + this._getStyle("link") +
						" title='" + this._getMeta("", 5, lang) + "'>" +
						"&gt;|" +
						"</A>";
				}
				return "";
			}
			this._getPrevBtn  = function PagingLineRender__getPrevBtn(lang) {
				if (1 < this._viewLsPage) {
					return "<A" + this._getURL(this._curPage - 1) + this._getStyle("link") +
						" title='" + this._getMeta(this._curPage - 1, 2, lang) + "'>" +
						"&lt;" +
						"</A>";
				}
				return "";
			}
			this._getNextBtn  = function PagingLineRender__getNextBtn(lang) {
				if (this._viewRsPage < this._maxPage) {
					return "<A" + this._getURL(this._curPage + 1) + this._getStyle("link") +
						" title='" + this._getMeta(this._curPage + 1, 4, lang) + "'>" +
						"&gt;" +
						"</A>";
				}
				return "";
			}
			this._getContexts = function PagingLineRender__getContexts(lang) {
				var sHTML = "";
				for (var i = this._viewLsPage; i <= this._viewRsPage; i++) {
					if (i == this._curPage) {
						sHTML += "<LABEL" + this._getStyle("current") +
							" title='" + this._getMeta("", 6, lang) + "'>" +
							this._curPage +
							"</LABEL>";
					} else {
						sHTML += "<A" + this._getURL(i) + this._getStyle("link") +
							" title='" + this._getMeta(i, 3, lang) + "'>" +
							i +
							"</A>";
					}
				}
				return sHTML;
			}
			this._getMeta     = function PagingLineRender__getMeta(data, idx, lang) {
				return PagingLine.GetResource(idx, lang).replace(/@data@/g, data);
			}
			this._getStyle    = function PagingLineRender__getStyle(suffix, quote) {
				if (1 > arguments.length) {
					suffix = "";
				} else {
					suffix = "." + suffix;
				}
				if (2 > arguments.length) {
					quote = "'";
				}
				return " class=" + quote +
					"paging-line" + suffix +
					" paging-line.style-" + this._style + suffix +
					quote;
			}
			this._getURL      = function PagingLineRender__getURL(lnkPage, quote) {
				if (1 > arguments.length) {
					lnkPage = this._maxPage;
				}
				if (2 > arguments.length) {
					quote = "'";
				}
				return " href=" + quote +
					this._lnkTpl.replace(/@page@/g, lnkPage) +
					quote + " target=" + quote + this._target + quote;
			}
		}
		curPage = parseInt(curPage);
		maxPage = parseInt(maxPage);
		if (1 > maxPage) {
			maxPage = 1;
		}
		if (1 > curPage) {
			curPage = 1;
		} else if (curPage > maxPage) {
			curPage = maxPage;
		}
		return new PagingLineRender(curPage, maxPage, lnkTpl, target);
	},
	"GetBrowserLanguage" : function PagingLine_GetBrowserLanguage() {
		if (!this._language.length) {
			this._language = (document.all
				? navigator.browserLanguage
				: navigator.language).toLowerCase();
		}
		return this._language;
	},
	"GetResource" : function PagingLine_GetResource(idx, lang) {
		if (!lang.indexOf("en")) {
			lang = "en";
		}
		if (!this._resource[lang] || this._resource[lang].length <= idx) {
			return "";
		}
		return this._resource[lang][idx];
	}
}
if (window == window.scope){
  window.scope.$UrlPattern = {
    articlePreview : "http://blog.sina.com.cn",
    friendList     : "http://blog.sina.com.cn/html/fl.html",
    articleSingle  : "http://blog.sina.com.cn/s/index_{$id}_{$page}.html",
    comment        : "http://blog.sina.com.cn/s/comment_{$id}_{$page}.html",
    commentsNum    : "http://blogcmn.sinajs.cn/cms?{$aid}",
    circle         : "",
    album_pic      : "http://blog.sina.com.cn/s/albumpiclist_{$album_id}_{$page}.html",
    albumList      : "http://blog.sina.com.cn/s/albumindex_{$id}.html",
    gbook          : "http://blog.sina.com.cn/s/gbook_{$id}_{$page}.html",
    gbookAdmin     : "http://my.blog.sina.com.cn/myblog/gbook/newgbook.php?uid={$uid}&page={$page}", 
    articleList    : "http://blog.sina.com.cn/s/alist_{$id}_{$page}.html",
    nickName       : "http://blogui.sinajs.cn/ui?t=t&{$uid}",
    uic            : "http://util.blog.sina.com.cn/ui?t=n&{$uid}",
    get : function(name, data, forceRefresh){
      var ptn = scope.$UrlPattern[name];
      if (!ptn) throw new Error ("no such pattern defined with name : " + name);
      if (forceRefresh) {
        ptn += ptn.indexOf("?") > -1 ? "&" : "?";
        ptn += new Math.random();
      }
      return scope.$UrlPattern.transform(ptn , data);   
    }, 
    transform : function (ptn, data){
      var str = ptn.replace(/\{\$([\w\d]+)\}/g, 
            function (a, b){ return data[b] || ("{$" + b + "}"); });
      return str;
    }
  }
  scope.$Url = scope.$UrlPattern.get;
}
window.scope.$Layout = {
  needUpdateArray : true,
  needUpdateHash  : true,
  cache_compArray : null,
  cache_compHash  : null,
  getCompsInPage : function (forceUpdate){
    var needUp = scope.$Layout.needUpdateArray || forceUpdate;
    if (!needUp) {
      return scope.$Layout.cache_compArray;
    }
    var page = window.scope;
    var comps = {};
    $R(1, 4).each(function (i){
      var cid = "column_" + i;
      var col = page.byId(cid);
      var comArray = getChildrenByClass(col, "component");
      comps[cid] = comArray;
    });
    scope.$Layout.cache_compArray = comps;
    scope.$Layout.needUpdateArray = false;
    return comps;
  },
  getCompsHashById: function (forceUpdate){
    var needUp = scope.$Layout.needUpdateHash || forceUpdate;
    if (!needUp) {
      return scope.$Layout.cache_compHash;
    }
    var page = window.scope;
    var comps = page.$Layout.getCompsInPage(forceUpdate);
    var hash = {};
    $R(1, 4).each(function (id){
      var col = comps["column_"+id];
      col.each(function (e){
        var id = e.id;
        var dbid = Element.Methods.readAttribute(e, "dbid");
        if (dbid != null && dbid != "" && dbid.indexOf("{") != 0){        //has a dbid
          id = id + " " + dbid;
        }
        hash[id] = e;
      });
    });
    scope.$Layout.cache_compHash = hash;
    scope.$Layout.needUpdateHash = false;
    return hash;
  },
  getCompConfig : function (){
    var layout;
    try {
      layout = window.scope.config.layout;
      var newLayout = {
        column_1 : layout.column_1.concat(), 
        column_2 : layout.column_2.concat()
      }
      var ly = newLayout.column_1;
      if (scope.config.theme == 4) ly = newLayout.column_2;
      ly.push("blog_counter", "blog_feeds_addr");
    } catch (err) {
      layout = null;
    }
    return newLayout;
  },
  moveComp : function (comp, option){
    var page = window.scope;
    comp = page.$(comp);
    if (!comp) return;
    var tar;
    if (option.before || option.after) {
      tar = page.$(option.before || option.after);
      if (!tar) return;
       if (option.before){            //insert before
         tar.parentNode.insertBefore(comp, tar);
       } else if (tar.nextSibling){   //insert after
         tar.parentNode.insertBefore(comp, tar.nextSibling);
       } else {                       //insert after
         tar.parentNode.appendChild(comp);
       }
    } else {                          
      var pos = option.position;
      if (!pos) return;
      var comps = getChildrenByClass(page.byId(pos.col),  "component");
      tar = comps[pos.idx];
      if (!tar) {
        page.byId(pos.col).appendChild(comp);
      } else {
        tar.parentNode.insertBefore(comp, tar);
       }
    }
  },
  removeComp : function (comp){
    comp = window.scope.$(comp);
    if (comp) {
      if (comp.comp) comp.comp.dispose();
      else comp.remove();
    }
  },
	checkConfig : function (){
		var page = window.scope;
		var cid = page.config.theme == 4 ? 2 : 1; 
		var compContain = byId("column_" + cid);
		var subs = navigator.appName == "Microsoft Internet Explorer" ? compContain.children : compContain.childNodes;
		var _comps = new Array();	
		window.foreach(subs, function(e){
			if(e.nodeType == 1)	_comps.push(e.id);
		});
		_comps = ArrayWithout(_comps,"blog_counter", "blog_feeds_addr");
		var cfg = page.config.layout["column_"+cid];
		return _comps.join("|") == cfg.join("|");
	},
  layoutByConfig : function (){
    var page = window.scope;
	if (scope.$Layout.checkConfig()){
		trace("re-layout is ABOUT!!!")
		return;
	}
    if (page.config.theme == 4){ 
      var cl1 = page.$("column_1");
      var cl2 = page.$("column_2");
      cl1.setStyle({width:"550px"});
      cl2.setStyle({width:"210px"});
    }
    var comps = page.$Layout.getCompsHashById();
    var config = page.$Layout.getCompConfig();
    if (!config) return;
    for (var i in comps){
      var cmp = comps[i];
      var cont = page.descByIds(cmp, "#>componentContent");
      var ss = cont.getElementsByTagName("script");
      for (var j=0; j<ss.length; ++j){
        ss[j].parentNode.removeChild(ss[j]);
      }
    }
    for (var c in config){
      var colm = config[c];
      colm.each(function (composedId, i){
        var compsArray= getChildrenByClass(page.byId(c),  "component");
        var comp = comps[composedId];
        if (comp == null) return;
        if (compsArray[i] != comp) page.$Layout.moveComp(comp, {position:{col:c, idx:i}});
        comps[composedId] = null;
      });
    }
    for (var i in comps){
      if (comps[i] != null) page.$Layout.removeComp(comps[i]);
    }
  }
}
if (window == window.scope){
  window.scope.$PV = window.scope.$PV || {}
  Object.extend(window.scope.$PV, {
    show : function (){
      if (scope.$PV.data == null) {
        scope.$PV.show.delayed(2000);
        return;
      }
      window.scope.$PV.display(null, window.scope.$PV.data);
    },
    display : function (text, data) {
      try {
        data = data || eval("(" + text.replace(/[\s\t\r\n]/g, "") + ")");
      } catch (e) {
        alert("parse json error while fetching PV data :" + e);
      }
      window.scope.$PV.setBlogViews.apply(window.scope, [data.totalPV]);
      try {
        window.scope.$PV.setArticleViews(data.articlesV.split(","));
      } catch (e) {
      }
    },
    setBlogViews : function (num){
      var id = "blogPV";
      num = (num + "").split("");
      var pv = byId(id);
      if (!pv) return; 
	  var countTheme = window.scope.config.countTheme;
	  var len = num.length;
	  var str ="";
	  while (len < 5){
		num.unshift("0");
		len = num.length;
	  }
	  for(var i=0;i<len;i++){
		var n = num[i];
		str += "<img title='"+n+"' alt='"+n+"' src='http://image2.sina.com.cn/blog/tmpl/v3/images/counter/"+ countTheme+"/"+num[i]+".gif' />";
	  }
	  pv.innerHTML = str;
    },
    setArticleViews : function (nums){
      cnt = scope.getArticleContainer();
      if (!cnt) return;            
      var lis = cnt.childNodes, len = lis.length;
      for (var i=0; i<len; ++i){
        if (lis[i].nodeType != 1) continue;
        var numNode = descByIds(lis[i], "#span>viewNum");
        var num = nums.shift();
        numNode && (numNode.innerHTML = num || 0);
      }
    }
  })
  window.scope.$SetPV = function (o){
    window.scope.$PV.data = o;
  };
} else {                                
  window.$SetPV = function (o){
    window.scope.$SetPV(o);
  }
}
if (window == scope){
  scope.$IF = {
    systemDialogIframeOnload : function () {
      var win = this.getWin();
      try{          win.location.href;
      } catch (e) { return; }
      var title = "";
      try{ title = win.document.title;
      } catch (e){}
      if (title != "")  scope.showSysDialog(title);
      else              scope.showSysDialog("系统提示");
      scope.$IF.watchResult.apply(this);
    },
    watchIframe : function (ifm, handler) {
      Event.observe(ifm, "load", scope.$IF.watchResult.bind(ifm, handler));
    },
    watchResult : function (handler){
      handler = handler || scope.Handler;
      var win = this.getWin();
      var result = scope.$IF._readResult(win);
      if (result) {
        var op = handler[result.operation] || scope.Handler[result.operation];
        if (op) {
          var func = (op[result.result] || op.defaultHandler).apply(this,[result]);
        }
      }
    },
    _readResult : function (win){
      try{
        var e = win.$("instruction");
        if (!e) return null;
        var r = {}
        var attrs = ["operation","result"];
        attrs.each(function (t){
          r[t] = Element.readAttribute(e, t);
        });
        r.subInstruction = e.childArray().hashBy("id");
        r.text = e.next("#text");
        r.text = r.text ? r.text.innerHTML : "";
        return r;
      } catch (e){
      }
    },
    autoSizeMe : function (){
      try{
        this.contentWindow.autoSize();
      } catch (e){
      }
    }
  };
  scope.Handler = {
    login : {
      succ : function (){
        hideSysDialog();
        this.getWin().location.href="/js/blank.html";
      }
    },
    checkLogin : {
      defaultHandler : function (){
        scope.loadUserInfo();
      }
    },
    refreshTop : {
      defaultHandler : function (){
        scope.location.reload();
      }
    },
    resizeDialog : {
      defaultHandler : function (res){
        var width = res.subInstruction.width.readAttribute("value").toInt();
        var height = res.subInstruction.height.readAttribute("value").toInt();
        scope.setDialogSize(width, height);
      }
    }
  };
}
if (window == window.scope){
  window.scope.showSysDialog = function (title) {
	title = title || "系统提示";
    var tmpRel = {};
    IframeBlock.init("special", "systemDialog", tmpRel);
    $("special").showBlock();
    $("systemDialog").middle();
	if(document.all){
		byId("systemDialog").children[0].children[0].innerHTML = title || "系统提示";
	}
	else{
		byId("systemDialog").childNodes[1].childNodes[1].innerHTML = title || "系统提示";
	}
    var block = $("systemDialog_iframeBlock");
    var content = $("systemDialog");
    content.style.zIndex = 10000;
    block.style.zIndex = 5000;
    block.style.position = "absolute";
    block.style.left = content.style.left;
    block.style.top = content.style.top;
    block.style.width = parseInt(content.clientWidth) + 2 + "px";
    block.style.height = parseInt(content.clientHeight) + 30 + 2 + "px";
  }
  window.scope.hideSysDialog = function () {
	var objIframe = byId("mySina_Host");
	if(objIframe!=null){
		objIframe.removeNode ? objIframe.removeNode(true) : objIframe.parentNode.removeChild(objIframe);
		objIframe = byId("systemIframe");
		objIframe.style.display = "";
		objIframe = byId("systemDialogFoot");
		objIframe.style.display = "";
		objIframe = byId("systemDialog_iframeBlock");
		objIframe.style.display = "";
	}
    scope.$("special").hide();
  }
  window.scope.setDialogSize = function (w, h) {
    var dlg = $("systemDialog");
	var chdNode = dlg.children || dlg.childNodes;
    var bar = document.all ? chdNode[0] : chdNode[1];
	var barHeight = bar.offsetHeight;
    var sysIframe = document.all ? chdNode[1] : chdNode[3];
	sysIframe = $("systemIframe");
    var foot = document.all ? chdNode[2] : chdNode[5];
	var footHeight = foot.offsetHeight;
    dlg.setStyle({
      width  : w + "px",
      height : h + barHeight + footHeight + "px"
    });
    sysIframe.setStyle({
      height : h + "px"
    });
    dlg.middle();
  }
  window.scope.showStatus = function (string, color) {
    var e = $("status");
    if (string == null) {
      e.hide();
    } else {
      color = color || "red";
      e.show();
      e.innerHTML = string;
      e.style.backgroundColor = "#" + color;
    }
  }
};
var $Br = (function () {
  var g = {};
  var ua = navigator.userAgent;
  g.$IE = (navigator.appName == "Microsoft Internet Explorer");
  g.$IE5 = g.$IE && (ua.indexOf('MSIE 5') != -1);
  g["$IE5.0"] = g.$IE && (ua.indexOf('MSIE 5.0') != -1);
  g.$IE6 = g.$IE && (ua.indexOf('MSIE 6') != -1);
  g.$IE7 = g.$IE && (ua.indexOf('MSIE 7') != -1);
  g.$Gecko = ua.indexOf('Gecko') != -1;
  g.$Safari = ua.indexOf('Safari') != -1;
  g.$Opera = ua.indexOf('Opera') != -1;
  g.$Mac = ua.indexOf('Mac') != -1;
  g.$NS7 = ua.indexOf('Netscape/7') != -1;
  g.$NS71 = ua.indexOf('Netscape/7.1') != -1;
  if (g.$Opera) {
    g.$IE = true;
    g.$Gecko = false;
    g.$Safari = false;
  }
  return g;
})();
function setClipBoard(text) {
  if (window.clipboardData) {
    return (window.clipboardData.setData("Text", text));
  }
  return false;
}
function addToFavorites(urlAddress, pageName) {
  if (window.external) {
    window.external.AddFavorite(urlAddress, pageName)
  } else {
    alert("Sorry! Your browser doesn't support this function.");
  }
}
function load_chk_img(s) {
  var stamp = new Date().getTime();
  byId(s).src = 'http://vlogin.blog.sina.com.cn/myblog/checkwd_image.php?' + stamp;
}
function callFlash() {
  byId('play_img').src = 'http://image2.sina.com.cn/blog/tmpl/v3/images/play_img.gif';
  window.document.mp3_player.SetVariable("isPlay", "1");
  byId('checkwd').value = '';
  byId('checkwd').focus();
} 
function dw(s) {
  document.write(s);
}
function dwSwf(_sName, _sSrc, _sWidth, _sHeight, _sMode, _aValue) {
  var sValue = '';
  var aFlashVars = [];
  if (_aValue) {
    for (var key in _aValue) {
      aFlashVars[aFlashVars.length] = key + "=" + _aValue[key];
    }
    sValue = aFlashVars.join('&');
  }
  _sMode = _sMode ? 'wmode="transparent"' : '';
  if(_sName == "calendar"){
	return '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="' + _sWidth + '" height="' + _sHeight + '" id="' + _sName + '" align="middle" ><param name="movie" value="' + _sSrc + '?' + sValue + '" /><embed name="' + _sName + '" src="' + _sSrc + '" ' + _sMode + ' quality="high" align="top" salign="lt" allowScriptAccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="' + _sWidth + '" height="' + _sHeight + '" flashVars="' + sValue + '"><\/embed></object>';
  }else{
	return '<embed id="' + _sName + '" name="' + _sName + '" src="' + _sSrc + '" ' + _sMode + ' quality="high" align="top" salign="lt" allowScriptAccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="' + _sWidth + '" height="' + _sHeight + '" flashVars="' + sValue + '"><\/embed>';
  }
}
function ResizeSWF(nWidth,  nHeight) {
  var swf = byId("music");
  var obj = byId("musicFlash");
  swf.style.width = nWidth;
  swf.style.height = nHeight;
  obj.width = nWidth;
  obj.height = nHeight;
}
function ResizeFlash(flashId,  layerId,  nWidth,  nHeight) {
  var swf = byId(layerId);
  var obj = byId(flashId);
  swf.style.width = nWidth;
  swf.style.height = nHeight;
  obj.width = nWidth;
  obj.height = nHeight;
}
function fixImageSize(img) {
  var parent = img.parentNode;
  var wth = parent.offsetWidth;
  img.style.width = "auto";
  if (img.offsetWidth > wth) img.style.width = "100%";
  parent.style.display = "";
}
function isRecentUpdate(postDate){
    var ins = 86400000;
    var todayDate = new Date().getTime();
	return Math.abs(todayDate - postDate*1000) < ins;
}
function getAuthorUID(){
  var AuthorInfo = getCookie("nick");
  scope.AuthorUID = AuthorInfo ? AuthorInfo.match(/\(\d{5,10}\)/g)[0].replace(/\(|\)/g,"") : null;
  return scope.AuthorUID;
}
function getCookie(name)
{
  var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
  if(arr != null) return unescape(arr[2]); return null;
}
 var $User = (function () {
   var g = {};
   try {
     g.isLogin = function (){
       return  !!window.scope.$UID;
     }
     g.isMaster = function () {
       return window.scope.$UID && window.scope.uid == window.scope.$UID;
     }
   }
   catch (e) {
     g.isLogin = function () {
       return false;
     }
     g.isMaster = function () {
       return false;
     }
   }
   return g;
 })();
var $Drag = {
  init : function (_root,_handle,xLock,yLock) {
    var o = this;
    var blk = byId(_root) || _root;
    blk.hdl = byId(_handle) || _handle;
    if(blk.hdl == null || _handle == undefined) blk.hdl = o.blk;
    blk.hdl.style.cursor = "move";
    blk.hdl.onmousedown = start;
    blk.onDragStart = new Function()
    blk.onDrag = new Function()
    blk.onDragEnd = new Function()
    function start (e) {
      var o = $Drag; v = blk;
      v.oX = o.getX(e);
      v.oY = o.getY(e);
      v.depth = v.style.zIndex;
      v.style.zIndex = 10000;
      v.rL = v.getLeft();
      v.rT = v.getTop();
      v.onDragStart(v.rL,v.rT);
      document.onmousemove = drag;
      document.onmouseup   = end;
      return false;
    };
    function drag (e) {
      var o = $Drag; var v = blk;
      var nX = o.getX(e);
      var nY = o.getY(e);
      var ll = v.rL + nX - v.oX;
      var tt = v.rT + nY - v.oY;
      if(!xLock)  v.style.left = ll + 'px';
      if(!yLock)  v.style.top  = tt + 'px';
      v.onDrag(ll,tt);
      return false;
    };
    function end () {
      v.style.zIndex = v.depth ;
      v.onDragEnd(parseInt(v.style.left),parseInt(v.style.top));
      document.onmousemove  = null;
      document.onmouseup    = null;
    };
  },
  fixE : function (e) {
    if (typeof e == 'undefined') e = window.event;
    if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
    if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
    return e;
  },
  getX : function (e){
    return this.fixE(e).clientX;
  },
  getY : function (e){
    return this.fixE(e).clientY;
  }
}
function getWinSize(_target) {
  var windowWidth, windowHeight;
  if(_target) target = _target.document;
  else  target = document;
  if (self.innerHeight) { // all except Explorer
    if(_target) target = _target.self;
    else  target = self;
    windowWidth = target.innerWidth;
    windowHeight = target.innerHeight;
  } else if (target.documentElement && target.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = target.documentElement.clientWidth;
    windowHeight = target.documentElement.clientHeight;
  } else if (target.body) { // other Explorers
    windowWidth = target.body.clientWidth;
    windowHeight = target.body.clientHeight;
  }
  return {width:parseInt(windowWidth),height:parseInt(windowHeight)};
}
function $C(tagName) {
    return document.createElement(tagName)
};
function $addEvent2(elm, func, evType, useCapture) {
  elm = byId(elm);
  if(typeof useCapture == 'undefined') useCapture = false;
  if(typeof evType == 'undefined')  evType = 'click';
        if (elm.addEventListener) {
            elm.addEventListener(evType, func, useCapture);
            return true;
        }
        else if (elm.attachEvent) {
            var r = elm.attachEvent('on' + evType, func);
            return true;
        }
        else {
            elm['on' + evType] = func;
        }
};
function removeNode(s){
  if(byId(s)){
    byId(s).innerHTML = '';
    byId(s).removeNode ? byId(s).removeNode() : byId(s).parentNode.removeChild(byId(s));
  }
}
function insertAfter (newElement, targetElement) {
  var parent = targetElement.parentNode;
  if(parent.lastChild == targetElement) {
    parent.appendChild(newElement);
  } else {
    parent.insertBefore(newElement, targetElement.nextSibling);
  }
}
function listArticleByDate(uid,date){
	try{
		byId("Content_ArticlePreview").src = "http://blog.sina.com.cn/s/indexbydate_" + uid + "_" + date + ".html";
		byId("outBound").scrollTop = 0;
	}catch(e){
	}
}
function calendar_DoFSCommand(command,args){
	if(command == "readArticleListByDate"){
		listArticleByDate(window.scope.uid,args);
	}
}
SpaceUserCard.setSendBtn(invite_friend);
SpaceUserCard.setOtherClose(true);
function showCard(uid,e,l, w, logType){
	SpaceUserCard.show(uid);
  if(logType == "blog_visit") {
	if(scope.pageMark == "article")	sendCommonLog("rela_visiter_card","articlenewone");
  } 
}
function send_message_to(_uid){
  window.scope.bcDialog.show("http://my.blog.sina.com.cn/myblog/message/send_message_static.php?toid=" + _uid, 278, 100);
  window.scope.bc.hidden();
}
function send_message(){
  window.scope.bcDialog.show("http://my.blog.sina.com.cn/myblog/message/send_message_static.php?toid=" + window.scope.uid, 278, 100);
  window.scope.bc.hidden();
}
function invite_friend(e){
  window.scope.bcDialog.show("http://my.blog.sina.com.cn/friend/add_friend_static.php?opid=" + (e!=null?e:window.scope.uid), 278, 258);
  SpaceUserCard.hidden(true);
  window.scope.bc.hidden();
}
function setArticleContentSize(sClass) {
  var clz = "m";
  if(sClass == "s")  clz="smallSize";
  if(sClass == "m")  clz="middleSize";
  if(sClass == "b")  clz="bigSize";
  $$('div#articleContentArea').inject([], function(m, e){
    m.push(e.down("#articleContent"));
    return m;
  })[0].className = clz;
}
function updateBlogui(){
  var url = "http://util.blog.sina.com.cn/ui?t=n&"+window.scope.uid+"&"+Math.random();    
  new Ijax(url,{
    onComplete : function (text){ 
      var o = text.replace(/;$/,"").j2o()[0];
      if(o)  
      try{    
        byId("blogName").innerHTML = o.blogtitle;
        descByIds(by("blogName"),"#a>").innerHTML = o.nick;
      }catch(e){}
    }
  });
}
function sendLog(_type, type) {
     var arg;
     if (!type)
     {
      arg = "fl";
     }else{ 
      arg = type;
     }  
     //addHTML(document.body, "<img style='display: none;' src='http://stat.blog.sina.com.cn/i.html?"+ arg +"&" + _type + "&nick&" + new Date().valueOf() + "'>");
	 return false;  
}
function sendCommonLog() {
	if(arguments.length == 0)	return false;
	var args = "";
	for(var i=0;i<arguments.length;i++){
		args += arguments[i] + "&";
	}
	//var logImg = new Image();
	//logImg.src ="http://stat.blog.sina.com.cn/i.html?"+args+new Date().valueOf();
   	return false;  
}
function showMyRecord(e){
	try{
		parent.showMyRecordDiv(e);
	}catch(e){
		showMyRecordDiv(e);
	}
	return false;
}
function gotoMessage()
{
	window.open("http://blog.msg.mail.sina.com.cn","_blank");
}
function goto()
{
	window.location.href="/logout.php";
}
function showMSG (sCt) {
	alert("unimplement");
	return;
	document.getElementById("ctMSG").style.display = "";
	document.getElementById("ctMSGNUM").innerHTML = sCt;
}
function hidMSG () {
	alert("unimplement");
	return;
	document.getElementById("ctMSG").style.display = "";
	document.getElementById("ctMSGNUM").innerHTML = "";
}
if (window == scope) {
  scope.isLogin = function (){
    var sCookie = document.cookie.toString().toLowerCase();
    return sCookie.indexOf("nick") != -1
  }
  scope.loadUserInfo = function () {
    if(scope.isLogin()) {
      new window.scope.Ijax(window.scope.$LoginInfoUrl, {
        onComplete:function (text) {
          var skripts = text.extractScripts();
          var html = text.stripScripts();
          window.scope.$Visitor = { html  : html };
          scope.tryToSetAdminLinks();
		  setUpgrade();
          initTpl();
          scope.initManageComp();
          scope.replaceHomeUrl();
          skripts.each(function(s) {
            window.scope.eval(s);
          });
          get_msgbox_popup();
        }});
    }
    else {
      var ifm = scope.descByIds(scope.document, "#blog_feeds#div>adminLinks");
      var holder = descByIds(ifm, "#guestPanel");
      holder.className = "";
      var loadText = descByIds(ifm, "#loadingText");
      loadText.className = "invisible";
    }
  }
  scope.tryToSetAdminLinks = function () {
    scope.log("tryToSetAdminLinks");
    var holder = scope.descByIds(scope.document, "#blog_feeds#div>adminLinks");
    holder.innerHTML = window.scope.$Visitor.html;
  }
  scope.toggleAdminUtil = function (){
    window.scope.toggleEditArticle();
    window.scope.toggleDeleteComment();
  }
  scope.isAdmin = function (){
    return checkAuthor();
  }
  scope.toggleEditArticle = function (){
    function toggleEditLink(edt, t){
      if (t) {
        edt.className = "";
      } else {
        Element.Methods.addClassName(edt, "invisible");
        edt.className = "invisible";
      }
    }
    try{
      var aCnt = scope.getArticleContainer();
      var lis = aCnt.getElementsByTagName("li"),isAdmin = scope.isAdmin();
      for (var i=0,len=lis.length; i<len; ++i){
        var edt = descByIds(lis[i], "#div>articleUtil#edit");
        toggleEditLink(edt, isAdmin);
      }
    } catch (e){
    }
  }
  scope.toggleDeleteComment = function (){
    try{
      var arWin = scope.getArticleWindow();
      var cmIf = arWin.byId("contentIframeLink");
      if (cmIf == null) return;
      var isAdmin = scope.isAdmin();
      var win =cmIf.contentWindow; 
      var deleteLinks = win.document.getElementsByTagName("li");
      for (var i=0,len=deleteLinks.length;i<len;++i){
        var l = deleteLinks[i];
        l = descByIds(l,  "#commentContentArea#commentDell#delete");
        if (isAdmin) Element.Methods.removeClassName(l,  "invisible");
        else Element.Methods.addClassName(l,  "invisible");
      }
    } catch (e){
      window.scope.log(e);
    }
  };
  scope.setProcessTip = function () {
    var option = {
      defaultProgress : "正在保存...",
      defaultComplete : "保存成功!",
      defaultError : "保存失败!"
    };
    window.scope.globalTip = new $ProcessTip(document.body, option);
    var tipobj = window.scope.globalTip.comp;
    tipobj.style.position = "absolute";
    var s = getWinSize().width;
    tipobj.style.left = (s+770)/2 + "px";
    tipobj.style.top = "15px";
  }
  scope.initManageComp = function (){
    if($getPageId() == "article")	return;
    scope.$ManaComp = new ManageComponent();
    Event.observe("manage_comp_btn","click",function (){
      scope.$ManaComp._show();
      return false;
    })
    if(window.location.hash == "#diyblog"){
      scope.$ManaComp._show();
    }
  }
  scope.replaceHomeUrl = function (){
    if($("homePage")){
      $("homePage").href= $("homePage").href+"?edit";
    }
    if($("home")){
      $("home").href= $("home").href;
    }
    if($("main_home")){
      $("main_home").href= $("main_home").href+"?edit";
    }
  }
}
if(window == window.scope){
   if(window.scope.Dialog == null) {
     window.scope.Dialog = {
       show: function (sURL, nWidth, nHeight) {
         nWidth = parseInt(nWidth);
         nHeight = parseInt(nHeight);
         sTitle = "数据载入中...";
         window.scope.showSysDialog(sTitle);
         this.resize(nWidth, nHeight);
         $("systemIframe").contentWindow.location.href=sURL;
       },
	   hidden: function () {
         window.scope.hideSysDialog();
       },
       resize: function (nWidth, nHeight) {
         window.scope.setDialogSize(nWidth, nHeight);
       }
	 };
   }
}
if(window == window.scope) {
	function getPageSize() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		}
		else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		}
		else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		}
		else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		}
		else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		}
		else { 
			pageHeight = yScroll;
		}
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		}
		else {
			pageWidth = xScroll;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	}
	var bcDialog = {};
	bcDialog.show = function (sURL, nWidth, nHeight) {
		var pageSize = getPageSize();
		document.getElementById("bcDialogFrameBox").innerHTML = '<iframe src="" id="bcDialogFrame" style="position:absolute; top: 0px; left: 0px;" frameBorder="0" scrolling="no"></iframe>';
		document.getElementById("bcDialogBox").style.display = "";
		document.getElementById("bcDialogShadow").style.width = pageSize[0] + "px";
		document.getElementById("bcDialogShadow").style.height = pageSize[1] + "px";
		document.getElementById("bcDialogFrame").style.left	= (pageSize[0] - nWidth)/2 + "px";
		document.getElementById("bcDialogFrame").style.top	= document.body.scrollTop + (pageSize[3] - nHeight) / 2 + "px";
		document.getElementById("bcDialogFrame").style.width = nWidth + "px";
		document.getElementById("bcDialogFrame").style.height = nHeight + "px";
		byId("bcDialogFrame").src = sURL;
	};
	bcDialog.show2 = function (sURL, nWidth, nHeight) {
		var bcwin = window.open(sURL, "bc_window","resizable=no, location=yes, status=yes, width=" + nWidth + ", height=" + nHeight + ", left=" + (window.screen.availWidth - nWidth) / 2 + ", top="+(window.screen.availHeight - nHeight) / 2+", location=no");
	};
	bcDialog.hidden = function () {
		document.getElementById("bcDialogBox").style.display = "none";
	}
	bcDialog.reSize = function (nWidth, nHeight) {
		var pageSize = getPageSize();
		document.getElementById("bcDialogFrame").style.left	= (pageSize[0] - nWidth)/2 + "px";
		document.getElementById("bcDialogFrame").style.top	= document.body.scrollTop + (pageSize[3] - nHeight) / 2 + "px";
		document.getElementById("bcDialogFrame").style.width = nWidth + "px";
		document.getElementById("bcDialogFrame").style.height = nHeight + "px";
	}
}
function include(jsfile, handle) {
	var ja = new Array();
	var jsHash = {};
	if(typeof jsfile == 'string') ja.push(jsfile);
	else ja = jsfile.slice(0);
	var ua = navigator.userAgent.toLowerCase();
	var isIE = /msie/.test(ua);
	var isOpera = /opera/.test(ua);
	var isMoz = /firefox/.test(ua);
	for(var i=0;i<ja.length;i++) {
		jsHash['j'+i] = false;
		var js = $C('script');
		js.type = 'text/javascript';
		js.src = ja[i];
		js.id = 'j' + i;
		if(isIE) js.onreadystatechange = function() {
			if(this.readyState.toLowerCase() == 'complete' || this.readyState.toLowerCase() == 'loaded'){
				jsHash[this.id] = true;
			}
		}
		if(isMoz) js.onload = function() {
			jsHash[this.id] = true;
		}
		if(isOpera) jsHash['j' + i] = true;
		document.body.appendChild(js);
	}
	var loadTimer = setInterval(function(){
		for(var i=0;i<ja.length;i++) {
			if(jsHash['j'+i] == false) return;
		}
		clearInterval(loadTimer);
		eval(handle)();
	},100);
}
function get_msgbox_popup() {
	var msg_box_url   = 'http://my.blog.sina.com.cn/login/message_count.php?'+ window.scope.$UID;
	var mail_info_url = 'http://hint.sinamail.sina.com.cn/mailproxy/mail.php';
	var _source = new Array();
	_source.push(msg_box_url);
	_source.push(mail_info_url);
	include(_source, show_msgbox_popup);
}
function show_msgbox_popup() {
	if(typeof(blog_msg_count) == 'undefined' ||  blog_msg_count == 0)	return;
	var sina_mail_count = sinamailinfo.unreadmail;
	var full_msg = "您有新纸条" + blog_msg_count + "个，新邮件" + sina_mail_count + "个";
	$('tdMSG').innerHTML = full_msg;
	var ajst = (String(blog_msg_count).length + String(sina_mail_count).length - 2)*6;
	$('ctMSG').style.width = 178 + ajst + "px";
	$('ctMSG').style.display = '';
}
if (scope == window){
  scope.getArticleWindow = function (){
    if (scope.isArticlePage()){
      return scope;
    } else if (scope.isFirstAP()){
      return scope;
    } else return scope.$("blog_feeds").down("iframe").contentWindow;
  }
  scope.getConIF = function (){
    return scope.byId("Content_ArticlePreview");
  }
  scope.getArticleContainer = function (useIframe){
    useIframe = useIframe == true;
    var ifm = scope.descByIds(scope.document, "#blog_feeds#iframe>Content_ArticlePreview");
    try{
      return ifm.contentWindow.byId("articleContainer");
    } catch (e){
    }
    var ac = scope.byId("articleContainer"); 
    if (ac) return ac;
    if (scope.isFirstAP() || scope.isArticlePage() || !useIframe){   
      return scope.byId("articleContainer"); 
    } else {
      var ifm = scope.descByIds(scope.document, "#blog_feeds#iframe>Content_ArticlePreview");
      return ifm.contentWindow.byId("articleContainer");
    }
  };
  scope.switchContainerToIframe = function (){
    if ($getPageId() != "blog") return false;
    var ifm = scope.$("blog_feeds").down("iframe");
    var div = scope.$("articleContainer"); 
    div && div.remove();
    div = scope.byId("articlePageDiv");
    div && div.parentNode.removeChild(div);
    ifm.style.display="block";
    scope.autoSize(ifm);
  };
  scope.isFirstAP = function (){
    if ($getPageId(scope) != "blog") return false;
    var cmd = scope.createAnchorCommand();
    return !cmd.hasOneOfCommands("apv"); 
  };
  scope.isArticlePage = function (){
    return ($getPageId() == "article");
  }
}
if (window == window.scope){
	window.scope.$Template = {
    blog_visit :
	'<li>\
		<div id="imageHolder"><span id="hotIcon" title="该博客最近有新文章"  class="icon star center #{visible}">&nbsp;<\/span><img id="image" title="查看个人名片" src="#{imageUrl}" title="#{imageAlt}" onerror="#{imgError}" onclick="#{show_card}" \/><\/div>\
		<a href="#" id="deleteButton" class="icon delete block center #{deleteVisible}" onclick="#{clearMode}">&nbsp;<\/a>\
		<h5 id="itemTitle"><a href="#{url}"  onclick="#{send_log}" title="#{desc}" target="_blank">#{title}<\/a>\
		<\/h5>\
		<p>#{content}<\/p>\
	<\/li>',
    blog_friend :
	'<li>\
		<div id="imageHolder"><span id="hotIcon" title="该博客最近有新文章" class="icon star center #{visible}">&nbsp;<\/span><img id="image" title="查看个人名片" src="#{imageUrl}" alt="#{imageAlt}" onerror="#{imgError}"  onclick="#{show_card}" \/><\/div>\
		<a href="#" id="sendTipButton" class="icon sendtip block center" onclick="#{send_msg}">&nbsp;<\/a>\
		<h5 id="itemTitle"><a href="#{url}" onclick="#{sendlog}" title="#{desc}" target="_blank">#{title}<\/a>\
		<\/h5>\
		<p>#{content}<\/p>\
	<\/li>',	
	blog_last_post : 
	'<li>\
		<a title="#{desc}" href="#{url}" target="_blank">#{title}<\/a>\
	<\/li>',
	blog_last_comment : 
	'<li>\
		<div>\
			<input type="button" class="icon personal_card #{visible}" onclick="showCard(\'#{uid}\', event,null,\'lcom\');return false;" \/>\
			<a href="#{url}" title="#{desc}" target="#{target}">#{title}<\/a>\
		<\/div>\
		<p>#{content}<\/p>\
	<\/li>',
	blog_last_gbook : 
	'<li>\
		<div>\
			<input type="button" class="icon personal_card" onclick="showCard(\'#{uid}\', event,null,\'lgbook\');return false;" \/>\
			<a href="#{url}" title="#{desc}" target="Content_ArticlePreview">#{title}<\/a>\
		<\/div>\
		<p>#{content}<\/p>\
	<\/li>',
	blog_myrecord : '',
    componet_more :
    '<div class="componetMore">\
        <a class="icon componetMoreIcon" href="#{href}" target="Content_ArticlePreview"> <\/a>\
    <\/div>'
    };
}
var TemplateLite = Class.create(); 
TemplateLite.prototype = {
	pattern : /(#\{(.*?)\})/g,
	initialize : function (tmpl) {
		this.tmpl = tmpl;
	},
	evaluate : function (data) {
	   return this.tmpl.replace(this.pattern, function(){
		   return data[arguments[2]] || "";
	   });
	},
	evaluateMulti : function (data, reverse) {
		var _buffer = new Array();
		window.foreach(data, function (v, i){
			i = reverse ? data.length - i : i;
			_buffer[i] = this.evaluate(v);
		}.bind(this));
		return _buffer.join("");	
	}
}
if (window == window.scope) {
  window.scope.Component = Class.create();
  Object.extend(window.scope.Component.prototype, {
    initialize : function (el, option) {
      option = option || {};
      option.transportType = option.transportType || "Ijax";
      this.option = option;
      this.data = [];
      this.dataProviders = this.option.dataProviders || [];
      this.currentDataProvider = -1;
      this.entity = $(el);
      this.ContentRoot = getChildrenByClass(this.entity, "componentInnderBorder")[0];
      this.contentElement = childById(this.ContentRoot, "componentContent");
      this.entity.comp = this;
      var tipContent = descByIds(this.ContentRoot, "#div>componentTip");
      this.tip = new $ProcessTip(tipContent);
      this.tip.service = this;
      var toggleLink = descByIds(this.ContentRoot, "#a>collapseButton");
      elementMethods.displayToggle(toggleLink);
      this.loadConfig();
	  this.activeTitle();
	  this.setManagement();
    },
    dispose : function () {
      this.clearEvents && this.clearEvents();
      this.contentElement = null;
      var entity = this.entity;
      this.entity.comp = null;
      this.entity = null;
      entity.parentNode.removeChild(entity);
    },
    load : function () {
      this.contentElement.style.display = "none";
      this.tip.onProgress();
      if (this.currentDataProvider == this.dataProviders.length - 1) {
        this.onFinishLoad();
        this.currentDataProvider = -1;
        return false;
      }
      this.currentDataProvider++;
      var provider = this.dataProviders[this.currentDataProvider];
      provider.init && provider.init.apply(this, [provider]);
      var charset = this.option.charset;
      if (provider.url && provider.url != "") {
        if (this.option.transportType == "Ijax")
          new Ijax(provider.url, {
            onComplete : provider.parse.bind(this).combine(this.load.bind(this))
          });
        else
          $ScriptLoader.request(provider.url, {
            onComplete : provider.parse.bind(this).combine(this.load.bind(this)),
            charset : charset || ""
          })
      } else
        this.load.bind(this).delayed();
    },
    moreLink : function (url) {
      var moreTpl = new Template(window.scope.$Template["componet_more"]);
      var obj = {href:url};
      return moreTpl.evaluate(obj);
    },
    onFinishLoad : function () {
      this.tip.onComplete();
      this.contentElement.style.display = "";
      this.show();
    },
    show : function () {
    },
    loadConfig : function () {
      this.key = this.entity.id == 'blog_diy_bm' || this.entity.id == "blog_diy_label"
          ? this.entity.id + " " + this.entity.attributes["dbid"].nodeValue
          : this.entity.id;
      this.property = window.scope.componentsConfig[this.key];
    },
    displayEmptyMsg : function () {
      var html = scope.$isAdmin ? this.property.adminEmptyMsg : this.property.guestEmptyMsg;
      html = '<div class="compEmptyInfo">' + html + '</div>';
      this.contentElement.innerHTML = html;
    },
    activeTitle : function () {
      var title = descByIds(this.ContentRoot, "#span>titleText");
      if (this.property.titleURL) {
        if (this.property.target == "blank") {
          title.innerHTML = '<a id="tilink">' + this.property.compName + '</a>';
          var link = this.property.titleURL;
          Event.observe(descByIds(title, "#a>tilink"), "mousedown", function (event) {
            Event.stop(event);
            window.open(link);
          })
        } else if (this.property.target == "self") {
          var target = "Content_ArticlePreview";
          title.innerHTML = '<a id="tilink">' + this.property.compName + '</a>';
          var link = this.property.titleURL;
          Event.observe(title, "mousedown", function (event) {
            Event.stop(event);
            byId(target).src = link;
          })
        }
      } else {
        title.style.cursor = "default";
        Event.observe(title, "mousedown", function(event) {
          Event.stop(event);
        })
      }
    },
    clear : function () {
      this.contentElement.innerHTML = "";
    },
    reload : function () {
      this.clear();
      this.load();
    }
  });
  Object.extend(window.scope.Component.prototype, {
    setManagement : function () {
	if (!scope.$isAdmin) return; //trace("ActiveMana is About!!")
	if($getPageId()!='blog') return;
      this.loadConfig();
      if (this.property.editURL) {
        var adminButton = descByIds(this.entity, "#a>adminCompButton");
		if(this.property.adminText)
			adminButton.innerHTML = this.property.adminText;
		else
        adminButton.innerHTML = "管理";
        removeClassName(adminButton, "invisible");
        Event.observe(adminButton, "mousedown", this.openManangementWindow.bind(this));
        if (this.key == "blog_friend") {
          var url = this.property.editURL;
          adminButton.href = url;
          adminButton.target = "Content_ArticlePreview";
        }
      }
      if (true) {
        var closeButton = descByIds(this.ContentRoot, "#a>closeCompButton");
        removeClassName(closeButton, "invisible");
        Event.observe(closeButton, "mousedown", this.close.bind(this));
      }
    },
    openManangementWindow : function (event) {
      Event.stop(event);
      var editURL = this.property.editURL;
      if (this.key == "blog_friend") {
        return false;
      }
      var iscroll = this.key == "blog_last_post" ? "scrollbars=yes," : "" ;
      if (this.property.isAli)
        window.open(editURL);
      else if (this.key != "blog_friend")
        window.open(editURL, "", "width=690,height=550," + iscroll + "left=" + (window.screen.width - 690) / 2 + ",top=" + (window.screen.height - 550) / 2);
      else
        byId("Content_ArticlePreview").src = editURL;
    },
    close : function (event) {
      Event.stop(event);
      if (!window.confirm("确认隐藏此模块么？隐藏后可到设置首页内容恢复。")) return;
      this.dispose();
      window.scope.$layoutModule.deleteComponent(this.key);
    }
  });
  window.scope.$ActiveManage = function() {
	return ;
	if (!scope.$isAdmin){
		trace("ActiveMana is About!!")
		return;	
	}
    var comps = ArrayWithout(window.scope.componentsName, "");
    comps.each(function (e) {
	  var cfg = window.scope.componentsConfig[e];
      if (cfg && cfg.compInstance) {
        var ins = cfg.compInstance.comp;
        if (ins) {
		  ins.setManagement();
        }
      } else {
        trace("NO FOUND CONFIG")
      }
    })
  }
  function reFreshComponent(componentId, newName) {
    if (componentId == "blog_diy_label") {
      scope.$ManaComp.loadDiyData(true, false);
      return;
    }
    if (componentId == "blog_diy_bm") {
      scope.$ManaComp.loadDiyData(false, true);
      return;
    }
    var ins = window.scope.componentsConfig[componentId].compInstance.comp;
    ins.reload();
    if (newName) {
      var title = descByIds(ins.ContentRoot, "#span>titleText");
      title.innerHTML = newName;
    }
  }
  window.scope.$Components = {};
  window.scope.$CreateDynamicComponent = function() {
    var comps = ArrayWithout(window.scope.componentsName, "");
	for(var i=0;i<comps.length;i++){
		if(comps[i]) window.scope.renderComp(comps[i]);
	}
  }
  window.scope.renderComp = function (e) {
      var comp = window.scope.componentsConfig[e];
      if (comp && comp.compInstance) {
        switch (comp.compType) {
          case "Static" :
          case "Default" :
            window.scope.initStaticComponent(comp.compInstance);
            break;
          case "Dynamic" :
            window.scope.defineComponent(comp.compInstance);
            break;
          default :
            break;
        };
      } else {
        trace("no found the component : " + e)
      }
    }
  window.scope.$Components.BlogPhoto = Class.define(
      null,
      window.scope.Component, {
    show : function () {
    },
    reload : function () {
      var url = "http://util.blog.sina.com.cn/ui?t=n&" + window.scope.uid + "&" + Math.random();
      new Ijax(url, {
        onStart : function () {this.tip.onProgress();
          this.contentElement.style.display = "none";
        },
        onComplete : function (text) {
          var o = text.replace(/;$/, "").j2o()[0];
          if (o)
            try {
              var photo = descByIds(byId("userImage"), "#image");
              photo.src = photo.src + "?" + Math.random();
              byId("intro").getElementsByTagName("a")[0].innerHTML = o.nick;
              descByIds(byId("adminPanel"), "#a>home").innerHTML = o.nick + " 您好！"
            } catch(e) {}
        }
      });
      this.tip.onComplete();
    }
  });
  window.scope.$Components.Static = Class.define(
      null,
      window.scope.Component, {
    show : function () {
    },
    reload : function () {
      if (this.key == "blog_myalbum" || this.key == "blog_diy_music"  ||   this.key == "blog_loverelay" ||  this.key == "blog_sunplayground" ) {
        this.tip.onProgress();
        var tmp = this.contentElement.innerHTML;
        this.contentElement.innerHTML = "";
        window.setTimeout(function () {
          this.tip.onComplete();
          this.contentElement.innerHTML = tmp;
        }.bind(this), 1000);
        return;
      }
      var url = this.property.contentURL;
      new Ijax(url, {
        onStart : function () {
          try {
            this.contentElement.style.display = "none";
            this.tip.onProgress();
          } catch(e) {}
        }.bind(this),
        onComplete : function (text) {
          try {
            this.contentElement.innerHTML = text;
            this.contentElement.style.display = "";
            this.tip.onComplete();
            if (descByIds(this.contentElement, "#div>Empty")) {
              this.displayEmptyMsg();
              return;
            }
            if (this.key == "blog_diy_cboard") {
              this.contentElement.innerHTML = text + ' <div slidecontrol="slideContent" class="slideButton" id="slideButtonArea"><input type="button" title="" class="icon callBoardButtonFront" id="prev" style="display: none;"/><input type="button" title="" class="icon callBoardButtonBack" id="next"/></div>';
              addSlide();
            }
          } catch(e) {
          }
        }.bind(this)
      });
    }
  });
  window.scope.initStaticComponent = function (dv) {
    var compId = dv.id;
    var clz;
    switch (compId) {
      case "blog_photo":
        clz = window.scope.$Components.BlogPhoto;
        break;
      default :
        clz = window.scope.$Components.Static;
        break;
    }
    var comp = new clz(dv);
    if (descByIds(comp.ContentRoot, "#div>Empty")) {
      comp.displayEmptyMsg();
    }
  }
  window.scope.defineComponent = function (dv) {
    var compId = dv.id;
    var option = {
      template : new TemplateLite(window.scope.$Template[compId])
    };
    var clz;
    switch (compId) {
      case "blog_visit" :
        clz = window.scope.$Components.BlogVisit;
        option.dataProviders = [new window.scope.BlogVisitDataProvider()];
        break;
      case "blog_friend" :
        clz = window.scope.$Components.BlogFriend;
        option.dataProviders = [new window.scope.BlogFriendDataProvider(), new window.scope.UICDataProvider()];
        break;
      case "blog_last_post":
        clz = window.scope.$Components.BlogLastPost;
        option.dataProviders = [new window.scope.BlogLastPostDataProvider()];
        option.transportType = "ScriptLoader";
        option.charset = "GB2312";
        break;
      case "blog_last_comment":
        clz = window.scope.$Components.BlogLastComment;
        option.dataProviders = [new window.scope.BlogLastCommentDataProvider()];
        option.transportType = "ScriptLoader";
        option.charset = "GB2312";
        break;
      case "blog_last_gbook":
        clz = window.scope.$Components.BlogLastGbook;
        option.dataProviders = [new window.scope.BlogLastGbookDataProvider()];
        option.transportType = "ScriptLoader";
        option.charset = "GB2312";
        break;
      case "blog_myrecord":
        clz = window.scope.$Components.BlogMyRecord;
        option.dataProviders = [new window.scope.BlogMyRecordDataProvider()];
        option.transportType = "ScriptLoader";
        option.charset = "GB2312";
        break;
      default:
    }
    var comp = new clz(dv, option);
    comp.load();
  }
}
var $DEF_MY_BLOG_DOMAIN = "http://my.blog.sina.com.cn";
if(typeof(uhost) == 'undefined')	var uhost = ""; 
window.scope.completeConfig = function () {
	window.scope.componentsConfig = {
		blog_photo : {
			compName : "个人信息",
			compType: "Static",
			isEdit : true,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "",//no such type
			adminEmptyMsg : "",//no such type
			editURL : $DEF_MY_BLOG_DOMAIN + "/myblog/blog4/staticinter.php?module=blog_photo",
			contentURL : "",
			titleURL : "",
			target : "blank",
			DBid : ""
		},
		blog_zone : {
			compName : "活力地带",
			compType: "Default",
			isEdit : false,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "",
			contentURL : "",
			titleURL : "",
			target : "",
			DBid : ""
		},
		blog_calendar : {
			compName : "日历",
			compType: "Default",
			isEdit : true,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "",
			contentURL : "",
			titleURL : "",
			target : "",
			DBid : ""
		},
		blog_last_post : {
			compName : "最新文章",
			compType: "Dynamic",
			isEdit : true,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "暂时没有最新文章。",
			adminEmptyMsg : "暂时没有最新文章，请发表文章。",
			editURL : $DEF_MY_BLOG_DOMAIN + "/writing/explorer/article_list_sort_static.php",
			contentURL : "",
			titleURL : "http://blog.sina.com.cn/s/alist_"+scope.uid+"_0_1.html",
			target : "self",
			DBid : ""
		},
		blog_last_comment : {
			compName : "最新评论",
			compType: "Dynamic",
			isEdit : true,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "暂时没有最新评论。",
			adminEmptyMsg : "暂时没有最新评论。",
			editURL : $DEF_MY_BLOG_DOMAIN + "/myblog/blog4/staticinter.php?module=blog_last_comment",
			contentURL : "",
			titleURL : "",
			target : "blank",
			DBid : ""
		},
		blog_last_gbook : {
			compName : "最新留言",
			compType: "Dynamic",
			isEdit : true,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "暂时没有最新留言。",
			adminEmptyMsg : "暂时没有最新留言。",
			editURL : $DEF_MY_BLOG_DOMAIN + "/myblog/blog4/staticinter.php?module=blog_last_gbook",
			contentURL : "",
			titleURL : "http://blog.sina.com.cn/s/gbook_"+scope.uid+"_1.html",
			target : "self",
			DBid : ""
		},
		blog_myalbum : {
			compName : "相册",
			compType: "Static",
			isEdit : true,
			isClose : true,
			isTitle : true,
			isAli : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "http://photo.sina.com.cn/"+ uhost,
			contentURL : "",
			titleURL : "http://photo.sina.com.cn/"+ uhost,
			target : "blank",
			DBid : ""
		},
		blog_visit : {
			compName : "访客",
			compType: "Dynamic",
			isEdit : false,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "暂时没有新浪访客，登录用户才能留下访问记录。",
			adminEmptyMsg : "暂时没有新浪访客，登录用户才能留下访问记录。",
			editURL : "",
			contentURL : "",
			titleURL : "",
			target : "",
			DBid : ""
		},
		blog_diy_serial : {
			compName : "文章专辑",
			compType: "Static",
			isEdit : false,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "暂时没有文章专辑。",
			adminEmptyMsg : "暂时没有文章专辑，<br>请创建文章专辑。",
			editURL : $DEF_MY_BLOG_DOMAIN + "/section/special/special_list_static.php",
			contentURL : "http://my.blog.sina.com.cn/sns/service_static.php?m=serial&uid="+scope.uid,
			titleURL : "",
			target : "blank",
			DBid : ""
		},
		blog_diy_cboard : {
			compName : "公告",
			compType: "Static",
			isEdit : false,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "暂时没有公告。",
			adminEmptyMsg : "暂时没有公告，请添加公告。",
			editURL : $DEF_MY_BLOG_DOMAIN + "/section/notice/notice_list_static.php",
			contentURL : "http://my.blog.sina.com.cn/sns/service_static.php?m=callboard&uid="+scope.uid,
			titleURL : "",
			target : "blank",
			DBid : ""
		},
		blog_sort : {
			compName : "文章分类",
			compType: "Static",
			isEdit : false,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "暂时没有文章分类。",
			adminEmptyMsg : "暂时没有文章分类，<br>请创建文章分类。",
			editURL : $DEF_MY_BLOG_DOMAIN + "/myblog/blog4/staticinter.php?module=blog_sort",
			contentURL : "http://my.blog.sina.com.cn/sns/service_static.php?m=sortlist&uid="+scope.uid,
			titleURL : "",
			target : "blank",
			DBid : ""
		},
		blog_diy_music : {
			compName : "音乐播放器",
			compType: "Default",
			isEdit : false,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "",
			contentURL : "",
			titleURL : "",
			target : "blank",
			DBid : ""
		},
		blog_circle_left : {
			compName : "圈子",
			compType: "Default",
			isEdit : false,
			isClose : true,
			isTitle : true,
			isAli : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "http://q.blog.sina.com.cn/myindex.php",
			contentURL : "",
			titleURL : "http://q.blog.sina.com.cn/myindex.php",
			target : "blank",
			DBid : ""
		},
		blog_boke : {
			compName : "播客",
			compType: "Default",
			isEdit : false,
			isClose : true,
			isTitle : true,
			isAli : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "http://you.video.sina.com.cn/m/",
			contentURL : "",
			titleURL : "",
			target : "blank",
			DBid : ""
		},
		blog_mybreach: {
			compName : "我突破",
			compType: "Static",
			isEdit : false,
			isClose : true,
			isTitle : true,
			isAli : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "",
			contentURL : "",
			titleURL : "",
			target : "blank",
			DBid : ""
		},
		blog_myrecord : {
			compName : "我记录",
			compType: "Dynamic",
			isEdit : false,
			isClose : true,
			isTitle : true,
			isAli : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "",
			contentURL : "",
			titleURL : "",
			target : "blank",
			DBid : ""
		},
		blog_2008mark : {
			compName : "“我的2008”徽章",
			compType: "Static",
			isEdit : false,
			isClose : true,
			isTitle : true,
			isAli : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "",
			contentURL : "",
			titleURL : "",
			target : "",
			DBid : ""
		},
		blog_friend : {
			compName : "好友",
			compType: "Dynamic",
			isEdit : false,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "http://blog.sina.com.cn/html/fl.html",
			contentURL : "",
			titleURL : "http://blog.sina.com.cn/html/fl.html",
			target : "self",
			DBid : ""
		},
		blog_loverelay : {
			compName : "爱心接力棒",
			compType: "Static",
			isEdit : true,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "http://my.blog.sina.com.cn/myblog/blog4/staticinter.php?module= blog_loverelay",
			contentURL : "",
			titleURL : "http://heart.sina.com.cn",
			target : "blank",
			DBid : ""
		},
		blog_toparticlesort : {
			compName : "新浪博客推荐文章",
			compType: "Static",
			isEdit : false,
			isClose : false,
			isTitle : false,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "",
			contentURL : "",
			titleURL : "",
			target : "",
			DBid : ""
		},
		blog_sunplayground : {
			compName : "阳光操场",
			compType: "Static",
			isEdit : true,
			isClose : true,
			isTitle : true,
			guestEmptyMsg : "",
			adminEmptyMsg : "",
			editURL : "",
			contentURL : "",
			titleURL : "http://sports.sina.com.cn/yangguangcaochang/index.shtml",
			target : "blank",
			DBid : ""
		} 
	}
	var compConfig = window.scope.componentsConfig;
	var page = window.scope; 
	var comps = page.$Layout.getCompsInPage();
	var cid = (page.config.theme == 4) ? 2 : 1;
	var cel = scope.document.getElementById("column_" + cid);
	var comp = comps["column_" + cid];
	window.scope.componentsName = ArrayWithout(eval("window.scope.config.layout.column_"+cid),"blog_counter","blog_feeds_addr","");
	window.scope.componentsColumnID = cel;
	var pageConfig = window.scope.componentsName;
	pageConfig.each(function (e){
		if(!compConfig[e]) {
			var componentType,componentDBid;
			e.replace(/(.*) (.*)/gi,function ($0,$1,$2){
				componentType = $1;
				componentDBid = $2;
			});
			var ins = null;
			for(i=0;i<comp.length;i++){
				if(comp[i].id == componentType && Element.readAttribute(comp[i],"dbid") == componentDBid ){
					ins = comp[i];
					break;
				}
			}
			if(ins)	compConfig[e] = {
				compInstance : ins,
				compName : descByIds(ins,"#span>titleText").innerHTML,
				compType: "Static",
				isEdit : true,
				isClose : true,
				isTitle : true,
				guestEmptyMsg : componentType == "blog_diy_bm" ? "暂时没有链接列表内容。" : "",
				adminEmptyMsg : componentType == "blog_diy_bm" ? "暂时没有链接列表内容,请添加。" : "",
				editURL :  componentType == "blog_diy_bm" ? $DEF_MY_BLOG_DOMAIN + "/myblog/blog4/staticinter.php?module="+componentType+"&nid="+componentDBid : $DEF_MY_BLOG_DOMAIN + "/section/label/label_edit_static.php?my_id=" + componentDBid,
				contentURL : componentType == "blog_diy_bm" ? "http://my.blog.sina.com.cn/sns/service_static.php?m=bmlink&uid="+scope.uid+"&vid="+componentDBid : "http://my.blog.sina.com.cn/sns/service_static.php?m=label&uid="+scope.uid+"&vid="+componentDBid,
				titleURL : "",
				target : "self",
				DBid : componentDBid
			}
		}else{
			compConfig[e].compInstance = childById(cel,e);
		}		
	});
}
var $ProcessTip = Class.create();
$ProcessTip.prototype = {
	defaultInit : "",
	defaultInitSrc : "",
	defaultProgress : "正在载入模块...",
	defaultProgressSrc : "http://blogjs.sinajs.cn/images/icon/loading_icon.gif",
	defaultComplete : "",
	defaultCompleteSrc : "",
	defaultError : "<font color=red>载入失败！</span><a id='reload_btn'>请重新载入</a>",
	defaultErrorSrc : "",
	initialize : function (pNode,option) {
		if(option)	for (var i in option)	this[i] = option[i];
		var sDiv = $C("div");
		sDiv.className = "process_tip";
		sDiv.id = "process_tip";
		sDiv.innerHTML = "<img id='icon' align=absmiddle /><span id='text'></span>";
		sDiv.style.display = "none";
		pNode.appendChild(sDiv);
		this.comp = childById(pNode, "process_tip");
		this.icon = childById(this.comp, "icon");
		this.text = childById(this.comp, "text");
	},
	status : function (msg,isAuto) {
		this.comp.style.display="";
		this.text.innerHTML = msg;
	},
	showIcon : function (iconSrc) {
		if(iconSrc == "")	{
		}else{
			this.icon.style.display="";
			this.icon.src = iconSrc;
		}
	},
	thenHide : function () {
		this.comp.style.display="none";
	},
	onInit : function (msg, src) {
		this.showIcon(src || this.defaultInitSrc);
		this.status(msg || this.defaultInit);
	},
	onProgress : function (msg, src) {
		this.showIcon(src || this.defaultProgressSrc);
		this.status(msg || this.defaultProgress);
	},
	onComplete : function (msg, src) {
		this.thenHide();
	},
	onError : function (msg, src){
		this.showIcon(src || this.defaultErrorSrc);
		this.status(msg || this.defaultError);
	}
};
if (window == window.scope) {
  window.scope.BlogLastPostDataProvider = Class.define(
      function () {
        this.url = "http://blognewarts.sinajs.cn/latest_art?" + window.scope.uid;;
      },
      Object, {
    init : function(loader) {
    },
    parse : function (text) {
      var o = text.j2o() || [];
      this.data = o.foreach(function (e) {
        e.url = 'http://blog.sina.com.cn/s/blog_'+e.l+".html";
        e.title = e.t;
        e.desc = e.c;
		return e;
      });
    }
  });
  window.scope.$Components.BlogLastPost = Class.define(
      null,
      window.scope.Component, {
    show : function () {
	  if(this.data.length == 0){
		this.displayEmptyMsg();
		return;
		}
      var str = "";
      var op = this.option;
	  str = op.template.evaluateMulti(this.data);
      str = "<ul class='previewList'>" + str + "<\/ul>";
      this.contentElement.innerHTML = str;
    }
  });
}
if (window == window.scope) {
  window.scope.BlogLastCommentDataProvider = Class.define(
      function () {
        this.url = "http://blognewcms.sinajs.cn/latest_cms?" + window.scope.uid;
      },
      Object, {
    init : function(loader) {
    },
    parse : function (text) {
      var o = text.j2o() || [];
      this.data = o.foreach(function (e) {
		  e.visible = e.g == '0' ? 'invisible' : '' ;
		  e.uid = e.g;
		  e.url = "http://blog.sina.com.cn/"+e.l+"#comment";
		  e.desc = e.c;
		  e.title = e.n;
		  e.content = e.c;
		  e.target = (e.l&&(e.l.indexOf('s/serial_')>-1))?'Content_ArticlePreview':'_blank';
		  return e;
	});
    }
  });
  window.scope.$Components.BlogLastComment = Class.define(
      null,
      window.scope.Component, {
    show : function () {
	  if(this.data.length == 0){
		this.displayEmptyMsg();
		return;
		}
      var str = "";
      var op = this.option;
	  str = op.template.evaluateMulti(this.data);
      str = "<ul class='previewList'>" + str + "<\/ul>";
      this.contentElement.innerHTML=str;
    }
  });
}
if (window == window.scope) {
  window.scope.BlogLastGbookDataProvider = Class.define(
      function () {
        this.url = "http://blognewgbooks.sinajs.cn/latest_msg?" + window.scope.uid;
      },
      Object, {
    init : function(loader) {
    },
    parse : function (text) {
      var o = text.j2o() || [];
	  var isAdmin = scope.$isAdmin;
      this.data = o.foreach(function (e) {
	      e.uid = e.g;
		  if(isAdmin){
				e.url = scope.$Url("gbookAdmin", {uid:scope.uid, page:1});
		  }else{
				e.url = scope.$Url("gbook", {id:scope.uid, page:1});
		  }
	      e.desc = e.c;
	      e.title = e.n;
	      e.content = e.c;
		  return e;
	      });
      }
  });
  window.scope.$Components.BlogLastGbook = Class.define(
      null,
      window.scope.Component, {
    show : function () {
	  if(this.data.length == 0){
		this.displayEmptyMsg();
		return;
		}
      var str = "";
      var op = this.option;
	  str = op.template.evaluateMulti(this.data);
      str = "<ul class='previewList'>" + str + "<\/ul>";
	  this.contentElement.innerHTML = str;
    }
  });
}
if (window == window.scope) {
  window.scope.BlogVisitDataProvider = Class.define(
      function () {
        this.url = "http://util.blog.sina.com.cn/rr?" + window.scope.uid +"&n";
      },
      Object, {
    init : function(loader) {
    },
    parse : function (text) {
	  text = text.substr(0,text.length-1);
      var o = text.j2o() || [];
      this.data = o.each(function (e) {
		var m = parseInt(e.uid)%8+1;
        e.visible = isRecentUpdate(e.newupdate) ? '' : 'visibility';
        e.imageUrl = "http://portrait"+ m +".sinaimg.cn/"+e.uid+"/space/30";  
        e.imageAlt = e.nick;
        e.url = "http://blog.sina.com.cn/" + e.url;
        e.desc = e.nick + "的博客";
        e.title   = e.nick;
		e.deleteVisible = (e.uid==scope.AuthorUID || scope.isAdmin()) ? '' : 'invisible';
		e.clearMode = 'clearRR('+e.uid+','+ e.time +')';
		e.show_card = "showCard("+e.uid+",event,'lrr',window,'blog_visit');return false;";
		e.send_log = scope.pageMark == "index"
			   ? "sendLog('lrr','rr');"
			   : "sendCommonLog('rela_visiter_nickname','articlenewone');";
		e.uid = e.uid == scope.AuthorUID ? e.uid : "";
        e.content = new Date(parseInt(e.time) * 1000).toLocaleString().replace(/\u5E74|\u6708/g, "-").replace(/\u65E5/g, " ");
		e.imgError = "this.onerror=null;this.src='http://blogimg.sinajs.cn/images/sample.template/component/fl_default.jpg'";
      });
    }
  });
  window.scope.$Components.BlogVisit = Class.define(
      null,
      window.scope.Component, {
    show : function () {
      var str = "";
      var op = this.option;
	  str = op.template.evaluateMulti(this.data, true);
      str = "<ul class='previewList'>" + str + "<\/ul>";
	  if(this.data.length == 0) str = '<div class="compEmptyInfo">暂时还没有访客记录，赶快邀请您的朋友来访问吧。</div>';
	  this.contentElement.innerHTML = str;
    },
	clearRecord : function(uid, vid, t){
		var newurl = "http://util.blog.sina.com.cn/rr?" + ((vid!=scope.AuthorUID)? vid + "&en&" : uid + "&dn&") + new Date().valueOf();
		this.dataProviders[0].url = newurl;
		include("http://v.space.sina.com.cn/visitor/del.php?pid=1&uid=" + uid+"&vid="+ vid +"&time="+ t  + "&var=newVisitRecord&"+new Date().valueOf(), function(){});
		this.load();
	}
	  });
}
function clearRR(vid,t){
  var uid = scope.uid;
	if(!uid) return;
	var confirmStr = (vid==scope.AuthorUID) ? "您是否要删除您的访客记录？删除后1小时内，您将无法进入到此博客的最近访客列表。" : "您是否要删除该条访客记录？删除后，该访客将不会再进入您的最新访客列表。", e = e||0;
	if(confirm(confirmStr)){
	$("blog_visit").comp.clearRecord(uid, vid, t);
	}
}
if (window == window.scope) {
  window.scope.BlogFriendDataProvider = Class.define(
      function () {
        this.url = "http://my.blog.sina.com.cn/myblog/friend_beta.php?uid=" + window.scope.uid;
      },
      Object, {
    parse : function (text) {
	var ar = text.match(/[\d,]*;/g);
	this.MFL = ar[0] ? ar[0].replace(";","").split(",") : [];
	this.MFL = this.MFL[0] == "" ? [] : (this.MFL.length > 10 ? this.MFL.slice(0,10) : this.MFL);
	this.OFL = ar[1] ? ar[1].replace(";","").split(",") : [];
	this.OFL = this.OFL[0] == "" ? [] : (this.OFL.length > 10 ? this.OFL.slice(0,10) : this.OFL);
	this.fromUic = this.MFL.concat(this.OFL || []);
    }
  });
  window.scope.UICDataProvider = Class.define(
      function () {
      },
      Object, {
    init : function (provider) {
      var $UIC_url = "http://util.blog.sina.com.cn/ui?t=n&";
      if (this.fromUic.length == 0) {
        provider.url = "";
        return;
      }
      provider.url = $UIC_url + this.fromUic.join(",") +"&" + new Date().valueOf();
    },
    parse : function (text) {
		text = text.replace(/;$/g,"");
      var uicList = text.j2o() || []; 
	var _M = this.MFL;
      uicList = uicList.each(function (e){
		var m = parseInt(e.uid)%8+1;
        e.visible = isRecentUpdate(e.newupdate) ? '' : 'visibility';
        e.imageUrl = "http://portrait"+ m +".sinaimg.cn/"+e.uid+"/space/30";
        e.url = "http://space.sina.com.cn/" + e.uid;
        e.nick = e.nick;
        e.desc = e.nick;
        e.title   = e.nick;
        e.uid = e.uid;
		e.send_msg = "send_message_to("+e.uid+")";
		e.logtype = _M.indexOf(e.uid) >= 0 ? 'lfl1' : 'lfl2';
		e.sendlog = "sendLog('"+e.logtype+"');"
		e.show_card = "showCard("+e.uid+",event,'" + e.logtype + "',window);return false;";
      }).hashBy("uid");
      this.MFL = this.MFL.inject([],function(m, v, i){
            m.push(uicList[v]);
            return m;
        })
      if(this.OFL)  this.OFL = this.OFL.inject([],function(m, v, i){
            m.push(uicList[v]);
            return m;
        })
    }
  });
  window.scope.$Components.BlogFriend = Class.define(
      null,
      window.scope.Component, {
    show : function () {
	var str = "";
	str += this.showList(this.MFL,"compFriendF","/html/fl.html?action=f");
	if(scope.$isAdmin){
	   str += '<div id="friendListToggleBar" toggle="compFriendO"><a href="javascript:;" >其他联系人</a><a id="Arrow" class="icon center"/> </a></div>';
	   str += this.showList(this.OFL,"compFriendO","/html/fl.html?action=o");
	}
	this.contentElement.innerHTML = str;
	if(byId("compFriendO"))	byId("compFriendO").style.display = "none";
	window.elementMethods.displayToggle("friendListToggleBar");
    },
    showList : function (data,id,more_link){
        var str = "";
        var op = this.option;
		str = op.template.evaluateMulti(data);
        if(data.length == 0){
            var EmptyStr = id=="compFriendF"
                  ? "博主还没有添加好友"
                  : "博主还没有添加其他联系人";
            str += "<li class='BlogFriendEmptyMsg'>"+EmptyStr+"</li>"
        }
        str = "<ul class='previewList' id='" + id + "'>" + str + "<\/ul>";
        if(data.length >= 10 ){
			str += this.moreLink(more_link);
		}
        return str;
    }
  });
}
if (window == window.scope) {
  window.scope.BlogMyRecordDataProvider = Class.define(
      function () {
				this.url = "http://blogolym.sinajs.cn/myolym?uid=" + window.scope.uid;
      },
      Object, {
    init : function(loader) {
    },
    parse : function (text) {
    	if(text == "empty"){
    		this.data = "empty";
    	}else 
    	if(text == "non-empty"){
    		this.data = "non-empty";
    	}else{
	      var e = text.j2o() || [];
	      var catesDef = ["我的事业梦想","我的生活梦想","我的情感梦想"];
	      this.data = e.foreach(function (o) {
					o.cateNum = parseInt(o.c);
					o.cate = catesDef[o.cateNum-1-10];
					o.articleSum = o.a;
					o.commentSum = parseInt(o.n)*10;
					o.listUrl = "http://blog.sina.com.cn/s/my2008_"+window.scope.uid+"_"+o.cateNum+"_1.html"	;
					o.msgSum = o.s;
					return o;
	      });
	    }
    }
  });
  window.scope.$Components.BlogMyRecord = Class.define(
      null,
      window.scope.Component, {
    show : function () {
    	var sConfig = "2007.9.10";
    	function formateDate(stamp)
			{
				var tmpDate = new Date(stamp);
				return (tmpDate.getMonth()+1)+"."+tmpDate.getDate();
			}
    	function getToday()
			{
				this.now = new Date();
				this.year = this.now.getFullYear();
				this.month = this.now.getMonth(); 
				this.day = this.now.getDate();
				this._day = this.now.getDay();
			}
			function updateGameBoard()
			{
				var ar = sConfig.split(".");
				var yearStart = parseInt(ar[0]);
				var monthStart = parseInt(ar[1]) -1;
				var dayStart = parseInt(ar[2]);
				var start = Date.UTC(yearStart, monthStart, dayStart);
				var now = new getToday();
				var end = Date.UTC(now.year, now.month, now.day);
				var per = 86400000 * 7;
				var week = Math.floor((end - start)/per);//+1;
				if(now._day == 1)
				var sis = formateDate(start+(week-1)*per)+" - "+formateDate(start+week*per-86400000);
				else
				var sis = formateDate(start+week*per)+" - "+formateDate(end-86400000);
				var tit = new Date(end).toLocaleString().replace(/ .+$/,"").replace(/\u5E74|\u6708/g, "-").replace(/\u65E5/g, " ");
				var days = ["日", "一", "二", "三", "四", "五", "六"];
				var tody = "(周" + days[new Date(end).getDay()] + ")";
				byId("cateDate").innerHTML = "2月18日 - 3月31日博主成绩";
			}
		  var str = '\
		  <table width="190" cellpadding="0" cellspacing="0" class="my2008">\
			  <tr>\
			    <td class="my2008head" id="my2008head">\
			    <div id="cateTitle">本期参加“我记录”活动情形</div>\
			    <div class="cateDate" id="cateDateCont">\
			    	<div id="cateDate"></div>\
			    	</div>\
			    <div class="my2008body" id="my2008content">\
				<div style="text-align:center;padding:10px;">数据正在加载中...</div>\
			    </div>\
			  </tr>\
			  <tr id="infoFoot">\
			    <td  style="text-align:center" class="my2008foot"><a href="http://my2008.sina.com.cn/blog" target="_blank" class="mg"  style="color:#D13600;text-decoration:underline;">活动首页</a><a target="_blank" id="curr"  style="color:#D13600;text-decoration:none; visibility:hidden">博主本期文章</a></td>\
			  </tr>\
			</table>';
      this.contentElement.innerHTML = str;
      if(this.data == "non-empty")	{
			byId("my2008content").innerHTML = '<div class="emptyInfo">本期博主尚未发表“我记录”活动<br>的相关文章。</div>';
			byId("curr").innerHTML = "博主所有参赛文章";
			//byId("curr").href = "http://blog.sina.com.cn/s/my2008_" + window.scope.uid + "_10_1.html";
			updateGameBoard();
			return;	
		}
		if(this.data == "empty")	{
			byId("cateDate").style.display = "none";
			byId("infoFoot").style.display = "none";
			byId("cateTitle").innerHTML = "欢迎参加“我记录”活动";
			byId("my2008content").innerHTML = '<div class="emptyInfo2">参加“我记录”活动，赢取万元大奖！　　<a href="http://my2008.sina.com.cn/blog" target="_blank"  style="color:#D13600;text-decoration:underline;">活动首页</a>';
			//byId("curr").href = "http://blog.sina.com.cn/s/my2008_" + window.scope.uid + "_10_1.html";
			return;
		}
		var html = "";
		this.data.each(function (e){
			html += '\
			<tr>\
			<td class="ca">'+ e.cate +'</td>\
			<td class="ar">'+ e.articleSum+'</td>\
			<td class="ps">'+ e.commentSum+'</td>\
			</tr>\
			';
		})	
		html = '\
		       <table width="175" class="my2008List">\
		       <tr>\
		       <th class="cate"><img src="http://blogimg.sinajs.cn/images/2008fenlei.gif"/></th>\
		       <th class="article"><img src="http://blogimg.sinajs.cn/images/2008wenzhangshu.gif"/></th>\
		       <th class="points"><img src="http://blogimg.sinajs.cn/images/2008pinglunjifen.gif"/></th>\
		       </tr>\
		' + html + '\
			</table>\
		';
		byId("my2008content").innerHTML = html;
		//byId("curr").href = "http://blog.sina.com.cn/s/my2008_" + window.scope.uid + "_10_1.html";
		updateGameBoard();
    }
  });
}
var MyRecordPopup = function() {
	this.init();
};
MyRecordPopup.prototype = {
	isLoaded : false,
	initDom : function () {
		var div = $C("div");
		div.id = "blog2008Box";
		div.style.display = "none";
		div.innerHTML = this.struc;
		var appendTarget;
		appendTarget = byId("innerBound") ? byId("innerBound") : document.body;
		appendTarget.appendChild(div);
	},
	init : function () {
		this.initDom();
		var self = this;
		$addEvent2('blog2008close', function(){
			var obj = byId("blog2008Box");
			obj.style.display = 'none';
		});
		if(!$ScriptLoader) var $ScriptLoader =
		{
			request : function (url,option){
				this.option = option || {};
				this.url = url;
				var js = document.createElement("script");
				js.charset = "gb2312";
				js.type = "text/javascript";
				var requestId = "&requestId=" + Math.random() + ".js";
				js.src = this.url + requestId;
				document.body.appendChild(js);
			},
			response : function(id, data){
				this.option.onComplete.call(this, data);
			}
		}
	},
	load : function () {
		this.resize();
		if(this.isLoaded)	return;
		var sConfig = "2007.9.10";
		var dataSource = "http://blogolym.sinajs.cn/myolym";
		var catesDef = ["我的事业梦想","我的生活梦想","我的情感梦想"];
		function formateDate(stamp)
		{
			var tmpDate = new Date(stamp);
			return (tmpDate.getMonth()+1)+"."+tmpDate.getDate();
		}
		function getToday()
		{
			this.now = new Date();
			this.year = this.now.getFullYear();
			this.month = this.now.getMonth();
			this.day = this.now.getDate();
			this._day = this.now.getDay();
		}
		function updateGameBoard()
		{
			var ar = sConfig.split(".");
			var yearStart = parseInt(ar[0]);
			var monthStart = parseInt(ar[1]) -1;
			var dayStart = parseInt(ar[2]);
			var start = Date.UTC(yearStart, monthStart, dayStart);
			var now = new getToday();
			var end = Date.UTC(now.year, now.month, now.day);
			var per = 86400000 * 7;
			var week = Math.floor((end - start)/per);//+1;
			if(now._day == 1)
				var sis = formateDate(start+(week-1)*per)+" - "+formateDate(start+week*per-86400000);
			else
				var sis = formateDate(start+week*per)+" - "+formateDate(end-86400000);
			var tit = new Date(end).toLocaleString().replace(/ .+$/,"").replace(/\u5E74|\u6708/g, "-").replace(/\u65E5/g, " ");
			var days = ["日", "一", "二", "三", "四", "五", "六"];
			var tody = "(周" + days[new Date(end).getDay()] + ")";
			var contObj = byId("blog2008Cont"); 
			descByIds(contObj,"#div>cateDate").innerHTML = "2月18日 - 3月31日博主成绩";
		}
		var loadOption =
		{
			onComplete : function (text) {
				var contObj = byId("blog2008Cont"); 
				if(text == "non-empty")	{
					descByIds(contObj,"#div>my2008content").innerHTML = '<div class="emptyInfo">本期博主尚未发表“我记录”活动<br>的相关文章。</div>';
					descByIds(contObj,"#a>curr").innerHTML = "博主所有参赛文章";
					//descByIds(contObj,"#a>curr").href = "http://blog.sina.com.cn/s/my2008_" + __uid + "_10_1.html";
					updateGameBoard();
					this.resize();
					return;
				}
				if(text == "empty")	{
					descByIds(contObj,"#div>cateDate").style.display = "none";
					descByIds(contObj,"#tr>infoFoot").style.display = "none";
					descByIds(contObj,"#div>cateTitle").innerHTML = "欢迎参加“我记录”活动";
					descByIds(contObj,"#div>my2008content").innerHTML = '<div class="emptyInfo2">参加“我记录”活动，赢取万元大奖！　　<a style="color:#D13600;text-decoration:underline;" href="http://my2008.sina.com.cn/blog" target="_blank">活动首页</a>';
					//descByIds(contObj,"#a>curr").href = "http://blog.sina.com.cn/s/my2008_" + __uid + "_10_1.html";
					this.resize();
					return;
				}
				var data = text.j2o() || [];
				var len = data.length;
				var html = "";
				for(var i=0;i<len;i++){
					var o = data[i];
					var cateNum = parseInt(o.c);
					var cate = catesDef[cateNum-1-10];
					var articleSum = o.a;
					var commentSum = parseInt(o.n)*10;
					var msgSum = o.s;
					var listUrl = "http://blog.sina.com.cn/s/my2008_" + __uid + "_"+cateNum+"_1.html"
					html += '\
					<tr>\
					<td class="ca">'+ cate +'</td>\
					<td class="ar">'+ articleSum +'</td>\
					<td class="ps">'+ commentSum +'</td>\
					</tr>\
					';
				}
				html = '\
					   <table width="175" class="my2008List">\
					   <tr>\
		       <th class="cate"><img src="http://blogimg.sinajs.cn/images/2008fenlei.gif"/></th>\
		       <th class="article"><img src="http://blogimg.sinajs.cn/images/2008wenzhangshu.gif"/></th>\
		       <th class="points"><img src="http://blogimg.sinajs.cn/images/2008pinglunjifen.gif"/></th>\
					   </tr>\
				' + html + '\
					</table>\
				';
				descByIds(contObj,"#div>my2008content").innerHTML = html;
				//descByIds(contObj,"#a>curr").href = "http://blog.sina.com.cn/s/my2008_" + __uid + "_10_1.html";
				this.resize();
			}
		}
		var __uid;
		try{
			__uid = scope.uid
		}catch(e){
			__uid = UID;
		}
		var dataURL = dataSource + "?uid=" + __uid;
		updateGameBoard();
		$ScriptLoader.request(dataURL, loadOption);
		//document.getElementById("curr").href="http://blog.sina.com.cn/s/my2008_" + __uid + "_10_1.html";
		this.isLoaded = true;
	},
	resize : function () {
		var obj = byId("blog2008");
		var shadow = byId("blog2008Shadow");
		shadow.style.position = "absolute";
		setTimeout(function (){
			shadow.style.height = obj.clientHeight + "px";
		},500);
	},
	show : function (e) {
		var obj = byId("blog2008Box");
		var scrollObj = byId("outBound") ? byId("outBound") : document.body;
		var isAdjust;
		try{
			var ifm = scope.$("Content_ArticlePreview").contentWindow;
			if(ifm.byId("articleContainer").nodeType){
				isAdjust = true;
			}
		}catch(e){
			isAdjust = false;
		}
		var _t,_l
		var mouseX = $Br.$IE && !isAdjust ? parseInt(this.getX()) : parseInt(this.getX(e));
		var mouseY = $Br.$IE && !isAdjust ? parseInt(this.getY()) : parseInt(this.getY(e));
		if(isAdjust){
			_t = parseInt($("Content_ArticlePreview").getLeft()) + mouseX - 200 + "px";
			_l = parseInt($("Content_ArticlePreview").getTop())  + mouseY + 10 + "px";
		}else{
			_t = mouseX - 200 + "px";
			_l = mouseY + parseInt(scrollObj.scrollTop) + 10 + "px";
		}
		obj.style.left = _t;
		obj.style.top = _l;
		obj.style.display = "";
		this.load();
	},
	hide : function () {
		byId("blog2008Box").style.display = "none";
	},
	fixE : function (e) {
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	},
	getX : function (e){
		return this.fixE(e).clientX;
	},
	getY : function (e){
		return this.fixE(e).clientY;
	},
	struc : '\
	<!--<div id="blog2008Box">-->\
		<div id="blog2008Shadow"></div>\
		<div id="blog2008">\
			<div id="blog2008Title"><img src="http://blogimg.sinajs.cn/images/sample.template/component/2008_float_06.gif" /><a href="javascript:;" id="blog2008close">&nbsp;</a></div>\
			<div id="blog2008Cont">\
			<table width="198" cellpadding="0" cellspacing="0" class="my2008">\
				 <tr>\
					<td class="my2008head" id="my2008head">\
					<div id="cateTitle">本期参加“我记录”活动情形</div>\
					<div class="cateDate" id="cateDateCont">\
						<div id="cateDate"></div>\
						</div>\
					<div class="my2008body" id="my2008content">\
					<div style="text-align:center;padding:10px;">数据正在加载中...</div>\
					</div>\
				  </tr>\
				  <tr id="infoFoot">\
					<td  style="text-align:center" class="my2008foot"><a href="http://my2008.sina.com.cn/blog" target="_blank" class="mg" style="color:#D13600;text-decoration:underline;">活动首页</a><a id="curr"  style="color:#D13600;text-decoration:underline; visibility:hidden">博主本期文章</a></td>\
				  </tr>\
				</table>\
			</div>\
		</div>\
	<!--</div>-->\
	'
}
function showMyRecordDiv(e) {
	scope.recordPopup.show(e);
}
function initMyRecordFloat() {
	scope.recordPopup = new MyRecordPopup();
}
var Module = Class.create();
Module.prototype = {
  serial : [],
  index : -1,
  initialize : function () {
    if (!scope.$isAdmin) {
      return;
    }
    this.serial = ArrayWithout(window.scope.componentsName, "blog_counter", "blog_feeds_addr", "");
    this.serial.each(function(compId, index) {
      var instance = this.getInstance(compId);
      if (!instance) return;
      instance.style.position = "static";
      instance.resignPosition = this.resignPosition.bind(instance);
      instance.resignArrange = this.resignArrange.bind(instance);
      instance.getPrevComp = function () {
        var prevComp = this.previous(".component");
        return prevComp || null;
      }
      instance.getNextComp = function () {
        var nextComp = this.next(".component");
        return (nextComp && nextComp.id != 'blog_counter' && nextComp.id != "blog_feeds_addr") ? nextComp : null;
      }
      instance.resignPosition();
      instance.Frame = this;
      var handle = descByIds(instance, "#table>componentBar");
      $Drag.init(instance, handle, true, false);
      instance.onDragStart = this.onStart.bind(instance).combine(function () {
        this.index = this.serial.findit(instance.comp.key);
        this._hideFlash();
      }.bind(this));
      instance.onDrag = this.onDrag.bind(instance);
      instance.onDragEnd = this.onEnd.bind(instance).combine(this.save.bind(this));
    }.bind(this));
  },
  getInstance : function (component_id) {
    var t = componentsConfig[component_id];
    if (t)  return t.compInstance;
  },
  resignPosition : function () {
    this.style.left = this.getLeft() + "px";
    this.style.top = this.getTop() + "px";
  },
  resignArrange : function () {
    var prevComp = this.getPrevComp();
    var nextComp = this.getNextComp();
    this._top = prevComp ? prevComp.getTop() + parseInt(prevComp.getHeight()) / 2 : -Infinity;
    this._down = nextComp ? nextComp.getTop() + parseInt(nextComp.getHeight()) / 2 - parseInt(this.getHeight()) : Infinity;
  },
  onStart : function () {
    this.resignPosition();
    this.style.width = "210px";
    var replace_html = '<div id="__replace_box" style="border:1px dashed #2FCC00; margin-bottom:4px;\
		width:' + (parseInt(this.getWidth()) - 2) + 'px;\
		height:' + (parseInt(this.getHeight()) - 2) + 'px;"> \
		<\/div>';
    new Insertion.After(this, replace_html);
    this.style.position = "absolute";
    var prevComp = this.getPrevComp();
    var nextComp = this.getNextComp();
    if (prevComp)  prevComp.resignPosition();
    if (nextComp)  nextComp.resignPosition();
    this.resignArrange();
    this.opacity(50);
  },
  onDrag : function (left, top) {
    if (top < this._top) {
      var moveobj = this.previous(".component");
      insertAfter(moveobj, $("__replace_box"));
      this.resignArrange();
      moveobj.resignPosition();
      var Mod = this.Frame;
      Mod.serial = Mod.serial.up(Mod.index, 1);
      Mod.index--;
    }
    else if (top > this._down) {
      var moveobj = this.next(".component");
      scope.$Layout.moveComp(moveobj, {before:this})
      this.resignArrange();
      moveobj.resignPosition();
      var Mod = this.Frame;
      Mod.serial = Mod.serial.down(Mod.index, 1);
      Mod.index++;
    } else {
    }
  },
  onEnd : function () {
    this.opacity(100);
    this.style.position = "static";
    this.style.width = "100%"
    $("__replace_box").remove();
    this.resignPosition();
  },
  save : function () {
    this._showFlash();
    if (this.serial.join("|") == window.scope.componentsName.join("|")) {
      return;
    }
    this.serial = ArrayWithout(this.serial, "");
    var colData = '"' + this.serial.join('","') + '"';
    var option = {};
    var newSerial = this.serial;
    option.onStart = function() {
      window.scope.globalTip.onProgress();
    };
    option.onComplete = function(e) {
      if (e == "OK") {
        window.scope.componentsName = newSerial.slice(0);
        window.scope.globalTip.onComplete();
      } else if (e == "ERROR") {
        window.scope.globalTip.onError();
      } else {
      }
    };
    option.post = {
      col : colData
    }
    new Ijax("http://conf.blog.sina.com.cn/cnfdich", option);
  },
  deleteComponent : function (compId) {
    this.serial = this.serial.without(compId);
    window.setTimeout(this.save.bind(this), 50);
  },
  flashComp : ['myCalendar','myalbum','music','vblog'],
  _showFlash : function () {
      this.flashComp.each(function(e) {
		try {
			$(e).style.visibility = "visible";
		} catch(e) {}
      });
  },
  _hideFlash : function () {
      this.flashComp.each(function(e) {
		try {
			$(e).style.visibility = "hidden";
		} catch(e) {}
      });
  }
}
var ManageComponent = Class.create();
ManageComponent.prototype = {
  initialize : function () {
    this.initDom();
  },
  _show : function () {
    this.contEl.show();
    this._resize();
    this.initEvent();
    this.loadData();
  },
  _resize : function () {
    this.resizeIframeBlock();
  },
  initDom : function () {
    var MCContent = $C("div");
    MCContent.id = "MCContent";
    MCContent.innerHTML = this.struc;
    MCContent.style.display = "none";
    document.body.appendChild(MCContent);
    elementMethods.displayToggle("olimpicModule");
    elementMethods.displayToggle("basicModule");
    elementMethods.displayToggle("diyModule");
    $addEvent2('olimpicModule', this._resize.bind(this), "click");
    $addEvent2('basicModule', this._resize.bind(this), "click");
    $addEvent2('diyModule', this._resize.bind(this), "click");
    this.contEl = $("MCContent");
    IframeBlock.init("MCContent", "manageComp_list", this);
    this.contEl.middle();
  },
  loadData : function () {
    var basicModuleContent = $("basicModuleContent");
    var clist = window.scope.componentsName.join(",");
    var html = "";
    function getN(v) {
      var n = 11 - v.length * 2 < 0 ? 0 : 11 - v.length * 2;
      var s = "            ";
      return v + s.substr(0, n).replace(/ /g, "&nbsp;");
    }
    this.listCfg.each(function(e) {
      var contHtml = "";
      e.each(function(blogid) {
        var cfg = componentsConfig[blogid];
        var checked = clist.indexOf(blogid) != -1 ? "checked" : "";
        var n = getN(cfg.compName);
        contHtml += '<input type="checkbox" ' + checked + ' id="' + blogid + '" /><label for="' + blogid + '">' + n + '</label>';
      });
      html += "<div>" + contHtml + "</div>"
    });
    this.CACHE_diy_basics = basicModuleContent.innerHTML = html;
	var olimpicModuleContent = byId("olimpicModuleContent");
	html = "";
	this.olimpicCfg.each(function(blogid){
		var cfg = componentsConfig[blogid];
        var checked = clist.indexOf(blogid) != -1 ? "checked" : "";
        var n = getN(cfg.compName);
        html += '<input type="checkbox" ' + checked + ' id="' + blogid + '" /><label for="' + blogid + '">' + n + '</label>';
	})
	olimpicModuleContent.innerHTML = "<div>"+html+"</div>";
    this.loadDiyData(true, true);
    window.setTimeout(this._resize.bind(this), 50);
  },
  loadDiyData : function (isLabel, isBm) {
    var uid = getAuthorUID();
    var url = "http://my.blog.sina.com.cn/myblog/blog4/get_usermodule.php?suid=" + uid;
    function getN(v) {
      var n = 11 - v.length * 2 < 0 ? 0 : 11 - v.length * 2;
      var s = "            ";
      return v + s.substr(0, n).replace(/ /g, "&nbsp;");
    }
    function sier(m, v, i) {
      var compId = v.type + "|" + v.dbid;
      var checked = clist.indexOf(v.type + " " + v.dbid) != -1 ? "checked" : "";
      var n = getN(v.name);
      m += '<input type="checkbox" ' + checked + ' id="' + compId + '" /><label for="' + compId + '">' + n + '</label>';
      return m;
    };
    var clist = window.scope.componentsName.join(",");
    var label_default = '暂时没有空白面板，请<a id="label_diy" href="javascript:;">新增</a>空白面板。';
    var bm_default = '暂时没有链接列表，请<a id="bm_diy" href="javascript:;">新增</a>链接列表';
    var tb = this.manageBm;
    var lb = this.manageLabel;
    var resize = this._resize;
    $ScriptLoader.request(url, {
      onComplete : function (data) {
        var o = data.j2o() || [];
        var diy_label_comps = [];
        var diy_bm_comps = [];
        o.each(function(e) {
          if (e.type == "blog_diy_label")
            diy_label_comps.push(e);
          else if (e.type == "blog_diy_bm")
            diy_bm_comps.push(e);
        })
        if (isBm) {
          byId("diy_bmts").innerHTML = diy_bm_comps.length == 0 ? bm_default : diy_bm_comps.inject("", sier);
          if (diy_bm_comps.length == 0)
            Event.observe("bm_diy", "click", tb);
        }
        if (isLabel) {
          byId("diy_labels").innerHTML = diy_label_comps.length == 0 ? label_default : diy_label_comps.inject("", sier);
          Event.observe("label_diy", "click", lb);
        }
      }
    });
  },
  initEvent : function () {
    $Drag.init("MCContent", "manageComp_titl");
    Event.observe("cp_close_btn", "click", function() {
      $("MCContent").hide();
    });
    Event.observe("manageComp_bt_ok", "click", this.save);
    Event.observe("manageComp_bt_cancel", "click", function () {
      $("MCContent").hide();
    });
    Event.observe("diy_label2", "click", this.manageLabel);
    Event.observe("diy_bm2", "click", this.manageBm);
  },
  save : function () {
    var isDelCache = false;
    var serial = window.scope.componentsName.without("", "blog_counter", "blog_feeds_addr");
    var selectList = [];
    var allList = $("manageComp_tabs").getElementsBySelector("input[type=checkbox]");
    allList.each(function (e) {
      if (e.checked)  selectList.push(e.id.replace("|", " "));
    })
    var serialText = serial.join(",");
    var selectListText = selectList.join(",");
    serial.each(function (e) {
      if (selectListText.indexOf(e) == -1) {
        serial = serial.without(e);
      }
    })
    selectList.each(function (e) {
      if (serialText.indexOf(e) == -1) {
        serial.push(e);
        isDelCache = true;
      }
    })
    var colData = '"' + serial.join('","') + '"';
    var option = {};
    option.onStart = function() {
    };
    option.onComplete = function(e) {
      if (e == "OK") {
        window.location.href = window.location.href + isDelCache ? "?edit" : "";
      } else if (e == "ERROR") {
      } else {
      }
    };
    option.post = {
      col : colData
    }
    new Ijax("http://conf.blog.sina.com.cn/cnfdich", option);
  },
  _shadow : function () {
    $("manageComp_shad").setStyle({
      height : $("manageComp_list").getStyle("height")
    });
  },
  manageBm : function () {
    var editURL = "http://my.blog.sina.com.cn/myblog/blog4/staticinter.php?module=blog_diy_bm";
    window.open(editURL, "", "width=690,height=550,left=" + (window.screen.width - 690) / 2 + ",top=" + (window.screen.height - 550) / 2);
  },
  manageLabel : function () {
    var editURL = "http://my.blog.sina.com.cn/section/label/label_list_static.php";
    window.open(editURL, "", "width=690,height=550,left=" + (window.screen.width - 690) / 2 + ",top=" + (window.screen.height - 550) / 2);
  },
  struc : '\
		<div id="manageComp_list">\
			<div id="manageComp_titl">\
			<div id="helpMsg">您可以在此显示或隐藏个人首页的内容模块</div>\
			<input type="button" id="cp_close_btn" style="width:17px;height:17px;left:477px;" /></div>\
			<div id="manageComp_tabs">\
				<div class="group">\
					<div id="olimpicModule" toggle="olimpicModuleContent" class="active"><span style="color:#FF0000;">我的2008活动模块<a href="http://my2008.sina.com.cn/index1.shtml" target="_blank" style="text-decoration:underline;color: #000000;">(参与“我的2008--我记录活动”，赢现金大奖！)</a></span></div>\
					<div id="olimpicModuleContent">数据加载中...</div>\
				</div>\
				<div class="group">\
					<div id="basicModule" toggle="basicModuleContent" class="active"><span>基本模块</span></div>\
					<div id="basicModuleContent">数据加载中...</div>\
				</div>\
				<div class="group">\
					<div id="diyModule" toggle="diyModuleContent" class="active"><span>自定义模块</span></div>\
					<div id="diyModuleContent">\
						<div class="ModuleTitle">&nbsp;自定义空白面板：<span>[<a id="diy_label2" href="javascript:void(0)">管理</a>]</span></div>\
						<div id="diy_labels">数据加载中...</div>\
						<div class="ModuleTitle">&nbsp;自定义链接面板：<span>[<a id="diy_bm2" href="javascript:void(0)">管理</a>]</span></div>\
						<div id="diy_bmts">数据加载中...</div>\
					</div>\
				</div>\
			</div>\
			<div id="manageComp_bts"><input type="button" id="manageComp_bt_ok" /><input type="button" id="manageComp_bt_cancel" /></div>\
		</div>\
		<!--<iframe id="blockFrame" frameborder=0></iframe>-->\
		<div id="manageComp_shad">2</div>\
	',
  listCfg : [
      ['blog_photo','blog_last_gbook','blog_diy_cboard','blog_calendar','blog_zone'],
      ['blog_boke','blog_myalbum','blog_diy_music'],
      ['blog_circle_left','blog_friend','blog_visit'],
      ['blog_last_post','blog_sort','blog_diy_serial','blog_last_comment','blog_loverelay']
      ],
	  olimpicCfg : ['blog_2008mark', 'blog_sunplayground']
}
var changeName = {
  $:function(id) { return document.getElementById(id) },
  node:{blogName:{},changeName:{},nameInput:{},changeBut:{},cancelBut:{},changeMessage:{}},
  mess:["提示：最多24个字符（包括24）或12个汉字",
      "您还可以输入",
      "！以达到字符输入上限，不能继续输入",
      "很抱歉！BLOG标题不能包含sina等特殊词哦~~请重新输入<br/>提示：BLOG标题只能输入中文、英文、数字及下划线.",
      "BLOG标题设置不能为空.",
      "很抱歉，系统繁忙，请稍后再试！"
      ],
  reg:[/sina/i], 
  hide:function (ele) {
    ele.style.display = "none";
  },
  hide1:function(ele) {
    ele.style.visibility = "hidden";
  },
  show:function(ele) {
    ele.style.display = "";
  },
  show1:function(ele) {
    ele.style.visibility = "visible";
  },
  showEdit:function() {
    var bn = this.node.blogName;
    var cn = this.node.changeName;
    var ni = this.node.nameInput;
    var cm = this.node.changeMessage;
    var canb = this.node.cancelBut;
    this.show(bn);
    this.show(cn);
    this.hide1(ni);
    cm.innerHTML = this.mess[0];
    this.hide(cm);
    this.hide(canb);
  },
  disabled:function() {
    var ni = this.node.nameInput;
    var chb = this.node.changeBut;
    var canb = this.node.cancelBut;
    canb.disabled = "disabled";
    ni.disabled = "disabled";
    chb.disabled = "disabled";
  },
  cancelDisable:function() {
    var ni = this.node.nameInput;
    var chb = this.node.changeBut;
    var canb = this.node.cancelBut;
    canb.disabled = "";
    ni.disabled = "";
    chb.disabled = "";
  },
  isEdit:null,
  init:function() {
    this.initNode();
    this.initView();
    this.node.changeBut.onclick = this.editObserver;
    this.node.cancelBut.onclick = this.cancelObserver;
  },
  initNode:function() {
    for (name in this.node) {
      this.node[name] = this.$(name);
    }
  },
  initView:function() {
    var _this = this;
    var cm = this.node.changeMessage;
    var bn = this.node.blogName;
    var blogui = "http://blogui.sinajs.cn/ui";
    var url = blogui + "?t=t&" + uid;
    $ScriptLoader.request(url, {
      onComplete:function (text) {
        bn.innerHTML = text;
        if (!_this.oldName)_this.oldName = text;
        _this.showEdit();
        _this.initPosition();
      },
      charset : "gb2312"
    });
  },
  initPosition:function() {
    var bn = this.node.blogName;
    var cn = this.node.changeName;
    var ni = this.node.nameInput;
    var cm = this.node.changeMessage;
    var bnTop = bn.offsetTop;
    var bnLeft = bn.offsetLeft;
    cn.style.top = (bnTop - 3) + "px";
    cn.style.left = bnLeft + "px";
    ni.style.width = bn.offsetWidth + "px";
    cm.style.left = (parseInt(ni.style.width) + 140) + "px";
  },
  editObserver:function() {
    changeName.swapEditMode();
  },
  cancelObserver:function() {
    changeName.cancelChange();
  },
  interval:null,
  swapEditMode:function() {
    var _this = this;
    var bn = this.node.blogName;
    var ni = this.node.nameInput;
    var cm = this.node.changeMessage;
    var chb = this.node.changeBut;
    var canb = this.node.cancelBut;
    if (this.isEdit) {
      if (!this.reg[0].test(ni.value)) {
        if (this.checkTitle() >= 0) {
          try {
            clearInterval(interval)
          } catch(e) {
          }
          ni.onkeydown = function() {
          };
          this.doGet(ni.value, {
            onComplete:function (text) {
              if (text > 0) {
                changeName.isEdit = false;
                changeName.initView();
                chb.value = "编辑";
                _this.showEdit();
                _this.initPosition();
                _this.cancelDisable();
              } else {
                if (text == -2) {
                  changeName.node.changeMessage.innerHTML = changeName.mess[4];
                } else if (text == -3) {
                  changeName.node.changeMessage.innerHTML = changeName.mess[2];
                } else if (text == -4) {
                  changeName.node.changeMessage.innerHTML = changeName.mess[3];
                } else if (text == -5) {
                  changeName.node.changeMessage.innerHTML = changeName.mess[5];
                }
                cm.className = "errorMessage";
                _this.cancelDisable();
                ni.focus();
                ni.onkeydown = _this.inputKeyDown;
              }
            }
          });
        }
      }
    } else {
      ni.value = bn.innerHTML;
      this.hide(bn);
      this.show1(ni);
      cm.innerHTML = this.mess[0];
      ni.onkeydown = this.inputKeyDown;
      ni.focus();
      chb.value = "保存";
      this.show(chb);
      this.show(canb);
      this.show(cm);
      this.isEdit = true;
    }
  },
  inputKeyDown:function() {
    var cm = changeName.node.changeMessage;
    var ni = changeName.node.nameInput;
    interval = setInterval(function () {
      var checkNum = changeName.checkTitle();
      if (checkNum > 0) {
        cm.innerHTML = changeName.mess[1] + checkNum + "个字符。";
      } else {
        cm.innerHTML = changeName.mess[Math.abs(checkNum)];
      }
    }, 50);
    ni.onkeydown = "";
  },
  cancelChange:function() {
    try {
      clearInterval(this.interval)
    } catch(e) {
    }
    var _this = this;
    var bn = _this.node.blogName;
    var cn = _this.node.changeName;
    var ni = _this.node.nameInput;
    var cm = _this.node.changeMessage;
    var chb = _this.node.changeBut;
    var canb = _this.node.cancelBut;
    ni.disabled = "";
    chb.disabled = "";
    chb.value = "编辑";
    _this.show(bn);
    _this.initPosition();
    _this.hide(canb);
    _this.hide1(ni);
    _this.hide(cm);
    _this.isEdit = false;
    _this.cancelDisable();
  },
  doGet:function(name, option) {
    var now = new Date();
    var url = "http://my.blog.sina.com.cn/myblog/blog4/modify_blogtitle.php?title=" + encodeURIComponent(name) + "&time=" + now.getTime();
    this.disabled();
    new window.scope.Ijax(url, option);
  },
  checkTitle:function() {
    var nameInput = this.node.nameInput;
    var cm = this.node.changeMessage;
    var length = this.getStrLength(nameInput.value);
    var isVa = this.reg[0].test(nameInput.value);
    if (length < 1) {
      cm.className = "errorMessage";
      return -4;
    }
    if (isVa) {
      cm.className = "errorMessage";
      return -3;
    }
    if (length <= 24 && !isVa) {
      cm.className = "";
      return (24 - length);
    } else {
      nameInput.value = nameInput.value.substring(0, 24);
      cm.className = "errorMessage";
      return -2;
    }
  },
  getStrLength:function (str) {
    var num = 0;
    for (i = 0; i < str.length; i++) {
      if (!(((str.charCodeAt(i) >= 0x3400) && (str.charCodeAt(i) < 0x9FFF)) || (str.charCodeAt(i) >= 0xF900))) {
        num++
      }
    }
    return (str.length - num) * 2 + num;
  }
}
var IframeBlock = new Object();
IframeBlock.init = function (containerElement, contentElement, objRel)
{
	var contain = byId(containerElement);
	var content = byId(contentElement);
	var iframe = document.createElement("iframe");
	iframe.id = contentElement + "_iframeBlock";
	contain.appendChild(iframe);
	objRel.resizeIframeBlock = function()
	{
		iframe.style.width = parseInt(content.clientWidth) + 2 + "px";
		iframe.style.height = parseInt(content.clientHeight) + 2 + "px";
	}
	objRel.resizeIframeBlock();
}
window.$util = {
  $ : function (id, doc){
    return (doc || document).getElementById(id);
  },
  $$ : function (ids, root){
    var ar = ids.split(".");
    var i = 0;
    root = root || (i++, $util.$(ar[0]));
    if (root == null) return null;
    for (;i<ar.length;i++){
      var id = ar[i];
      if (id == "") continue;
      if (ar[i-1]=="") {//deal ".." symbol, to find element in all descendants.   
        var _al = root.getElementsByTagName("*"), _l = _al.length;        
        for (var k = 0;k<_l; k++){
          if (_al[k].id == id) {
            var s = $util.$$(ar.slice(i+1).join("."),_al[k]);
            if (s != null) return s;
          }
        }
        return null;        
      } else {
        var sb = root.childNodes, jl = sb.length;
        for (var j=0;j<jl; j++){
          var n = sb[j];
          if (n.nodeType == 1 && n.id == id){ //get the matching element          
            root = n;
            break;
          }
        }
        if (j == jl) return null;
      }     
    }
    return root;
  }
}
window.$str = {
  trim : function (str){
    return $str.trimTail($str.trimHead(str));
  },
  trimHead : function (str){
    return str.replace(/^(\u3000|\s|\t)*/gi,"");
  },
  trimTail : function (str){
    return str.replace(/(\u3000|\s|\t)*$/gi,"");
  },
  getStrWrap : function (str,charset){    
    var ar = str.replace(/([\u00ff-\uffff])/gi,"$1\01").split("");
    ar.$substr = $str.__substr;
    return ar;
  },  
  __substr : function (start,len){
    if (this[start]=="\01") start--;
    var end = start + len ;
    if (this[end]=="\01") end--;
    return this.slice(start,end-1).join("").replace(/\01/gi,"");
  },  
  getShort : function (str,len){
    var aln = $str.getStrWrap(str), al = aln.length;
    if (al > len) str = aln.$substr(0,len) + "..";
    return str;
  }
}
window.acmd = new AnchorCommand(window);
acmd.setExecutor("sld",function (type, data){
  var pid, idx;
  if (type == "pid"){
    pid = data;
    idx = window.$Album.picHash[pid].idx;
  } else if (type == "idx"){
    idx = parseInt(data);
    if (idx < 0) idx = window.$Album.pics.length + idx;
  }
  displayPic(idx);
});
window.initAlbum = function (){
  window.$Album = window.$Album || {};
  window.$Album.pics = [];
  window.$Album.picHash = {};
  window.currentSlide = null;
}
function init_album_pic(){
  window.acmd.runCommands();
  window.descByIds("#picSlide#img>image").onload = autoSize.bind(window.parent, window.frameElement);
}
window.addSlideCmd = function (idx, page){
  var url = idx < 0 ? $("prevPage").href : $("nextPage").href;
  if (page != null){
    url = scope.$Url("album_pic", {album_id:album_id, page:page});
  }
  window.acmd.setUrl(url);
  window.acmd.setCommand("sld", ["idx", idx]);
  scope.tmpWin = window;
  window.location.href = window.acmd.getUrlStr();
}
window.pushPic = function (pid, pname, surl, furl){
  var item = {
      idx   : window.$Album.pics.length,                      
      pid   : pid,
      pname : pname,
      surl  : surl,
      furl  : furl
  };
  window.$Album.pics.push(item);
  window.$Album.picHash[pid] = item;
}
window.setCurrentPage = function (cur, total){
  window.currentPage = cur;
  window.totalPage = total;
}
window.displayPic = function (i){
  i = i == null ? 0 : i;            //default to 1st pic in current page
  var pid;
  if (typeof(i) == "string"){       //param is pid
    pid = i;
    i = findIndexByPid(pid);
  } else {                          //param is index in current page
    pid = window.$Album.pics[i];
  }
  if (i == null) return;
  currentSlide = i;
  var pic = window.$Album.pics[i];
  setSlideImg(pic.surl, pic.furl);
  setSlideTitle(pic.pname);
  toggleSlide(true);
  fixSlidePaging();
  var scrips = document.getElementsByTagName("script");
  for (var i=0; i<scrips.length; ++i){
    var e = scrips[i];
    if (e.src.indexOf("hits?") >-1){
      var ns = document.createElement("script");
      ns.src=e.src;
      document.body.appendChild(ns);
      break;
    }
  }
}
window.hasPrevPage = function (){
  return $("prevPage").visible();
}
window.hasNextPage = function (){
  return $("nextPage").visible();
}
window.fixSlidePaging = function (){
  var alb = window.$Album;
  var hasNext = !(currentSlide == alb.pics.length-1 && !hasNextPage());
  var hasPrev = !(currentSlide == 0 && !hasPrevPage());
  if (hasNext) 
    togglePicFlip("nextPic",true);
  else 
    togglePicFlip("nextPic",false);
  if (hasPrev) 
    togglePicFlip("prevPic",true); 
  else 
    togglePicFlip("prevPic",false);
  var sldNode = $("slide");
  var ttNode = sldNode.down("#total");
  var pp1 = sldNode.down("#picPage");
  var pp2 = sldNode.down("#picPage2");
  pp2.innerHTML = pp1.innerHTML.replace(/_extended\=\"true\"/g, "");
  pp2.down("#totalDiv").hide();
}
window.togglePicFlip = function (id, flg){
  var alb = window.$Album;
  var sld = $("slide");
  var paging = sld.down("#picPage");
  var tag = paging.down("#"+id);
  var greyTag = paging.down("#"+id+"Gray");
  if (flg) {
    tag.show();
    greyTag.hide();
  }
  else {
    tag.hide(); 
    greyTag.show();
  }
}
window.findIndexByPid = function (pid){
  if (window.$Album.picHash[pid] == null) return null;
  var ar = window.$Album.pics;
  for (var i=0; i<ar.length; ++i){
    if (ar[i].pid == pid) return i;
  }
  return null;
}
window.toggleSlide = function (t){
  t = t != false;
  $("slide").style.display = t ? "block" : "none";
  $("pics").style.display = t ? "none" : "block";
}
window.setSlideImg=function (url, fullUrl){
  var img = $("slide");
  img = img.down("#picSlide");
  img = img.down("#image");
  var imgLink = img.parentNode;
  img.src = url;
  imgLink.href = "/main/html/showpic.html#url=" + fullUrl;
  img.onload=scope.autoSize.bind(window).combine(function (){}).delay(500);
}
window.getSlideImgUrl = function (){
  var img = $("slide").down("#picSlide").down("#image");
  var url = img.src;
  return (url.match(/\/([^\/]*)$/) || [])[1];
}
window.setSlideTitle=function (txt){
  $util.$$("slide.picSlide..title").innerHTML = $str.getShort(txt,40);
}
window.flipPic=function (i){
  i = i > 0 ? 1 : -1;
  var p = currentSlide + i;
  if (p < 0) 
    addSlideCmd(-1);
  else if (p >= window.$Album.pics.length) 
    addSlideCmd(0);
  else 
    displayPic(p);
}
window.toFirst = function (){
    addSlideCmd(0, 1);
}
window.toLast = function (){
  addSlideCmd(-1, window.totalPage);
}
window.gotoPage = function (i){
  var x = parseInt(i);
  if (!isNaN(x)) {
    document.getElementById("pageNum").value=x;
    if (x>totalPage || x<=0) {
      alert("没有此页");
      return false;
    } else {
      location.href = scope.$UrlPattern.get("album_pic", {album_id:album_id, page:x});
      return false;
    }
    } else {
      alert("没有输入正确的页数");
      return false;
    }
  }       
window.initAlbumSelector = function(){
  window.$Album           = window.$Album || {};
  window.$Album.albums    = [];
  window.$Album.albumHash = {};
}
window.init_album_icon_slide = function(){
  window.currentId     = parent.album_id;
  if (window.currentId == null) {
    scope.fatal("cant find album_id");
    return;
  }
  window.displayAmount = 5;
  window.listHolder    = $("albumListHolder");
  window.tables        = listHolder.getElementsByTagName("table");
  window.position      = window.$Album.albumHash[window.currentId];
  window.total         = tables.length;
  var rg = getWindowRange(window.position, window.total);
  for (var i=0; i<total; i++){
    var tb = tables[i];
    var divs = tb.getElementsByTagName("div");
    for (var j=0; j<divs.length;j++){
      if (divs[j].id == "mark"){
        tb.markElm = divs[j];
        break;
      }
    }
    if (i >= rg.l && i <= rg.r){
      showAlbum(i);
    } else {
      hideAlbum(i);
    }
    if (tb.id != currentId){
      setMark(i,false);
    } else {          
      setMark(i,true);
      curIdx = i;
      window.position = i;
    }
  }
  window.position = rg.l;
}
window.getWindowRange = function (i, len){
  var span = window.displayAmount;
  span = span > len ? len : span;
  var l = i, r = i;
  while (r - l + 1 < span){
    --l;
    ++r;
    if (l < 0) ++l;
    if (r >= len) --r;
  }
  return {l:l, r:r};
}
window.pushAlbum = function(aid){
  window.$Album.albumHash[aid] = window.$Album.albums.length;
  window.$Album.albums.push(aid);
}
window.refresh = function (){
  var fr = $("gallery");
  var r = fr.style.display;
  fr.style.display="none";
  fr.style.display=r;
}
window.setMark = function (i,f){
  window.tables[i].markElm.style.display = f ? "" : "none";
}
window.preAlbum = function (){
  var i = window.position, t = i > 0;
  t ? (i = --window.position, hideAlbum(i + 5), showAlbum(i)) : null;   
  refresh();//opera bug   
}
window.nextAlbum = function (){       
  var i = window.position, t = i < (window.total - 5);
  t ? (hideAlbum(i), showAlbum(i + 5), ++window.position) : null;
  refresh();//opera bug
}
function hideAlbum(i){
  window.tables[i].style.display = "none";
}
function showAlbum(i){
  window.tables[i].style.display = "";
}
var TPLINIT = true;
var THEME = window.scope.config.theme;
var sBanner = window.scope.config.customTheme.bannar;
function saveTpl(code){
	if(THEME==10)
		if(BusinessTheme.changeMode())
			return ;
	if(!TPLINIT) return;
	TPLINIT = false;
	var theme = code.split('_')[0];
	var sid = code.split('_')[1];
	var paraStr = conf.data[theme].conf[sid];
	var keys = {	
	  d : 'calendar',
	  a : 'photo',
	  b : 'bannar',
	  c : 'menu',
	  e : 'box_1',
	  f : 'box_2',
	  m : 'bg',
	  k : 'music'
	}
	_para = paraStr.split(",");
	for(var i=0;i<_para.length;i++){
		_para[i] = _para[i].replace(/([a-z])(\d+)/ig,function($0,$1,$2){
			return $1 + (parseInt($2) + 0);
		});
	}
	for(var i=0;i<_para.length;i++){
		var key = _para[i].replace(/[^a-z]/g,"");
		_para[i] = _para[i].replace(key,keys[key]+":");
	}
	paraStr = _para.join(",");
	var cssData = (parseInt(theme)+1)+"{"+ paraStr +",photo:1}";
	var option = {};
	option.onStart = function(){
		window.scope.globalTip.onProgress();
	};
	option.onComplete = function(e){
		scope.trace("result : "+e)
			if(e == "OK"){
				var reLoad = function(){
						window.scope.globalTip.onComplete();
						var lr = window.location;
						window.location.href = lr.href.replace(lr.search,"").replace(lr.hash,"") + "?tmpl";
				}
				new Ijax("http://my.blog.sina.com.cn/blog/resume_diy_css.php",{
					'onComplete': reLoad,
					'onException': reLoad
				});
			}else if(e == "ERROR"){
				window.scope.globalTip.onError();
			}else{
				window.scope.globalTip.onError();
			}
	};
	option.post = {
		css : cssData
	}
	new Ijax("http://conf.blog.sina.com.cn/cnfdich",option);
}
function initDom(){
	var tpl_cont = $C('div');
	tpl_cont.innerHTML = struc;
	tpl_cont.id='tpl_cont';
	tpl_cont.style.display = "none";
	$("innerBound").appendChild(tpl_cont);
	IframeBlock.init("tpl_cont", "tpl_list", this);	
}
function initData(){
	var Data = newConf.data;
	for(var i=0;i<Data.length;i++){
		var groupDiv = $C('div');
		groupDiv.className = 'group';
		groupDiv.innerHTML ='\
			<div class="unactive" id="tpl_tab'+ i +'"><span>'+ Data[i].name +'</span></div>\
			<div class="tpl_list_div" id="tpl_box'+i+'"></div>\
		';
		$('tpl_tabs').appendChild(groupDiv);
		setEvent(i);
	}
		$addEvent2('change_btn',function(){
			show_tpl();
			return false;
		},'click')
		$addEvent2('close_btn',function (){
			$('tpl_cont').style.display = 'none';
			var lr = document.location.href;
			if(/\?tmpl/.test(lr)){
				document.location.href = lr.substr(0,lr.indexOf('?'))+"?edit";
			}
			if(window.scope.CustTpl.isEdit) document.location.href = lr.replace(/\?.+/,'');
		},'click');
		$addEvent2('diy_btn',function(){
			window.open("http://my.blog.sina.com.cn/theme/step1.html","","width=538,height=525,left=" + (window.screen.width-538)/2 + ",top=" + (window.screen.height-525)/2);
		},'click');
		var shining = setInterval(function(){
			$('tpl_msgs').style.color = ($('tpl_msgs').style.color == '#428eff') ? '#005aff' : '#428eff';
		},500);
}
function show_tpl(){
	$('tpl_cont').style.display = '';
	try{
		$('tpl_cont').style.left = (getWinSize().width - 378)/2+'px';
		$('tpl_cont').style.top = '210px';
	}catch(e){};
        if(typeof initOpenFlag == 'undefined'){
               initOpen(initCodes);
               $Drag.init('tpl_cont','tpl_titl');
        }
	initCustEvents();
	window.setTimeout(function(){
		setRightMark(getInitTheme(THEME),parseInt(sBanner));
	},500);
}
function initOpen(initCodes){
	for(var i=0;i<initCodes.length;i++)
		inju(initCodes[i]);
	initOpenFlag = true;
}
function setEvent(id){
	$('tpl_box'+id).style.display = 'none';
	$addEvent2('tpl_tab'+id,function(){
		var tab = $('tpl_tab'+id);
		if(tab.className == 'active')
			setO(id,false);
		else
			setO(id,true);
		listPics(id);
	},'click');
}
function setO(id,iso){
	$('tpl_tab'+id).className = iso ? 'active' : 'unactive';
	$('tpl_box'+id).style.display = iso ? '' : 'none';
	shadow();
}
function checkO(id) {
	return $('tpl_box'+id).style.display == '';
}
function inju(id){
	setO(id,true);
	listPics(id);
}
function shadow(){
	var shadowHeight = 259;
	for(var i=0;i<newConf.data.length;i++){
		if($('tpl_tab'+i).className == 'active'){
			var Data = newConf.data[i].conf;
			var row = Math.ceil(Data.length/5);
			shadowHeight += row*60;
			shadowHeight += 5;
		}
	}
	$('tpl_shad').style.height = shadowHeight;
	window.setTimeout(this.resizeIframeBlock.bind(this), 50);
}
function listPics(theme){
	var Data = newConf.data[theme].conf;
	var tab = $('tpl_tab'+theme);
	var box = $('tpl_box'+theme);
	if(tab.alt == 'init') return true;;
	tab.alt = 'init';
	var table = $C('table');
	table.border = 0;
	table.cellspacing = 0;
	table.cellpadding = 0;
	var tbody = $C('tbody');
	var row = Math.ceil(Data.length/5);
	if(theme==7 && Data.length==0){
		var tr = $C('tr');
		var td = $C('td');
		var div=$C('div');
		div.innerHTML="目前没有商业模板。";
		td.appendChild(div);
		tr.appendChild(td);
		tbody.appendChild(tr);
	}else{
		for(var i=0;i<row;i++){
			var tr = $C('tr');
			for(var j=0;j<5;j++){
				var td = $C('td');
				var id = i*5+j;
				if(id>=Data.length) break;
				var a = $C('a');
				var cfg = Data[id];
				a.alt = cfg.oTheme+'_'+cfg.oid;
				a.href = 'javascript:;';
				var num;
				if(cfg.oTheme!=9){
					num=(cfg.oid+1);
				}else{
					Data[id].cfg.replace(/b(\d*)/,function(a,b){num=parseInt(b)});
				}
				a.innerHTML = '<span><div style="width:60px;height:50px;border:2px solid #FFFFFF;border-bottom:none;background:url(http://blogimg.sinajs.cn/images/tmp/'+cfg.oTheme+'/'+num+'.gif) no-repeat;"></div></span>';
				a.onclick = function(){
					try{
					saveTpl(this.alt);
					this.blur();
					}catch(e){}
				};
				td.appendChild(a);
				tr.appendChild(td);
			}
			tbody.appendChild(tr);
		};
	}
	table.appendChild(tbody);
	box.appendChild(table);
}
function setRightMark(theme,id){
	id = parseInt(id);
	var vid = null;
	var dataArr = newConf.data[theme].conf;
	for(var i=0;i<dataArr.length;i++){
		if(dataArr[i].cfg.indexOf('b'+id) != -1 && dataArr[i].oTheme == (parseInt(THEME)-1)){
			vid = i;
			break;
		}
	}
	removeNode('rm_cont');
	if(vid == null) return;
	var rm = $C('div');
	rm.className = 'right_mark';
	rm.style.display = "none";
	rm.innerHTML = '<img id="right_mark" src="http://blogimg.sinajs.cn/images/tmp/right_mark.gif" border="none">';
	rm.id = "rm_cont";
	rm.style.position = 'absolute';
	rm.style.left = (vid%5)*71 + 53 + 'px';
	rm.style.top = Math.floor(vid/5)*61 + 65 + 'px';
	rm.style.display = "";
	$('tpl_box'+theme).appendChild(rm);
	var curroTheme	= dataArr[vid].oTheme;
	var currOid			= dataArr[vid].oid + 1;
	var sUrl = 'http://blogimg.sinajs.cn/images/tmp/'+curroTheme+'/'+currOid+'.gif';
	setCustPic({type:'head', headUrl: sUrl, align: 'center center'}); //默认头图(缩图)
	var t   = THEME; //1 -> gif	2 -> jpg	3 -> gif	 4 -> jpg	5 -> gif	 6 -> jpg	7 -> jpg	8 -> gif
	var ext = (t==1||t==3||t==5||t==8)?'.gif':'.jpg';
	var sBg = window.scope.config.customTheme.bg + ext;
	var bgm = window.scope.CustTpl.basicThemeUrl + THEME + '/images/bg/' + sBg;
	setCustPic({type:'bg', bgUrl: bgm, align: 'center center'}); //默认背景图
}
var struc = '\
<div id="tpl_list">\
	<div id="tpl_titl"><div id="tpl_titl_dft">&nbsp;</div><div id="tpl_titl_cust">&nbsp;</div><input type="button" id="close_btn" style="width:17px;height:17px;left:350px;" /></div>\
	<div id="tpl_cust_cnt">\
			<iframe name="custPostFrame" id="custPostFrame" style="display:none" onload="if(this.actCb) custUploadCb(this.actCb);"></iframe>\
			<div class="group">\
				<div id="tpl_cust_tab0" class="active"><span>更换头图</span></div>	\
					<div id="tpl_cust_box0" class="tpl_list_div">\
						<ul class="cust_selecter">\
							<li>\
								<a href="javascript:;" id="cust_head_upload"><div id="head_upload_cover"></div></a>\
							</li>\
							<li>\
								<a href="javascript:;" id="cust_head_default" ><div class="cust_cover"></div></a>\
							</li>\
						</ul>\
						<div id="cust_head_cnt">\
							<div id="cust_head_uparea" style="display:none">\
								 <div class="triangle"></div>\
								 <form   name="userfile" id="cust_head_upForm" enctype="multipart/form-data"  target="custPostFrame" action="http://my.blog.sina.com.cn/blog/upload_diy_pic.php"  onsubmit="return doCustUpload(this);"  method="post">\
									<div id="head_upcnt" style="display:block">\
										<input type="file" name="fileContent"  id="head_file" ContentEditable="false" />\
										<input type="hidden" name="pic_type" value="1">\
										<input type="submit" value="上传" id="head_file_submit" disabled="true" />\
									</div>\
									<div id="head_upcnt_loading" style="display:none"></div>\
								 </form>\
								 <span id="head_uptips" style="display:block">支持大小不超过600k的jpg,gif,png图片，建议宽度为770象素</span>\
							</div>\
							<div id="cust_head_setting" style="display:none">\
								 <div class="triangle_set"></div>\
								<div  id="cust_head_reupload"><img src="http://blogjs.sinajs.cn/images/tmp/t_arrow.gif" alt="arrow" /><a href="javascript:;"  id="cust_head_reupload_link">重新上传自定义图片</a></div>\
								<img src="http://blogjs.sinajs.cn/images/tmp/t_line.gif" alt="line" />\
								<ul>\
									<li><h3>设置图片：</h3></li>\
									<li>\
										<label>平铺: </label>\
										<select id="head_tiled" onchange="showCustSetting(this);">\
											<option value="none">不平铺</option>\
											<option value="default" selected="true" >平铺</option>\
											<option value="h">横向</option>\
											<option value="v">纵向</option>\
										</select>\
									</li>\
									<li>\
										<label>对齐: </label>\
										水平方向 <select id="head_align_h" onchange="showCustSetting(this);">\
												<option value="default">默认</option>\
												<option value="left">左</option>\
												<option value="center">中</option>\
												<option value="right">右</option>\
												</select>\
										垂直方向 <select id="head_align_v" onchange="showCustSetting(this);">\
												<option value="default">默认</option>\
												<option value="top">上</option>\
												<option value="center">中</option>\
												<option value="bottom">下</option>\
											   </select>\
									</li>\
									<li><label for="head_height">高度: </label>\
											<input type="text" id="head_height" onblur="showCustSetting(this);"  maxlength="3" onkeyup="this.value=this.value.replace(/\\D/g,\'\')" onpaste="return false;" /> 象素<span id="head_height_tip" class="htips">(100-300象素)</span>\
									</li>\
								</ul>\
							</div>\
						</div>\
					</div>\
			</div>\
			<div class="group">\
				<div id="tpl_cust_tab1" class="active"><span>更换背景图</span></div>	 \
					<div id="tpl_cust_box1" class="tpl_list_div">\
						<ul class="cust_selecter">\
							<li>\
								<a href="javascript:;" id="cust_bg_upload"><div id="bg_upload_cover"></div></a>\
							</li>\
							<li>\
								<a href="javascript:;" id="cust_bg_default" ><div class="cust_cover"></div></a>\
							</li>\
						</ul>\
						<div id="cust_bg_cnt">\
							<div id="cust_bg_uparea" style="display:none">\
								 <div class="triangle"></div>\
								 <form   name="userfile" id="cust_bg_upForm" enctype="multipart/form-data"  target="custPostFrame" action="http://my.blog.sina.com.cn/blog/upload_diy_pic.php"  onsubmit="return doCustUpload(this);"  method="post">\
									<div id="bg_upcnt" style="display:block">\
										<input type="file" name="fileContent"  id="bg_file"  ContentEditable="false"  />\
										<input type="hidden" name="pic_type" value="2">\
										<input type="submit" value="上传" id="bg_file_submit" disabled="true" />\
									</div>\
									<div id="bg_upcnt_loading" style="display:none"></div>\
								 </form>\
								 <span id="bg_uptips" style="display:block">支持大小不超过600k的jpg,gif,png图片，建议宽度为770象素</span>\
							</div>\
							<div id="cust_bg_setting" style="display:none">\
								 <div class="triangle_set"></div>\
								<div  id="cust_bg_reupload"><img src="http://blogjs.sinajs.cn/images/tmp/t_arrow.gif" alt="arrow" /><a href="javascript:;"  id="cust_bg_reupload_link">重新上传自定义图片</a></div>\
								<img src="http://blogjs.sinajs.cn/images/tmp/t_line.gif" alt="line" />\
								<ul>\
									<li><h3>设置图片：</h3></li>\
									<li>\
										<label>平铺: </label>\
										<select id="bg_tiled" onchange="showCustSetting(this);">\
											<option value="none">不平铺</option>\
											<option value="default" selected="true" >平铺</option>\
											<option value="h">横向</option>\
											<option value="v">纵向</option>\
										</select>\
									</li>\
									<li>\
										<label>对齐: </label>\
										水平方向 <select id="bg_align_h" onchange="showCustSetting(this);">\
												<option value="default">默认</option>\
												<option value="left">左</option>\
												<option value="center">中</option>\
												<option value="right">右</option>\
												</select>\
										垂直方向 <select id="bg_align_v" onchange="showCustSetting(this);">\
												<option value="default">默认</option>\
												<option value="top">上</option>\
												<option value="center">中</option>\
												<option value="bottom">下</option>\
											   </select>\
									</li>\
								</ul>\
							</div>\
						</div>\
					</div>\
			</div>\
	</div>\
    <div id="tpl_cust_btn">\
				<input type="hidden" id="head_currpic" />\
				<input type="hidden" id="bg_currpic" />\
				<input type="button" value="保存设置" id="tpl_cust_btn_save" onclick="doCustSaveSetting();" /> <input type="button" value="恢复默认设置" disabled="disabled" id="tpl_cust_btn_reset" onclick="doCustSaveSetting(\'clear\');"/>\
	</div>\
	<div id="tpl_msgs">\
		<!--<img src="/images/tmp/t_90.gif" />-->\
		一键更换您的模版，点击图片后将自动保存！\
	</div>\
	<div id="tpl_tabs">\
	</div>\
	<div id="tpl_diy_div"><img src="http://blogimg.sinajs.cn/images/tmp/blueArr.gif" align="absmiddle" /><a href="javascript:;" id="diy_btn">进入模板变变变</a></div>\
</div>\
<div id="tpl_shad">2</div>\
';
var conf = {
	'data' : [
		{
			'name' : '朴素',
			'conf' : [
				'f1,k1,e1,d1,c1,b1,m1',
				'f8,k7,e2,d2,c7,b2,m9',
				'f5,k4,e3,d7,c9,b3,m10',
				'f4,k2,e4,d2,c7,b4,m4',
				'f4,k1,e1,d4,c2,b5,m1',
				'f2,k3,e5,d1,c5,b6,m5',
				'f6,k8,e5,d8,c4,b7,m6',
				'f7,k3,e1,d5,c2,b8,m5',
				'f2,k8,e6,d6,c6,b9,m6',
				'f1,k9,e5,d5,c4,b10,m8'
			]
		},
		{
			'name' : '灰色轨迹',
			'conf' : [
				'f1,k1,e1,d1,c1,b1,m1',
				'f1,k3,e8,d2,c2,b2,m14',
				'f1,k4,e2,d7,c6,b3,m14',
				'f1,k1,e9,d5,c2,b4,m7',
				'f1,k1,e7,d6,c5,b5,m5',
				'f1,k5,e12,d2,c8,b6,m2',
				'f1,k3,e3,d4,c2,b7,m4',
				'f1,k3,e11,d1,c2,b8,m9',
				'f1,k3,e5,d7,c2,b9,m9',
				'f1,k7,e9,d1,c1,b10,m12',
				'f1,k3,e1,d1,c7,b11,m11',
				'f1,k3,e11,d4,c10,b12,m9',
				'f1,k9,e1,d5,c8,b13,m8'
			]
		},
		{
			'name' : '轻描淡写',
			'conf' : [
				'f1,k8,e1,d2,c1,b1,m8',
				'f2,k1,e4,d3,c2,b2,m2',
				'f3,k3,e3,d1,c3,b3,m9',
				'f4,k2,e5,d4,c4,b4,m7',
				'f1,k9,e10,d5,c8,b5,m3',
				'f4,k2,e2,d7,c7,b8,m9',
				'f7,k6,e13,d8,c10,b9,m9',
				'f5,k3,e3,d9,c6,b10,m7',
				'f3,k3,e3,d10,c3,b11,m1',
				'f6,k1,e3,d6,c6,b7,m4'
			]
		},
		{
			'name' : '野蛮丫头',
			'conf' : [
				'f1,k5,e1,d11,c1,b1,m1',
				'f1,k2,e2,d5,c1,b2,m7',
				'f1,k7,e7,d2,c1,b3,m4',
				'f1,k3,e5,d4,c1,b4,m3',
				'f1,k9,e9,d1,c1,b5,m6',
				'f1,k5,e5,d1,c1,b6,m7',
				'f1,k5,e4,d7,c1,b7,m10',
				'f1,k8,e5,d2,c1,b8,m9',
				'f1,k9,e3,d3,c1,b9,m3',
				'f1,k10,e4,d1,c1,b10,m4'
			]
		},
		{
			'name' : '节日',
			'conf' : [
				'f1,k8,e1,d1,c1,b1,m1',
				'f2,k9,e3,d3,c2,b2,m2',
				'f3,k5,e5,d5,c3,b3,m5',
				'f5,k3,e12,d4,c5,b4,m4',
				'f8,k6,e1,d1,c8,b6,m6',
				'f9,k5,e6,d7,c7,b7,m9',
				'f10,k6,e2,d2,c10,b10,m6',
				'f11,k6,e11,d11,c11,b11,m11',
				'f12,k2,e12,d12,c12,b12,m12',
				'f13,k6,e13,d13,c13,b13,m13'
			]
		},
		{
			'name' : '魔兽风格',
			'conf' : [
				'f1,k1,e1,d1,c1,b1,m1',
				'f2,k2,e2,d2,c2,b2,m2',
				'f3,k5,e3,d3,c3,b3,m3',
				'f4,k7,e4,d4,c4,b4,m4',
				'f5,k7,e5,d5,c5,b5,m5',
				'f6,k5,e6,d6,c6,b6,m6',
				'f7,k8,e7,d7,c7,b7,m7',
				'f8,k1,e8,d8,c8,b8,m8',
				'f9,k7,e9,d9,c9,b9,m9',
				'f10,k9,e10,d10,c10,b10,m10'
			]
		},
		{
			'name' : '足球',
			'conf' : [
				'f1,k1,e1,d1,c1,b1,m1',
				'f3,k2,e2,d4,c1,b2,m10',
				'f2,k7,e10,d5,c4,b4,m39',
				'f9,k9,e14,d10,c10,b8,m47',
				'f10,k3,e4,d8,c9,b9,m9',
				'f9,k2,e5,d4,c7,b12,m4',
				'f5,k10,e13,d8,c3,b5,m34',
				'f3,k1,e3,d2,c7,b15,m2',
				'f2,k2,e7,d7,c8,b7,m7',
				'f6,k2,e3,d4,c1,b17,m12'
			]
		},
		{
			'name' : '音乐旋风',
			'conf' : [
				'f1,k1,e1,d1,c1,b1,m1',
				'f2,k1,e9,d7,c2,b9,m21',
				'f5,k8,e6,d6,c6,b23,m37',
				'f1,k4,e1,d5,c8,b20,m32',
				'f3,k3,e3,d15,c4,b32,m29',
				'f3,k7,e5,d9,c5,b25,m16',
				'f3,k5,e6,d3,c6,b5,m10',
				'f2,k2,e2,d7,c2,b21,m3',
				'f6,k10,e5,d6,c6,b12,m35',
				'f3,k5,e5,d3,c5,b27,m14',
				'f3,k3,e3,d7,c3,b15,m6',
				'f9,k2,e6,d3,c9,b2,m20',
				'f3,k7,e5,d3,c6,b22,m25',
				'f3,k3,e4,d7,c3,b4,m11',
				'f3,k7,e6,d3,c5,b3,m34',
				'f1,k4,e8,d4,c10,b33,m12',
				'f6,k3,e5,d3,c6,b14,m28',
				'f1,k4,e10,d4,c10,b31,m15',
				'f4,k5,e7,d6,c6,b6,m7',
				'f3,k2,e3,d14,c3,b13,m42',
				'f4,k5,e7,d6,c7,b16,m23',
				'f7,k1,e3,d3,c4,b18,m22',
				'f3,k7,e5,d3,c5,b30,m18',
				'f5,k8,e5,d3,c6,b24,m17',
				'f8,k9,e6,d3,c5,b26,m19',
				'f3,k3,e3,d3,c3,b34,m44',
				'f4,k1,e7,d3,c7,b7,m36',
				'f1,k4,e1,d5,c8,b35,m49',
				'f11,k1,e11,d3,c11,b36,m51',
				'f12,k1,e12,d5,c12,b37,m52'
			]
		},{},
		{
			'name' : '品牌故事',
			'conf' : [
			]
		}
	]
};
var newConf = {
	data : [
		{
			name : '浪漫温馨',
			ln : [0,2]
		},
		{
			name : '活泼可爱',
			ln : [3]
		},
		{
			name : '另类空间',
			ln : [1]
		},
		{
			name : '魔兽风格',
			ln : [5]
		},
		{
			name : '音乐旋风',
			ln : [7]
		},
		{
			name : '足球世界',
			ln : [6]
		},
		{
			name : '节日表情',
			ln : [4]
		},
		{
			name : '品牌故事',
			ln : [9]
		}
	]
};
function createNewConf(){
	for(var i=0;i<newConf.data.length;i++){
		var ln = newConf.data[i].ln;
		var sConf = [];
		for(var j=0;j<ln.length;j++){
			var arr = conf.data[parseInt(ln[j])].conf.length;
			for(var k=0;k<arr;k++){
				var tmp = {};
				tmp.oTheme = ln[j];
				tmp.oid = k;
				tmp.cfg = conf.data[ln[j]].conf[k];
				sConf.push(tmp);
			}
		}
		newConf.data[i].conf = sConf;
	}
}
var BusinessTheme={
	 	request:function(url){
			if(window!=scope)return
			var id="business";
			var businessScript=$(id);
			if(businessScript){
				businessScript.parentNode.removeChild(businessScript);
			}
      		var script=document.createElement("script");
			script.id=id;
			script.src=url+"?"+Math.random();
			document.body.appendChild(script);
        },
		response:function(text){
			this.onComplete(text);
		},
		onComplete:function(text){
				this.data=eval(text);
				conf.data[9].conf=this.data;
				createNewConf();
		},
		changeMode:function(){
			var str=this.data.toString();
			var reg=new RegExp("b"+sBanner+"(,|$)");
			if(!reg.test(str)){
				return !confirm("你目前使用的商业模板已经过期，如果更换将无法恢复。是否更换？");
			}
			return false;
		}
}
BusinessTheme.request("http://bbs.sina.com.cn/iframe/ad/config_080114.js");
initCodes = [];
function getInitTheme(theme){
	theme = parseInt(theme) - 1;
	for(var i=0;i<newConf.data.length;i++){	
		if(newConf.data[i].ln.join('').indexOf(theme) != -1){
                        return i;
                }	
	}
}
initCodes.push(getInitTheme(THEME));
function initTpl(){
	initDom();
	initData();
	var lr = window.location.href;
	if(/\?tmpl/.test(lr)){
		show_tpl();
	}
}
function Stylesheet(ss) {
	var dss = document.styleSheets;
	var dsl  = dss.length;
	if(!dsl || !ss) {
		ss = $C('style');
		$$('head')[0].appendChild(ss);
		ss = ss.styleSheet?ss.styleSheet:ss.sheet;
	}else if (typeof ss == "number"){
		ss = dss[ss];
	}
    this.ss = ss;
}
Stylesheet.prototype.getRules = function() {
    return this.ss.cssRules?this.ss.cssRules:this.ss.rules;
}
Stylesheet.prototype.getRule = function(s) {
    var rules = this.getRules();
    if (!rules) return null;
    if (typeof s == "number") return rules[s];
    s = s.toLowerCase();
    for(var i = rules.length-1; i >= 0; i--) {
        if (rules[i].selectorText.toLowerCase() == s) return rules[i];
    }
    return null;
};
Stylesheet.prototype.getStyles = function(s) {
    var rule = this.getRule(s);
    if (rule && rule.style) return rule.style;
    else return null;
};
Stylesheet.prototype.getStyleText = function(s) {
    var rule = this.getRule(s);
    if (rule && rule.style && rule.style.cssText) return rule.style.cssText;
    else return "";
};
Stylesheet.prototype.insertRule = function(selector, styles, n) {
    if (n == undefined) {
        var rules = this.getRules();
        n = rules.length;
    }
    if (this.ss.insertRule)   // Try the W3C API first
        this.ss.insertRule(selector + "{" + styles + "}", n);
    else if (this.ss.addRule) // Otherwise use the IE API
        this.ss.addRule(selector, styles, n);
};
Stylesheet.prototype.replaceRule = function(selector, styles, n) {
	this.deleteRule(selector || n);
	this.insertRule(selector, styles, n);
}
Stylesheet.prototype.deleteRule = function(s) {
    if (s == undefined) {
        var rules = this.getRules();
        s = rules.length-1;
    }
    if (typeof s != "number") {
        s = s.toLowerCase();    // convert to lowercase
        var rules = this.getRules();
        for(var i = rules.length-1; i >= 0; i--) {
            if (rules[i].selectorText.toLowerCase() == s) {
                s = i;  // Remember the index of the rule to delete
                break;  // And stop searching
            }
        }
        if (i == -1) return;
    }
    if (this.ss.deleteRule) this.ss.deleteRule(s);
    else if (this.ss.removeRule) this.ss.removeRule(s);
};
function setCustStyle(tp, ct, cv, ch, cp, hh){
	var ss = window.scope.CustTpl.ss;
	ct = (ct=='none')?'no-repeat':(ct=='default')?'repeat':(ct=='h')?'repeat-x':'repeat-y';
	cv	= (cv=='default'?'top':cv);
	ch	= (ch=='default'?'left':ch);
	if(tp == 'bg'){
		var t = byId('innerBound');
		t.style.background =  'url('+cp+')';
		t.style.backgroundRepeat =  ct;
		t.style.backgroundPosition =  cv + ' ' + ch;
		document.body.style.background = '#fff';
	}else{
		var styles = 'background: transparent url('+cp+') '+ct+' scroll '+cv + ' ' + ch + ';' + (tp=='head'&&hh?'height:'+hh:'');
		var selector = '#bannerContent .positionHelper';
		if(ss.getRule(selector)){
			ss.replaceRule(selector, styles);
		}else{
			ss.insertRule(selector, styles);
			ss.insertRule('#bannerContent #blogName', 'top:24%');
			ss.insertRule('#bannerContent #blogLink', 'top:56%');
		}
	}
}
function resetCustStyle(tp){
	var ss = window.scope.CustTpl.ss;
	if(tp=='head'){
		ss.deleteRule('#bannerContent .positionHelper');
		ss.deleteRule('#bannerContent #blogName');
		ss.deleteRule('#bannerContent #blogLink');
	}else{
		var t = byId('innerBound');
		t.style.backgroundImage =  '';
		t.style.backgroundRepeat =  '';
		t.style.backgroundPosition =  '';
		document.body.style.background = '';
	}
}
(function (){
	var picUrl = 'http://album.sina.com.cn/pic/';
	var themeUrl = 'http://image2.sina.com.cn/blog/tmpl/v3/theme/';
	try{
		var dftHd = { currpic: 'dpic', usepic: '3',  tiled: 'default', align_h: 'default', align_v: 'default', height: 100 };
		var dftBg = { currpic: 'dpic', usepic: '3',  tiled: 'default', align_h: 'default', align_v: 'default' };
		if(customTemplate.head == null) customTemplate.head = dftHd;
		if(customTemplate.bg == null) customTemplate.bg = dftBg;
		window.scope.CustTpl = Object.extend({
					head: dftHd,
					bg: dftBg,
					basicPicUrl: picUrl,
					basicThemeUrl: themeUrl,
					ss: (new Stylesheet())
		}, customTemplate||{});
		var sc = window.scope.CustTpl;
		sc.head.oldPic = sc.basicThemeUrl + THEME + '/images/banner/' + sBanner+'.jpg';
		var sBg = window.scope.config.customTheme.bg;
		sc.bg.oldPic = sc.basicThemeUrl + THEME + '/images/bg/' + sBg+(THEME==1?'.gif':'.jpg');
		if(sc.head.currpic!='dpic' && sc.head.usepic == '1'){
			setCustStyle('head', sc.head.tiled, sc.head.align_v, sc.head.align_h, sc.basicPicUrl + sc.head.currpic, sc.head.height+'px');
		}
		if(sc.bg.currpic!='dpic' && sc.bg.usepic == '1'){
			setCustStyle('bg', sc.bg.tiled, sc.bg.align_v, sc.bg.align_h, sc.basicPicUrl + sc.bg.currpic);
		}
		if($Br.$IE6) document.execCommand("BackgroundImageCache",false,true); //fixed ie6 bg cache bug
	}catch(e){ window.scope.CustTpl = { head: dftHd, bg: dftBg, basicPicUrl: picUrl, basicThemeUrl: themeUrl , ss: (new Stylesheet()) }; }
})();
function initCustEvents(){
	var eShowTabs = showTabs.bindAsEventListener(this);
	$('tpl_titl_dft', 'tpl_titl_cust').each(function(el){ el.observe('click',  eShowTabs); });
	var eCheckSel = checkCustSelect.bindAsEventListener(this);	
	var eReupload = doCustReupload.bindAsEventListener(this);
	['head','bg'].each(function(pannel, idx){
		var cur = $('tpl_cust_tab'+idx);
		cur.idx = idx;
		cur.onclick = function(){
			set_cust(this.idx, !(this.className == 'active'));
		}
		$('cust_'+pannel+'_upload', 'cust_'+pannel+'_default').each(function(el){
			$(el).observe('click',  eCheckSel);
		});
		$('cust_'+pannel+'_reupload_link').observe('click', eReupload);
		$(pannel + '_file').observe('change', function(e){
			   var el = $(Event.element(e));
			   $(el.id+'_submit').disabled = !el.value;
		});
	});
	$('head_height').observe('keydown', function(e){
		if(e.keyCode == 13) showCustSetting($(Event.element(e)));
	});
	initCustValues();
}
function initCustValues(){
	var tpl = window.scope.CustTpl;
	['head','bg'].each(function(pannel){
		var cp = tpl[pannel];
		for(o in cp){
			try{
				var el = $(pannel+'_'+o);
				if(el) el.value = cp[o];
			}catch(e){ continue; }
		}
	});
	try{
		if(tpl.head.currpic!='dpic'){
			setCustPic({type:'head', headUrl: tpl.basicPicUrl + tpl.head.currpic, headUp:true});
			$('head_upload_cover').className = 'cust_cover';
		}
		if(tpl.bg.currpic!='dpic'){
			setCustPic({type:'bg', bgUrl:  tpl.basicPicUrl + tpl.bg.currpic, bgUp:true});
			$('bg_upload_cover').className = 'cust_cover';
		}
	}catch(e){}
	$('tpl_cust_btn_reset').disabled = (tpl.head.usepic=='3'&&tpl.bg.usepic=='3');
}
function showTabs(e){
	var el = $(Event.element(e));
	var dft   = $('tpl_titl_dft');
	var cust = $('tpl_titl_cust');
	function setTab(sdft, scust){
		$('tpl_msgs').style.display= sdft;
		$('tpl_tabs').style.display=  sdft;
		$('tpl_diy_div').style.display= sdft;
		$('tpl_cust_cnt').style.display=  scust;
		$('tpl_cust_btn').style.display= scust;
	}
	var sc = window.scope.CustTpl;
	switch(el.id){
		case 'tpl_titl_dft':
			dft.style.height = '27px';
			cust.style.height = '26px';
			setTab('block', 'none');
			shadow();
			break;
		case 'tpl_titl_cust':
			dft.style.height = '26px';
			cust.style.height = '27px';
			setTab('none', 'block');
			sc.isEdit = true;
			shadow_cust();
			['head','bg'].each(function(pannel){
				try{
					if(sc[pannel].usepic=='1') checkCustSelect('cust_'+pannel+'_upload'); //默认选中
					if(sc[pannel].usepic=='3'){
						checkCustSelect('cust_'+pannel+'_default'); //默认选中
						$(pannel + '_currpic') = 'dpic';
					}
				} catch(e){}
			});
			break;
	}
}
function setCustPic(obj){
	var smallPic =  '';
	var sc = window.scope.CustTpl;
	if(obj.type == 'head'){
		if(obj.headUrl){
			smallPic = 'url('+obj.headUrl+') '+(obj.align||'left top');
			$('cust_head_'+(obj.headUp?'upload':'default')).style.background = smallPic;
		}
	}else{
		if(obj.bgUrl){
			smallPic = 'url('+obj.bgUrl+') '+(obj.align||'left top');
			$('cust_bg_'+(obj.bgUp?'upload':'default')).style.background = smallPic;
		}
	}
}
function setHeadHeight(){
	var el	= $('head_height');
	var tip = $('head_height_tip');
	var val	= val || el.value || window.scope.CustTpl['head'].height;
	var err = false;
	if(isNaN(val) || !val) err = true;
	if(val > 300) err = true;
	if(val < 100) err = true;
	if(err){
		tip.update('(只能输入100-300之间的整数！)');
		tip.style.color = '#f00';
		el.value = '';
		el.focus();
		return false;
	}else{
		tip.update('(100-300象素)');
		tip.style.color = '';
	}
	return val + 'px';
}
function resetCustTheme(el){
	var eForm = $(el.id.replace('default','uparea'));
	var ePannel = $(el.id.replace('default','setting'));
	eForm.hide();
	ePannel.hide();
	var tp = chkType(el,true);
	$(tp+'_currpic').value ="dpic";
	var sc = window.scope.CustTpl;
	resetCustStyle(tp);
	sc[tp].usepic = 3;
	try{ if($('changeName').style.display!='none') changeName.initPosition(); } catch(e){};
	shadow_cust();
}
function showCustForm(el){
	var eForm = $(el.id.replace('upload','uparea'));
	eForm.show();
}
function showCustSetting(el){
	var tp = (typeof el =='string' ? el :chkType(el, true));
	var sc = window.scope.CustTpl;
	try{
		$('cust_'+tp+'_setting').show();
		$('cust_'+tp+'_uparea').hide();
		$(tp+'_currpic').value = sc[tp].currpic;
		var ct = $(tp+'_tiled').value || sc[tp].tiled;
		var cv = $(tp+'_align_v').value || sc[tp].align_v;
		var ch = $(tp+'_align_h').value || sc[tp].align_h;
		var cp = sc.basicPicUrl + sc[tp].currpic;
		var hh = setHeadHeight();
		if(hh) setCustStyle(tp, ct,  cv, ch , cp, hh);
		sc[tp].usepic = 1;
	}catch(e){}
	try{ if($('changeName').style.display!='none') changeName.initPosition(); } catch(e){};
	shadow_cust();
}
function checkCustSelect(e){
	var el = (typeof e == 'object')?$(Event.findElement(e, 'a')):$(e);
	var tp = chkType(el,true);
	if(el.id.indexOf('upload')!=-1){
		var tp = chkType(el, true)
		try{
			var sc = window.scope.CustTpl[tp];
			if(sc.currpic&&sc.currpic!='dpic') showCustSetting(el);
			else showCustForm(el);
		}catch(e){ showCustForm(el); };
	}
	else if(el.id.indexOf('default')!=-1){
		resetCustTheme(el);
	}
	setCustTick(el);
	shadow_cust();
	el.blur();
}
function setCustTick(el){
	var currTick = $C('div');
		 currTick.className = 'cust_curpic';
	el.appendChild(currTick);
	var sc = window.scope.CustTpl;
	var cSel = null;
	if(chkType(el)){
		if(sc.currCustHSel) cSel = sc.currCustHSel;
		sc.currCustHSel = {target: el, tick: currTick};
	}else{
		if(sc.currCustBSel) cSel = sc.currCustBSel;
		sc.currCustBSel = {target: el, tick: currTick};
	}
	if(cSel){
		var t = cSel.target;
		t.removeChild(cSel.tick);
		t.className = '';
	}
	el.className = 'active';
}
function chkType(el, s){
	if(s) return (el.id.indexOf('head')!=-1)?'head':'bg';
	return el.id.indexOf('head')!=-1;
}
function custUploadCb(cb){
	try{
		var ifm = byId('custPostFrame');
		var body  =  ifm.contentWindow.document.body;
		cb(body.innerHTML);
	}catch(e){ cb('{errId: "unknow"}'); }
}
function showErrMsg(parent, clz, msg){
	if($(parent).className!='err'){
		$(parent).className = 'err';
		getChildrenByClass(parent, clz)[0].className = clz + '_e';
	}
	var ico = '<img src ="http://blogjs.sinajs.cn/images/tmp/t_cross.gif" align="absmiddle" /> ';
	var tips = $(chkType(parent, true)+'_uptips')
		tips.className = 'tipsErr';
		tips.innerHTML = ico + msg;
}
function resetErrMsg(parent, clz, msg, noico){
	if($(parent).className=='err'){
		$(parent).className = '';
		getChildrenByClass(parent, clz+'_e')[0].className = clz;
	}
	var ico = !noico?'<img src ="http://blogjs.sinajs.cn/images/tmp/t_tick.gif" align="absmiddle" /> ':'';
	var tips = $(chkType(parent, true)+'_uptips')
		tips.className = '';
		tips.innerHTML = ico + (msg||'支持大小不超过600k的jpg,gif,png图片，建议宽度为770象素');
}
function CustUploadProgress(tp, end){
	var cnt = $(tp + '_upcnt_loading');
	if(end){
		cnt.style.display='none';
		return;
	}
	resetErrMsg($('cust_'+tp+'_uparea'), 'triangle');
	cnt.style.display='block';
	if(cnt.innerHTML) return;
	var loadingTxt = '<div style="float:left;border:1px solid #B0B0B0;background:#F5F5F5;color:#787878;width:200px;height:20px;margin:10px 0 0 10px;">\
					 <img src ="http://blogjs.sinajs.cn/images/tmp/t_loading.gif" align="absmiddle" />上传中...</div>\
					 <input type="button" value="取消上传" style="margin:10px 0 0 0;" onclick="CustUploadCancel(\''+tp+'\')"/>';
	cnt.update(loadingTxt);
}
function CustUploadCancel(tp){
	restoreUpArea(tp);
	CustUploadProgress(tp, true);
	var ifm = byId('custPostFrame');
	ifm.actCb = '';
	ifm.location = 'about:blank';
}
function doCustUpload(el){
	var tp = chkType(el, true);
	if(!$(tp + '_file').value){
		showErrMsg($('cust_'+tp+'_uparea'), 'triangle', "请先选择图片!");
		return false;
	}
	CustUploadProgress(tp);
	byId('custPostFrame').actCb = function(txt){
		var data = eval('('+txt+')');
		if(data.errId){
			var errMsg = '';
			switch(parseInt(data.errId)){
				case 1: errMsg = '上传类型不正确，请重试。'; break;
				case 2: errMsg = '很抱歉，请登录后再上传图片！';break;
				case 3: errMsg = '上传的图片不得超过600k，请重新上传。'; break;
				case 5: errMsg = '上传的图片为空，请重新上传。'; break;
				case 6: errMsg = '上传的图片不得超过600k，请重新上传。'; break;
				case 10: errMsg = '上传图片只支持jpg、gif、png格式，请重新上传。'; break;
				case 11: errMsg = '路径错误，请重新上传。'; break;
				case 13: errMsg = '保存失败，请重新上传。'; break;
				case 'unknow' : CustUploadCancel(tp);
				case 4:
				case 7:
				case 8:
				case 9:
				case 12:
				case 14:
				default: errMsg = '上传失败，请重新上传。';
			}
			CustUploadProgress(tp, 'success');
			restoreUpArea(tp);
			showErrMsg($('cust_'+tp+'_uparea'), 'triangle', errMsg);
			return false;
		}
		setTimeout(function(){
			var sc = window.scope.CustTpl;
			CustUploadProgress(tp, 'success');
			restoreUpArea(tp);
			$('cust_'+tp+'_uparea').hide();
			$(tp + '_upload_cover').className = 'cust_cover';
			sc[tp].currpic = data.picId;
			sc[tp].usepic = '1';
			setCustPic({type: tp, custUrl: data.picId});
			var obj = {type: tp };
				obj[tp+'Url'] = sc.basicPicUrl + data.picId;
				obj[tp+'Up'] = true;
			setCustPic(obj);
			showCustSetting(tp);
			var okStr = '<img src="http://blogjs.sinajs.cn/images/tmp/t_tick2.gif" alt="arrow" />\
							<span style="color:#2f8323;font-weight:bold;">上传成功.</span><a href="javascript:;" id="cust_'+tp+'_reupload_link">重新上传</a>';
			$('cust_'+tp+'_reupload').update(okStr);
			$('cust_'+tp+'_reupload_link').observe('click', doCustReupload.bindAsEventListener(this));
			byId('custPostFrame').actCb = '';
			resetErrMsg($('cust_'+tp+'_uparea'), 'triangle');
		}, 1000);
	}
}
function restoreUpArea(tp){
		var upArea = $('cust_'+tp+'_uparea');
		upArea.update(upArea.innerHTML);
		$(tp + '_file_submit').disabled  = true;
		$(tp + '_file').onchange =  function(e){
			   try{ var el = e.target }
			   catch(e){ var el =  event.srcElement; }
			   $(el.id+'_submit').disabled = !el.value;
		}
}
function doCustReupload(e){
		var el = $(Event.element(e));
		var tp =  chkType(el, true);
		resetErrMsg($('cust_'+tp+'_uparea'), 'triangle', '',true);
		$(tp+'_file_submit').disabled = true;
		$('cust_'+tp+'_setting').hide();
		$('cust_'+tp+'_uparea').show();
		shadow_cust();
}
function doCustSaveSetting(clear){
	var obj = {};
	$w('head bg').each(function(b){
		$w('_currpic _tiled _align_h _align_v').each(function(s){
			obj[b+s] = $(b+s).value;
		});
	});
	var hh = $('head_height');
	if(!hh.value) hh.value = '100';
	obj['head_height'] = hh.value;
	obj['pic_type'] = clear?2:1;
	var url = 'http://my.blog.sina.com.cn/blog/save_diy_css.php';
	new Ijax(url,{
		onComplete : function (text){ 
			var data = eval('('+text+')');
			if(data.success  == 'true'){
				$('tpl_cust_btn_reset').disabled = (obj['pic_type']==2);
				alert('自定义模板'+(obj['pic_type']==1?'保存':'恢复')+'成功！');
					var dl = document.location;
					dl.replace(dl.href.replace('?tmpl',''));
			}else{
				alert(data.errMsg);
			}
		},
		post: obj
	  });
}
function set_cust(idx, iso){
	$('tpl_cust_tab'+idx).className = iso ? 'active' : 'unactive';
	$('tpl_cust_box'+idx).style.display = iso ? '' : 'none';
	shadow_cust();
}
function shadow_cust(){
	var shadowHeight = 82;
	var activeCount = 0;
	for(var i=0;i<2;i++){
		if($('tpl_cust_tab' + i).className == 'active'){
			shadowHeight += $('tpl_cust_box'+i).getHeight();
			shadowHeight += 5;
		}
	}
	$('tpl_shad').style.height = (shadowHeight+38) + 'px';
	$('tpl_cust_cnt').style.height = (shadowHeight-33) +'px';
	window.setTimeout(this.resizeIframeBlock.bind(this), 50);
}
if(window == window.scope) {
	var contentBody  = "outBound";
	function JsLoader(){
		this.load = function(url, charset){
			var ss = document.getElementsByTagName("script");
			for(var i = 0;i < ss.length; i++){
				if(ss[i].src && ss[i].src.indexOf(url) != -1) {
					this.onsuccess();
					return;
				}
			}
			var s = document.createElement("script");
			s.type= "text/javascript";
			s.src = url;
			s.charset = charset ? charset : "utf-8";
			var head = document.getElementsByTagName("head")[0];
			head.appendChild(s);
			var self = this;
			s.onload = s.onreadystatechange = function() {
				if(this.readyState && this.readyState == "loading")return;
				self.onsuccess();
			}
			s.onerror = function() {
				head.removeChild(s);
				self.onfailure();
			}
		};
		this.onsuccess=function(){};
		this.onfailure=function(){};
	}
	document.write('<style>\
	.BusinessCardDIV * {color:#5D5D5D;;line-height: 14px;font-size: 12px;font-family:"宋体";}\
	.BusinessCardDIV a:hover{color:#FF0000;text-decoration:underline;}\
	.BusinessCardDIV a {color:#7569BF;}\
	</style>');
	function getPageSize() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = $(contentBody).scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		}
		else if ($(contentBody).scrollHeight > $(contentBody).offsetHeight){ // all but Explorer Mac
			xScroll = $(contentBody).scrollWidth;
			yScroll = $(contentBody).scrollHeight;
		}
		else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = $(contentBody).offsetWidth;
			yScroll = $(contentBody).offsetHeight;
		}
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		}
		else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		}
		else if ($(contentBody)) { // other Explorers
			windowWidth = $(contentBody).clientWidth;
			windowHeight = $(contentBody).clientHeight;
		}	
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		}
		else { 
			pageHeight = yScroll;
		}
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		}
		else {
			pageWidth = xScroll;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	}
	function addHTML(oParentNode, sHTML) {
		if(window.addEventListener) {// for MOZ
			var oRange = oParentNode.ownerDocument.createRange();
			oRange.setStartBefore(oParentNode);
			var oFrag = oRange.createContextualFragment(sHTML);
			oParentNode.appendChild(oFrag);
		}
		else {// for IE5+
			oParentNode.insertAdjacentHTML("BeforeEnd", sHTML);
		}
	}
	var card_data;
	function BusinessCard() {
		var _this = this;
		var isLoad = true;
		var timer;
		var udata;
		var bcHome, bcName,bcNick,bcPhoto,bcFLD,bcSED,bcDIV,CT1,CT2,CT3,CT4,bcB,bcV,bcB2,bcQ,bcP;
		var sAction = null;
		var showMode = false;
		var uid = null;
		this.createLog = function (csAction) {
			sAction = sAction != "" && sAction != null ? sAction : "error";
			csAction = csAction != "" && csAction != null ? csAction : "error";
			if(scope.pageMark != "article")
			{
				//addHTML(document.body, "<img style='display: none;' src='http://stat.blog.sina.com.cn/i.html?card&" + sAction + "&" + csAction + "&" + new Date().valueOf() + "'>");
			}
			else {
				sendCommonLog("rela_visitor_cardhref","articlenewone");
			}
			csAction = null;
			return false;
		};
		this.create = function () {
			if(document.getElementById("BusinessCardDIV"))return;
			var sBC = '\
			<div style="position:absolute;left:0px;top:0px;display:none;" id="BusinessCardDIV" onclick="bc.rtn(event)" class="BusinessCardDIV">\
				<div id="BusinessCardContent" style="position:absolute;left:4px;top:4px; width: 310px; height: 160px; background:#000;filter: alpha(opacity=10);-moz-opacity: 0.1;"></div>\
				<div style="position:absolute; left: 0px; top: 0px; width: 310px; height: 160px; overflow: hidden;"><img src="http://image2.sina.com.cn/blog/tmpl/v3/images/datong/card/bg.gif" onerror="this.src=this.src"/></div>\
				<div style="position:absolute; left: 0px; top: 0px;">\
					<!--用户头像-->\
					<div style="position: absolute; left: 10px; top: 10px;"><a id="BusinessCardPhotoLink" target="_blank" onclick="bc.createLog(\'headpic\');" href="javascript:void();"><img src="http://image2.sina.com.cn/blog/tmpl/v3/images/default_icon.jpg" alt="用户头像" width="60" height="60" id="BusinessCardPhoto" border="0"/></a></div>\
						<!--头像底部链接-->\
						<div style="position: absolute; left: 10px; top: 74px; width: 60px; height: 14px; text-align: center; line-height: 14px;"><a href="javascript:void(0);" onclick="bc.createLog(\'home\');" target="_blank" id="BusinessCardHome">进入空间</a></div>\
						<!--my2008链接-->\
						<div style="position: absolute; left: 10px; top: 92px; text-align: center;"><a target="_blank" href="http://my2008.sina.com.cn/index1.shtml"><img src="http://image2.sina.com.cn/blog/tmpl/v3/images/datong/card/my2008.gif" alt=\"参加“我的2008”，赢取每周大奖！\" width="62" height="29" border="0"/></a></div>\
						<!--昵称-->\
						<div style="position: absolute; left: 85px; top: 10px; width: 200px; height: 12px; line-height: 12px;" id="BusinessCardNick">昵&nbsp;&nbsp;&nbsp;&nbsp;称<b>:</b> <b><a href="http://blog.sina.com.cn/u/1147672380" target="_blank" style="color: rgb(93, 93, 93);" onclick="bc.createLog(\'nick\');">蓝调小雨云</b></a></div>\
						<!--登录名-->\
						<div style="position: absolute; left: 85px; top: 26px; width: 200px; height: 12px; line-height: 12px;" id="BusinessCardName">会员编码<b>:</b> <b><a href="http://blog.sina.com.cn/u/1147672380" target="_blank" style="color: rgb(93, 93, 93);" onclick="bc.createLog(\'loginname\');">1147672380</a></b></div>\
						<!--关闭按钮-->\
						<div style="position: absolute; left: 291px; top: 10px;"><a href="javascript: void(0);" id="BusinessCardClose"><img border="0" src="http://image2.sina.com.cn/blog/tmpl/v3/images/datong/card/close.gif" alt="关闭" width="9" height="9" onclick="bc.hidden();"></a></div>\
						<!--内容区域-->\
						<div style="position: absolute; left: 85px; top: 53px; width: 160px; height: 70px;">\
							<div id="BusinessCardCT1" style="display: none;" style="color:#7e7e7e;"></div>\
							<div id="BusinessCardCT2" style="display: none;">读取中……</div>\
							<div id="BusinessCardCT3" style="display: none;">读取中……</div>\
							<div id="BusinessCardCT4" style="display: none;">读取中……</div>\
						</div>\
						<!-- 加为好友 -->\
						<div style="position: absolute; left: 250px; top: 85px;"><a href="javascript:void(0)" id="BusinessCardFLD" style="display: none;" onclick="bc.createLog();"><img src="http://image2.sina.com.cn/blog/tmpl/v3/images/datong/card/friend_invite.gif" alt="加为好友" width="50" height="17" border="0"></a></div>\
						<!-- 发纸条 -->\
						<div style="position: absolute; left: 250px; top: 107px;"><a href="javascript:void(0)" onclick="bc.createLog();" id="BusinessCardSend" style="display: none;"><img src="http://image2.sina.com.cn/blog/tmpl/v3/images/datong/card/send.gif" alt="发纸条" width="50" height="17" border="0"></a></div>\
						<!-- 5个链接 -->\
						<div style="position: absolute; left: 8px; top: 138px; width: 292px; height: 12px; text-align: center; line-height: 12px;"><a href="javascript:void(0)" id="BusinessCardLinkB" onclick="bc.createLog(\'home2\');" target="_blank">博客</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="javascript:void(0)" onclick="bc.createLog(\'otherpr\');" id="BusinessCardLinkV" target="_blank">播客</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="javascript:void(0)" id="BusinessCardLinkB2" target="_blank" onclick="bc.createLog(\'otherpr\');">论坛</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="javascript:void(0)" id="BusinessCardLinkQ" target="_blank" onclick="bc.createLog(\'otherpr\');">圈子</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="javascript:void(0)" id="BusinessCardLinkP" target="_blank" onclick="bc.createLog(\'otherpr\');">相册</a></div>\
				</div>\
			</div>\
			';
			addHTML($("innerBound"), sBC);
			IframeBlock.init("BusinessCardDIV", "BusinessCardContent", this);
			var iblock = document.getElementById("BusinessCardContent_iframeBlock");
			iblock.style.width = "310px";
			iblock.style.height = "160px";
			bcClose = document.getElementById("BusinessCardClose");
			bcHome = document.getElementById("BusinessCardHome");
			bcName = document.getElementById("BusinessCardName");
			bcNick = document.getElementById("BusinessCardNick");
			bcPhoto = document.getElementById("BusinessCardPhoto");
			bcPhotoA = document.getElementById("BusinessCardPhotoLink");
			bcFLD = document.getElementById("BusinessCardFLD");
			bcSED = document.getElementById("BusinessCardSend");
			bcDIV = document.getElementById("BusinessCardDIV");
			CT1 = document.getElementById("BusinessCardCT1");
			CT2 = document.getElementById("BusinessCardCT2");
			CT3 = document.getElementById("BusinessCardCT3");
			CT4 = document.getElementById("BusinessCardCT4");
			bcB = document.getElementById("BusinessCardLinkB");
			bcV = document.getElementById("BusinessCardLinkV");
			bcB2 = document.getElementById("BusinessCardLinkB2");
			bcQ = document.getElementById("BusinessCardLinkQ");
			bcP = document.getElementById("BusinessCardLinkP");
		}
		this.rtn = function (e) {
			if(e.stopPropagation) {
				e.stopPropagation();
			}
			else {
				e.cancelBubble = true;
			}
		}
		this.hidden = function () {
			//if(bcDiv != null ){ bcDIV.style.display = "none"; }
			clearInterval(timer);
		}
		this.show = function (u, e, f, a) {
			uid = u;
			showMode = false;
			sAction = a;
			var pageSize = getPageSize();
			bcNick.innerHTML = "读取中……";
			bcName.innerHTML = "读取中……";
			bcPhoto.src = "http://image2.sina.com.cn/blog/tmpl/v3/images/default_icon.jpg";
			bcSED.style.display = "none";
			bcFLD.style.display = "none";
			bcHome.style.display = "none";
			bcB.href = "http://blog.sina.com.cn/u/" + u;
			bcV.href = "http://v.blog.sina.com.cn/m/" + u;
			bcB2.href = "http://bbs.service.sina.com.cn/forum/disprofile.php?uid=" + u;
			bcQ.href = "http://q.sina.com.cn/mygroup.php?uid=" + u;
			bcP.href = "http://photo.sina.com.cn/u/" + u;
			bcClose.style.display = e == 0 ? "none" : "";
			bcDIV.style.display = "";
			var fL, fT;
			var x, y, w, h, ox, oy;
			if(f && f.frameElement) {// Iframe中
				var	pos = [0, 0];
				function getIframePos(_elem) {
					var _pos = [_elem.offsetLeft, _elem.offsetTop];
					parentNode = _elem.offsetParent;
					if (parentNode != _elem) {
						while (parentNode) {
							 _pos[0] += parentNode.offsetLeft;
							 _pos[1] += parentNode.offsetTop;
							 parentNode = parentNode.offsetParent;
						}
					}
					return _pos;
				}
				function getScopePos(fNode) {
					var _pos = [0, 0];
					var _posObj = null;
					while(fNode != window.scope){
						_posObj = getIframePos(fNode.frameElement);
						_pos[0] += _posObj[0];
						_pos[1] += _posObj[1];
						fNode=fNode.parent;
					}
					return _pos;
				}
				pos = getScopePos(f);
				fL = pos[0] - $(contentBody).scrollLeft;
				fT = pos[1] - $(contentBody).scrollTop;
				x = e == 0 ? 0 : e.clientX + fL;
				y = e == 0 ? 0 : e.clientY + fT;
			}
			else {// 主体中
				fT = fL = 0;
				x = e == 0 ? 0 : e.clientX;
				y = e == 0 ? 0 : e.clientY;
			}
			ox = pageSize[2];
			oy = pageSize[3];
			if(x > ox || y > oy)return false;
			w = 310;
			h = 160;
			bcDIV.style.left = (x + $(contentBody).scrollLeft + 3) + "px";
			bcDIV.style.top = (y + $(contentBody).scrollTop + 3) + "px";
			this.rtn(e);
			CT1.style.display = CT2.style.display = CT3.style.display = CT4.style.display = "none";
			if(isLoad == true) {
				CT3.style.display = "";
			}
			var timeoutNum = 4; // 超期时间[单位秒]
			var t = 0;
			card_data = null;
			var jl = new JsLoader();
			jl.onsuccess = function(){
				if(window["card_data"] != null) {
					_this.writeData(e);
				}
				else {
					this.onfailure();
				}
			}
			jl.onfailure = function(){
				CT4.style.display = CT2.style.display = CT3.style.display = CT1.style.display = "none";
				if(isLoad == true) {
					CT4.style.display = "";
				}
			}
			jl.load("http://util.blog.sina.com.cn/ui?t=c&" + u + "&" + new Date().valueOf(), "gb2312");
			return false;
		}
		this.show2 = function (u, e, f, a) {
			showCard(u, e, f, a);
			//this.show(u, e, f, a);
			showMode = true;
		}
		this.writeData = function (e) {
			if(card_data.length > 0) {// 有数据时候
				var udata = card_data[0];
				var m = parseInt(udata["uid"])%8+1;
				if(udata["url"] != "") {// 产品用户
					bcHome.href = "http://space.sina.com.cn/" + udata["uid"];
					bcNick.innerHTML = "昵&nbsp;&nbsp;&nbsp;&nbsp;称<b>:</b>&nbsp;<b><a  onclick='bc.createLog(\"nick\");' style='color:#5D5D5D;' target='_blank' href='http://space.sina.com.cn/" + udata["uid"] + "'>" + udata["nick"] + "</a></b>";
					bcPhotoA.href = "http://space.sina.com.cn/" + udata["uid"];
					bcName.innerHTML = "会员编码<b>:</b>&nbsp;<b><a onclick='bc.createLog(\"loginname\");' style='color:#5D5D5D;' target='_blank' href='http://space.sina.com.cn/" + udata["uid"] + "'>" + udata["uid"] + "</a></b>";
					bcPhoto.src = "http://portrait"+ m +".sinaimg.cn/"+ udata["uid"] +"/space/50";
					bcPhoto.alt = udata["nick"] + "的空间";
					if(e == 0) {
						bcFLD.style.display = "none";
					}
					else {
						bcFLD.style.display = "";
					}
					bcSED.style.display = "";
					bcHome.style.display = "";
					bcSED.onclick = function () {
						if(e == 0) {
						}
						if(showMode) {
							bcDialog.show2("http://my.blog.sina.com.cn/myblog/message/send_message.php?toid=" + udata["uid"], 278, 100);
							bc.hidden();
						}
						else {
							window.scope.bcDialog.show("http://my.blog.sina.com.cn/myblog/message/send_message_static.php?toid=" + udata["uid"], 278, 100);
							window.scope.bc.hidden();
						}
					}
					bcFLD.onclick = function () {
						if(e == 0) {}
						if(showMode) {
							bcDialog.show2("http://my.blog.sina.com.cn/friend/add_friend.php?opid=" + udata["uid"], 278, 258);
							bc.hidden();
						}
						else {
							window.scope.bcDialog.show("http://my.blog.sina.com.cn/friend/add_friend_static.php?opid=" + udata["uid"], 278, 258);
							window.scope.bc.hidden();
						}
					}
					var nPage = udata.article;
					var str = '最新文章更新:\
						<table width="160" border="0" cellspacing="0" cellpadding="0">\
						';
					for(var i = 0; i < nPage.length; i ++ ) {
						var sSplit = nPage[i].name.split("|");
						var sTxt = "";
						var sTxt2 = "";
						if(sSplit.length > 1) {
							sTxt = sSplit[0] + "...";
							sTxt2 = sSplit.join("");
						}
						else {
							sTxt2 = sTxt = sSplit.join("");
						}
						str += '\
						<tr>\
						<td height="18" valign="bottom" style="background-image:url(http://image2.sina.com.cn/blog/tmpl/v3/images/datong/card/dot.gif); background-repeat:no-repeat; padding-left: 8px; color: #3e2db0;" title="'+sTxt2+'"><a onclick="bc.createLog(\'article\');" href="http://blog.sina.com.cn/'+nPage[i].url+'" target="_blank" >' + sTxt + '</a></td>\
						</tr>\
						';
					}
					str += '</table>';
					if(nPage.length == 0) {
						CT1.innerHTML = "暂时没有内容更新";
					}
					else {
						CT1.innerHTML = "";
						addHTML(CT1, str);
					}
					CT2.style.display = CT3.style.display = CT4.style.display = "none";
					CT1.style.display = "";
					isLoad = true;
				}
			}
			else {// 裸用户
				udata = {uid: uid};
				bcHome.href = "";
				bcNick.innerHTML = "";
				bcName.innerHTML = "会员编码<b>:</b>&nbsp;<b><a  onclick='bc.createLog(\"loginname\");' style='color:#5D5D5D;' target='_blank' href='http://blog.sina.com.cn/u/" + udata["uid"] + "'>" + udata["uid"] + "</a></b>";
				bcPhoto.src = "http://image2.sina.com.cn/blog/tmpl/v3/images/default_icon.jpg";
				bcPhotoA.href = "";
				if(e == 0) {
					bcFLD.style.display = "none";
				}
				else {
					bcFLD.style.display = "";
				}
				CT1.style.display = CT2.style.display = CT3.style.display = CT4.style.display = "none";
				bcSED.style.display = "";
				bcHome.style.display = "none";
				isLoad = false;
			}
		}
	}
	var bc;
	bc = new BusinessCard();
	function hid() {
		bc.hidden();
	}
	if(document.addEventListener) {
		window.addEventListener("load", function () {
			bc.create();
			$(contentBody).addEventListener("click", hid, false);
		}, false);
	}
	else {
		window.attachEvent("onload", function () {
			bc.create();
			$(contentBody).attachEvent("onclick", hid);
		});
	}
}
else {// 如果不是在顶级窗口被引用
 	function hid() {
		window.scope.bc.hidden();
	}
	if(document.addEventListener) {
		window.addEventListener("load", function () {
			document.addEventListener("click", hid, false);
		}, false);
	}
	else {
		window.attachEvent("onload", function () {
			document.attachEvent("onclick", hid);
		});
	}
}
var Jobs = {
  addBannerFunction       : addBannerFunction,
  addDialogCloseEvent     : Event.observe.bind(   Event, 
                                                descByIds(scope.document, "#systemDialog#div>buttons#a>close"), 
                                                             "click", 
                                                             scope.hideSysDialog), 
  addAutoszieToCompIframe : function (){
    window.each(getCompHtmlElements(), addCompIframeOnload);
  }, 
  addAutoScrollToMain     : function (){
    var ifm = scope.byId("Content_ArticlePreview");
    if (!ifm) return;
    Event.observe(ifm,  "load",  function (){
    });
  },
  addAutoScrollToArticle  : function (){
   var ifm = scope.byId("contentIframeLink");
   if (!ifm) return;
   Event.observe(ifm,  "load",  (function (){
     var url = ifm.contentWindow.location.href;
     if (url.match(/_(\d+)\.html$/)[1] != "1")
       scope.location.hash = "#"+ ifm.name;
   }).protect());
  },
  autoSizeIframes         : function (){
    $$("iframe").each(function (iframe){
      if (iframe.id == "systemIframe") return;
      iframe.observe("load", window.scope.$IF.autoSizeMe.bind(iframe));
    });
  }, 
  applyCommentRestriction : function (){
    if (!scope.config.isCommentAllowed) {
      var cnt = scope.getArticleContainer();
      var node = descByIds(cnt, "#a>comments")
      node && node.parentNode.removeChild(node);
      var alnk = byId("contentIframeLink");
      alnk && (alnk.href="");
    }
  }, 
  applyMessageRestriction : function (){
    if (!scope.config.isMessageAllowed) {
      var zoneComp = scope.byId("blog_zone");
      var node = descByIds(zoneComp,  "#a>myGbook")
      node && node.parentNode.removeChild(node);
      var mc1 = scope.byId("mainMenu_control");
      if (!mc1) return;
      node = mc1.getElementsByTagName("a");
      node = node[node.length-1];
      if (!node) return;
      if (node.href.indexOf("gbook")>=0) {
        node.parentNode.removeChild(node.previousSibling);
        node.parentNode.removeChild(node);
      }
    }
  },  
  autoSizeOutBound        : function (){ window.onresize = resizeOutBound; resizeOutBound(); }, 
  fixAllowComment         : function (){
    scope.config.isCommentAllowed = scope.config.isCommentAllowed && (scope.isCommentAllowedBySystem != false);
  }, 
  fixMainMenu             : function (){
    var isMain = $getPageId() == "blog";
    var mm = scope.byId("mainMenu_control");
    fixMenuLink(mm, isMain);
  }, 
  fixHotArea              : function (){
    var isMain = $getPageId() == "blog";
    var mm = scope.byId("blog_zone");
    if (!mm) return;
    mm = descByIds(mm, "#div>componentContent");
    fixMenuLink(mm, isMain);
  }, 
  fixHotzoneGbookAddr     : function (){
    if (!scope.$isAdmin) return;
    var mm = scope.byId("blog_zone");
    if (!mm) {
      return;
    }
    mm = descByIds(mm, "#a>myGbook");
    if (mm){
      mm.href = fixGbookUrl(mm.href);
    } else {
    }
  }, 
  fixMainMenuGbookAddr    : function (){
    if (!scope.$isAdmin) return;
    var mm = scope.byId("main_gbook");
    if (mm){
      mm.href = fixGbookUrl(mm.href);
    }
  }, 
	activeChangeName : function(){
    if (!scope.$isAdmin) return;
		changeName.init();
	},
  createIframes           : createIframes,
  createIframeForArticle  : function (){
    var a = byId("contentIframeLink");
    a && createIframeByA(a);
  }, 
  divToIframeSwitch       : function (){
    var ifm = scope.byId("Content_ArticlePreview");
    Event.observe(ifm, "load", function (){
      try{
        ifm.contentWindow.location.href;
        scope.switchContainerToIframe();
      } catch (e){
	  }
    });
  }, 
  hideArticleSubContent   : function (){                                                           
    if (!scope.config.isCommentAllowed) {
      var t = $("contentIframeLink");
	  if(t){
		t.style.visibility="hidden";	  
	  }
    }
  }, 
  initComponent           : scope.$CreateDynamicComponent, 
  loadStaticInfo          : $ScriptLoader.request.bind(   $ScriptLoader, 
                                                        $BASE+"js/sinamessage.js", 
                                                                    {}),
  loadUserInfo            : scope.loadUserInfo, 
  moveTitleToHostComp     : function (){
    var title = $$("title")[0].innerHTML;
    if (window.frameElement) {
      var comp = $(window.frameElement).up("div.component");
      if (comp) comp.down("span#titleText").innerHTML = title;
    }
  }, 
  observeDialogIframe     : Event.observe.bind(   Event, 
                                                byId("systemIframe"), 
                                                            "load", 
                                                            scope.$IF.systemDialogIframeOnload.bind(byId("systemIframe"))), 
  reLayout                : scope.$Layout.layoutByConfig,
  replaceArtSortInArrPage : function (){
    var cmp = scope.byId("blog_sort");
    if (!cmp) return;
    var ul = descByIds(cmp, "#div>componentContent");
    if (!ul) return;
    var as = ul.getElementsByTagName("a");
    for (var i=0; i<as.length; ++i){
      var a = as[i];
      a.target = "_self";
      a.href = scope.byId("main_home").href + "#cmd:asc(" + a.href +")";
    }
  }, 
  requestRealTimeNick     : function (){
    var url = $Url("uic", {uid : uid});
    new scope.Ijax(url, { onComplete : fixNickName, charset:"gb2312" });
  }, 
  runAncCmdInMain         : runAnchorCommandInMainFrame.bind(scope, scope), 
  showPV                  : scope.$PV.show, 
  genArticlePageTitle     : function (){
    try{
      var articleTitle = descByIds("#articleBar#a>articleTitle").innerHTML.unescapeHTML();
      var pageTitle    = scope.document.title;
      scope.document.title = articleTitle + "-" + pageTitle; 
    } catch (e){
    }
  }, 
  addClickToggle          : addClickToggle.bind(   null), 
  addClickToggleToArtItem : function (){ 
    var acnt = scope.getArticleContainer();
    if (!acnt) return;
    var lis = acnt.getElementsByTagName("li");
    for (var i=0; i<lis.length; ++i){
      var li = lis[i];
      var bar = descByIds(li, "#articleBar#a>collapseButton");
      elementMethods.displayToggle(bar,"click");
      if(scope.$isAdmin) {
        var editBtn = descByIds(li, "#a>edit"); 
        var deleteBtn = descByIds(li, "#a>delete"); 
        editBtn && removeClassName(editBtn,"invisible");
        deleteBtn && removeClassName(deleteBtn,"invisible");
      }
    }
  }, 
  addClickToggleToArt     : function (){
    var comps = scope.$Layout.getCompsHashById();
    for (var i in comps){
      var comp = comps[i];
      var tbl = byClz(comp,  "a",  "toggleLink")[0];
      elementMethods.displayToggle(tbl);
    }
    elementMethods.displayToggle(scope.descByIds(scope.document, "#articleBar#a>collapseButton"));
  },  
  addClickToggleToCom      : function (){
    var ls = document.getElementsByTagName("li");
    for (var i=0;i<ls.length;++i){
      var bar = descByIds(ls[i],  "#commentBar");
      bar && elementMethods.displayToggle(bar);
    }
    var t = byId("commentPageBar");
    elementMethods.displayToggle(t);
    var f = byId("postComment");
    f = f.getElementsByTagName("legend")[0];
    f && elementMethods.displayToggle(f);
  },  
  addSlide                : addSlide.protect(), 
  fixPhotoSize            : function (){
    var cmp_p = byId("blog_photo");
    cmp_p && fixImageSize(descByIds(cmp_p,"#img>image"));
  },
  activeManage            : scope.$ActiveManage,
  initLayoutModule        : function (){
	window.scope.$layoutModule = new Module();
  },
  setPageMark		  : function (target) {
	window.scope.pageMark = target
  },
  initGlobalTip           : scope.setProcessTip,
  initMyRecordFloat		  :	function () {
	scope.recordPopup = new MyRecordPopup();
  },
	initArticleNavBtn			: function () {
		var url = "http://blog.sina.com.cn/s/articleprevnext_" + varblogid + ".html";
		new scope.Ijax(url, { onComplete : viewArticleNavBtn, charset:"gb2312" });
	}
}
function getCompHtmlElements(){
  var comps = [];
  var cols = [1,2];
  for (var i=0;i<cols.length; ++i){
    cols[i] = scope.document.getElementById("column_" + (i + 1));
    comps = comps.concat(getChildrenByClass(cols[i], "component"));
  }
  return comps;
}
function addCompIframeOnload(comp){
	try{
	  var iframe = comp.down("iframe");
	  iframe && iframe.observe("load", window.scope.autoSize.bind(scope, iframe));
	  autoSize(iframe);
	}catch(e){}
}
function addSlide(){
  if(window.scope.componentsName.findit("blog_diy_cboard")>=0){
    elementMethods.slideControl(childById(window.scope.componentsColumnID, "blog_diy_cboard"));
  }
}
function fixNickName(json){
  json = json.replace(/;$/, "").j2o();
  var name = json[0].nick;
  try{
    var node = descByIds(scope.document, "#blog_photo#div>intro").getElementsByTagName("a")[0];
    node.innerHTML = name;
  } catch (e){
  }
}
function viewArticleNavBtn (sCnt) {
	var job = sCnt.j2o();
	var str = "";
	if(job[0] != "") {
		str += "<div class='NavPrv'>前一篇:<a href='http://blog.sina.com.cn/s/blog_" + job[0].blogid + ".html'>" + job[0].label + "</a></div>"
	}
	if(job[1] != "") {
		str += "<div class='NavNext'>后一篇:<a href='http://blog.sina.com.cn/s/blog_" + job[1].blogid + ".html'>" + job[1].label + "</a></div>"
	}
	$("articleNavBtn").innerHTML = str;
}
function setUpgrade(){
	if(scope.$isAdmin){
		var node = byId("mainMenuImportant");
		node.innerHTML += '<DIV style="font-weight:300;color:#000000;PADDING-LEFT: 0px;FONT-SIZE: 12px; BACKGROUND: url(http://blogimg.sinajs.cn/images/update_bg.gif) no-repeat 0% 100%;WIDTH: 120px; POSITION: absolute; HEIGHT: 116px; margin-left: 753px; MARGIN-TOP: -62px; *margin-left: 700px; *MARGIN-TOP: -40px; "><DIV style="PADDING-RIGHT: 8px; PADDING-LEFT: 9px; PADDING-BOTTOM: 0px; LINE-HEIGHT: 22px; PADDING-TOP: 14px">全新模板,功能更强<STRONG>2008</STRONG>新版博客上线<BR><CENTER><A style="color:#000000;TEXT-DECORATION: underline" href="http://blog.sina.com.cn/lm/html/2008-04-18/1341.html" target=_blank>了解新版博客</A></CENTER></DIV><DIV style="MARGIN-TOP: 5px; TEXT-ALIGN: center"><A onclick="sendUpgrade();return false;" href="javascript:return false;"><IMG src="http://blogimg.sinajs.cn/images/update_but.gif"></A></DIV></DIV>';
	}
}
function sendUpgrade(){
	if(confirm('您确定升级到新版博客吗？升级后将无法返回到旧版博客。\n提示：为保证顺利升级，在升级中请避免使用"更换模板"、"添加模块"。')){
		var url = "http://my.blog.sina.com.cn/myblog/post_upgrade.php";
		include(url, function(){
	});
	}
}
var $Debug = false;
function main_sub(){
	var nHeight = byId("outBound").scrollHeight;
	if(nHeight == 0){setTimeout(main_sub, 500);return;}
	try{
	if($Br.$IE && $getPageId() == "comment"){
		parent.window.byId("contentIframeLink").style.height = nHeight + 50;
	}
	if($Br.$IE && $getPageId() == "blog"){
		parent.window.byId("Content_ArticlePreview").style.height = nHeight + 50;
	}
	}catch(e){}
}
function renderMain(){
  window._render_blog();
}
function main() {
  window._init_blog();
}
function main_article(){
  window._init_article();
}
function renderArticleMain(){
  window._render_article();
}
function init_article(){
  window._init_index();
}
function init_articleList() {
   window._init_alist();
}
function init_message() {
  window._init_gbook();
}
function init_comment(){
  window._init_comment();
  init_comment_post();
}
function init_circle(){
  window._init_circle();
}
function init_album(){
  window._init_album();
}
function init_album_icons(){
  window._init_album_icons();
}
function render(pageId){
  var func = window["_render_" + pageId];
  if (func != null && typeof(func) == "function"){
    func();
  } 
}
function init(pageId){
  var func = window["_init_" + pageId];
  if (func != null && typeof(func) == "function"){
    func();
  } 
}
window._render_blog = function (){
  if($Br.$IE && document.body.readyState != 'loaded' && document.body.readyState != 'complete'){
    renderMain.delayed(500);
    return;
  }
  if (window.Sina && Sina.util && Sina.util.Trace) Sina.util.Trace.init(true);
  setCommentNum2();  
  Jobs.showPV();  
  Jobs.setPageMark("index");
  Jobs.fixMainMenuGbookAddr();
  Jobs.fixHotzoneGbookAddr();
  Jobs.reLayout();
  Jobs.divToIframeSwitch();
  Jobs.addAutoScrollToMain();
  Jobs.runAncCmdInMain();
  Jobs.requestRealTimeNick();
  Jobs.addClickToggleToArtItem();
  Jobs.addAutoszieToCompIframe();
  Jobs.observeDialogIframe();
  Jobs.addBannerFunction();
  Jobs.addDialogCloseEvent();
  Jobs.loadUserInfo();
  Jobs.loadStaticInfo();
  //window.scope.Dialog.showUhostDialog();
  window.scope.completeConfig();
  window.scope.$CreateDynamicComponent();
  Jobs.addSlide();
  Jobs.showPV();
  Jobs.activeChangeName();
  Jobs.initLayoutModule();
  Jobs.initGlobalTip();
  Jobs.initMyRecordFloat();
  $ScriptLoader.request("http://blogpagin.sinajs.cn/article?"+window.scope.uid+"&0", {
    onComplete : articlePageFunc
  });
}
window._init_blog = function () {
  Jobs.fixPhotoSize();
}
function setCommentNum2 (){
  if (!window.$ArticleIds){
    window.setTimeout(setCommentNum2, 500);
  }else{
    $ScriptLoader.request(scope.$Url("commentsNum", {aid:$ArticleIds}), {});
  }
}
window._render_article = function (){
  if (window.Sina && Sina.util && Sina.util.Trace) Sina.util.Trace.init(false);
  Jobs.setPageMark("article");
  Jobs.fixMainMenuGbookAddr();
  Jobs.fixHotzoneGbookAddr();
  Jobs.replaceArtSortInArrPage();
  Jobs.fixAllowComment();
  Jobs.applyCommentRestriction();
  Jobs.applyMessageRestriction();
  Jobs.requestRealTimeNick();
  var subContentManager = function(url){
    scope.$("contentIframeLink").href = url;
    scope.setTimeout(function (){ scope.location.hash = "#contentIframeLink";}, 10);
  }
  var cmd = createAnchorCommand();
  cmd.setExecutor("asc", subContentManager);   
  cmd.runCommands();
  var hash = scope.location.hash.substr(1);
  switch (hash){
    case 'comment':
      var utl = byId("articleUtil");
      var cir = descByIds(utl, "#comments");
      scope.$("contentIframeLink").href = cir.href;
      scope.setTimeout(function (){ scope.location.hash = "#contentIframeLink";}, 10);
      break;
    case 'circleinfo' :
      var utl = byId("articleUtil");
      var cir = descByIds(utl, "#circle");
      scope.$("contentIframeLink").href = cir.href;
      scope.setTimeout(function (){ scope.location.hash = "#contentIframeLink";}, 10);
      break;
  }
  Jobs.showPV();
  Jobs.createIframeForArticle();
  Jobs.addAutoScrollToArticle();
  Jobs.autoSizeIframes();
  Jobs.genArticlePageTitle();
  Jobs.hideArticleSubContent();
  Jobs.reLayout();
  Jobs.loadStaticInfo();
  Jobs.observeDialogIframe();
  Jobs.addBannerFunction();
  Jobs.addDialogCloseEvent();
  Jobs.loadUserInfo();
  Jobs.initGlobalTip();
  Jobs.initMyRecordFloat();
  $ScriptLoader.request("http://blogpagin.sinajs.cn/article?"+window.scope.uid+"&0", {
    onComplete : articleIndexPageFunc
  });
  var ifm = byId("contentIframeLink");
  autoSizeIframe5Times(ifm);
  window.scope.completeConfig();
  window.scope.$CreateDynamicComponent();
}
window._init_article = function (){
  Jobs.fixPhotoSize();
  autoSize();
}
window._render_index = function (){
  if (window._renderedIndex) return;
  window._renderedIndex = true;
  Jobs.showPV();
  setCommentNum2();
  Jobs.fixAllowComment();
  Jobs.applyCommentRestriction();
  Jobs.addClickToggleToArtItem();
  var subContentManager = function(url){
    scope.$("contentIframeLink").href = url;
    scope.setTimeout(function (){ scope.location.hash = "#contentIframeLink";}, 10);
  }
  var cmd = createAnchorCommand();
  cmd.setExecutor("asc", subContentManager);   
  cmd.runCommands();
  Jobs.addClickToggleToArt();
  Jobs.genArticlePageTitle();
  Jobs.createIframes();
  if (this.location.href.match(/index_/)!=null)
    $ScriptLoader.request("http://blogpagin.sinajs.cn/article?"+window.scope.uid+"&0", {
      onComplete : articleIndexPageFunc
    });
  return;
}
window._init_index = function (){
  window._render_index();
  autoSize();
}
window._render_alist = function (){
  if (window._renderedAlist) return;
  window._renderedAlist = true;
  var match = window.location.href.match(/alist_(\d*)_(\d*)_(\d*)\.html/);
  if (!match) return;
  var articleIndex = match[2];
  $ScriptLoader.request("http://blogpagin.sinajs.cn/article?"+window.scope.uid+"&"+articleIndex, {
    onComplete : function (nKey) {
      generatePagingForSubpage(nKey/20, "articleList", "articleListPageDiv");
      scope.autoSize(scope.getConIF());
    }
  });
  autoSize();
}
window._init_alist = function () {
  window._render_alist();
  autoSize();
}
window._render_gbook = function (){
  if (window._renderedGbook) return;
  window._renderedGbook = true;
  autoSize();
  Jobs.addClickToggle();
  var messageFormIframe = $$("iframe#messageForm")[0];
  var watchHandler = {
    login : {
      succ : function (){
        scope.loadUserInfo();
        try{
          var win = this.getWin().parent;
          var url = fixGbookUrl(win.location.href, true);
          win.location.href = url;
        } catch (e){
          alert("error occur while processing post gbook" + e);
        }
      },
      fail : function (){
        alert("登录失败");
      }
    },
    gbook_post : {
      succ : function (rs){
        alert(rs.text);
        try{
          var win = this.getWin().parent;
          win.location.reload();
          scope.$("blog_last_gbook").comp.reload();
        } catch (e){
        }
      },
      fail : function (rs){
        alert(rs.text);
      }
    },
    gbook_del : {
      succ : function (rs){
        alert(rs.text);
        try{
          var win = this.getWin().parent;
          win.location.reload();
          scope.$("blog_last_gbook").comp.reload();
        } catch (e){
        }
      },
      fail : function (rs){
        alert(rs.text);
      }
    }
  };
  scope.$IF.watchIframe(messageFormIframe, watchHandler);
  $ScriptLoader.request("http://blogpagin.sinajs.cn/gbook?" + window.scope.uid, {
    onComplete : function (nKey) {
      generatePagingForSubpage(nKey/50, "gbook", "gbookPageDiv");
      scope.autoSize(scope.getConIF());
    }
  });
  autoSize();
}
window._init_gbook = function (){
  window._render_gbook();
  Jobs.addClickToggle();
  autoSize();
}
window._init_serial = function (){
  autoSzie();
}
window._render_serial = function (){
  autoSize();
  return;
}
window._render_comment = function (){
  if (window._renderedComment) return;
  window._renderedComment = true;
  init_comment_post();
  Jobs.addClickToggleToCom();
  var observer = function (e){
    var t = confirm("确定要删除此评论吗?");
     if (!t) {
    } else if (!window.inOperation) {
      window.inOperation=true;
      $("requestProxy").getWin().location.href=this.href;
    } else {
      alert("上一个操作正在处理,请稍后再删除");
    }
    Event.stop(e);
  }
  var lis = document.getElementsByTagName("li");
  for (var i=0; i<lis.length; ++i){
    var e = descByIds(lis[i], "#a>delete");
    Event.observe(e, "click", observer.bindAsEventListener(e));
  }
  var handler = {
    comment_del : {
      succ : function (r){
        alert(r.text);
        window.inOperation=false;
         var si = r.subInstruction;
        if (si && si.refresh) {
          var win = this.getWin().parent.parent;
          win.location.href=si.refresh.readAttribute("addr");
          win.location.reload();
        }
      },
      fail : function (r){
        alert(r.text);
        window.inOperation=false;
      }
    }
  };
  var ifm = this.byId("requestProxy");
  window.scope.$IF.watchIframe(ifm,handler);
  window.scope.toggleAdminUtil();
  var articleId = parent 
                  .location.href.match(/_([\w\d]+)\.html/) || [];
  articleId = articleId[1];
  $ScriptLoader.request(scope.$Url("commentsNum", {aid:articleId}), {});
  return;
}
window._init_comment = function (){
  _render_comment();
  autoSize();
}
window._render_album = function (){
  autoSize();
  return;
}
window._init_album = function (){
  createAssistants();
  autoSize();
}
window._render_album_icons = function (){
  return;
}
window._init_album_icons = function (){
  init_album_icon_slide();
}
window._render_circle = function (){
  return;
}
window._init_circle = function (){
}
function articlePageFunc(nKey) {
  var container = $("articlePageDiv");
  var iCurrPage = 1;
  var iMaxPage = Math.ceil(nKey / 10);
  var html = PagingLine.Create(iCurrPage, iMaxPage, scope.$Url("articleSingle", {
    id : scope.uid,
    page : "@page@"
  }), "Content_ArticlePreview").ToggleEndpoint(true)
  .Render("zh-cn");
  container.innerHTML = html;
  scope.autoSize(scope.getConIF());
  return;
};
function articleIndexPageFunc(nKey) {
  generatePagingForSubpage(nKey/10, "articleSingle", "articlePageDivIF");
  scope.autoSize.bind(scope, scope.byId("Content_ArticlePreview")).delayed(500);
}
  scope.wait = function(re, cb, interval){
	if(!interval) interval = 10;
	if(!re||!cb) return;
	re.waitItv = setInterval(function(){
		try{
			if(re()){
				cb();
				clearInterval(re.waitItv);
			}
		}catch(e){ 
			clearInterval(re.waitItv); 
		}
	},interval);
}
function setCommentsNumInArticle(ar){
  this.comments_num = ar;
  var cnt = $("articleContainer");
  if (!cnt) return;
  var _lis = cnt.childNodes, lis = [];
  for (var i=0; i<_lis.length; ++i){
    if (_lis[i].nodeType == 1) lis.push(_lis[i]);
  }
  for (var i=0; i<lis.length; ++i){
    var li   = lis[i];
    var con  = childById(li, "articleContentArea");
    var utl  = childById(con, "articleUtil");
    var cmnt = childById(utl, "comments");
    var num  = childById(cmnt, "commentsNum");
    if(num)
	num.innerHTML = ar[i] == null ? "" : ar[i];
  }
}
function $SetCommentsNum(ar){
  window.comments_num = ar;
  var pr = window.parent;
  pr.setCommentsNumInArticle && pr.setCommentsNumInArticle(ar);
  generatePagingForSubpage.bind(this, Math.ceil(ar[0]/50), "comment", "pageArea", "contentIframeLink").Try();
  autoSize();
}
function init_comment_post(){
  if (window.$$inited) return;
  window.$$inited = true;
  window.scope.log("init_comment_post");
  var ifm = $("dataHolder");
  var handler = {
    post_comment : {
      succ : function (r){
        var addr = r.subInstruction.refresh.readAttribute("addr");
        var win = this.getWin().parent;
        win.location.href=addr;
        win.location.reload();
        alert(r.text)
      },
      fail : function (r){
        alert("发表评论失败:" + r.text);
    load_chk_img('chk_img');
      }
    }
  };
  window.scope.$IF.watchIframe(ifm, handler);
  autoSize();
}
try{parent.informIframeReady(this);} catch (e){}
function delArticle(article_id,event){
  var url = "http://my.blog.sina.com.cn/writing/scriber/article_del_recycle_static.php?blog_id=" + article_id;
  if(confirm("确认要删除此文章吗？删除后可以到文章回收站恢复！")) new scope.Ijax(url,{
    onStart : function () {
      window.scope.globalTip.onProgress("正在删除");   
    },
    onComplete : function (text) {
      text = text.replace(/^\s|\s$/g,"");
      if(text == "1"){
        alert("文章删除成功！");
        refreshArticleFeeds();  
        try{
          $("blog_last_post").comp.reload();
        }catch(e){}
      }else{
        alert("文章删除失败！");
      }
    }
  })
  Event.stop(event);
  return false; 
}
function editArticle(article_id, event){
  Event.stop(event);
  var editURL = "http://my.blog.sina.com.cn/writing/scriber/article_edit.php?openmode=static&f=static&blog_id="+article_id;
  window.open(editURL,"","width=690,height=550,left=" + (window.screen.width-690)/2 + ",top=" + (window.screen.height-550)/2+",scrollbars=yes");
  return false; 
}
function refreshArticleFeeds(){
  try{
    var ifm = scope.$("Content_ArticlePreview").contentWindow;
    ifm.byId("articleContainer").nodeType;
    ifm.location.reload();
    try{
      scope.reFreshComponent("blog_last_post");
    }catch(e){
    }
  } catch (e){
    scope.location.reload();
  }
}
function callAlbum(){
  var t = byId("Content_ArticlePreview");
  if (t.style.display == "none"){ 
    t.src = $Url("albumList", {id:uid});
  } else {
    t.contentWindow.location.href = $Url("albumList", {id:uid});
  }
  scope.switchContainerToIframe();
}
