﻿// jstyle.js

// Javascript Extension Begin

var Jx = new function() {
  this.Version = "Version 1.7.0.0045 (2011-07-09)";
  this.IsGecko = ((navigator.userAgent.toLowerCase().indexOf('gecko') != -1) 
    && (navigator.userAgent.toLowerCase().indexOf('khtml') == -1));
  this.IsIE = !!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1);
  this.IsStupidIE6 = this.IsIE && (!window.XMLHttpRequest);
  this.Extend = function(dest, mtds) {
    if(dest == HtmlObject.prototype) {this.HtmlExtensions.push(mtds); return;}
    if(dest == TextArea.prototype) {this.TextAreaExtensions.push(mtds); return;}
    for(var name in mtds) {dest[name] = mtds[name];}
    if(!Jx.IsGecko && mtds.toString != Object.prototype.toString) {
      dest.toString = mtds.toString; // Stupid IE ignores all "toString" key.
    }
  }
  this.ExtendAll = function(dest, arrmtds) {
    for(var i = 0; i < arrmtds.length; i ++) {this.Extend(dest, arrmtds[i]);}
  }
  this.HtmlExtensions = [];
  this.TextAreaExtensions = [];
  this.ExtendHtml = function(d) {
    if(!d._HTMLObjectExtended) {
      if(this.IsGecko) {d = HTMLElement.prototype;}
      this.ExtendAll(d, this.HtmlExtensions);
      d._HTMLObjectExtended = true;
    }
  }
  this.ExtendTextArea = function(d) {
    if(d.tagName && (d.tagName.toLowerCase() == "textarea") && (!d._TextAreaExtended)) {
      this.ExtendAll(d, this.TextAreaExtensions);
      d._TextAreaExtended = true;
    }
  }
  window.HtmlObject = {};
  window.HtmlObject.prototype = {};
  window.TextArea = {};
  window.TextArea.prototype = {};
}

var $A = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  var length = iterable.length, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

var $ = function(el) {
  if(Jx.IsString(el)) {el = document.getElementById(el);}
  if(!el) {return el;}
  Jx.ExtendHtml(el);
  Jx.ExtendTextArea(el);
  return el;
}

var $Class = function() {
  var baseClass = null, properties = $A(arguments);
  if (Jx.IsFunction(properties[0])) {baseClass = properties.shift();}

  var NewObj = function() {
    var obj = baseClass ? new baseClass : new Object;
    obj.Initialize = Jx.EmptyFunction;
    for(var i=0; i<properties.length; i++) {
      Jx.Extend(obj, properties[i]);
    }
    return obj;
  }

  var NewClass;
  if(baseClass && baseClass.prototype.NotInheritable) {
    NewClass = function() {
      var obj = NewObj();
      obj.Initialize.apply(obj, arguments);
      return obj;
    }
    NewClass.prototype.NotInheritable = true;
  } else {
    NewClass = function() {
      this.Initialize.apply(this, arguments);
    }
    NewClass.prototype = NewObj();
  }
  return NewClass;
}

// Dont extend follow "Is" function into object, because in stupid IE, 
// DOM object is not based on Javascript object, they will not be extended.
Jx.Common = {
  IsString   : function(obj) {return typeof obj == "string"   ;},
  IsFunction : function(obj) {return typeof obj == "function" ;},
  IsNumber   : function(obj) {return typeof obj == "number"   ;},
  IsUndefined: function(obj) {return typeof obj == "undefined";},

  EmptyFunction: function() { },

  GetEvent: function (e) {
    // in firefox, the e is event; in IE, e is undefined, use window.event
    return e || window.event;
  }, 
  GetSender: function(e) {
    // in firefox, e.target is sender; in IE, e.srcElement is sender
    e = this.GetEvent(e); return e.target || e.srcElement || document;
  },
  CancelEvent: function(e) {
    e = this.GetEvent(e);
    if ("cancelBubble" in e) { e.cancelBubble = true; } 
    if ("stopPropagation" in e) { e.stopPropagation(); }
    if ("preventDefault" in e) { e.preventDefault(); }
    if ("returnValue" in e) { e.returnValue = false; }
    return false; 
  },
  
  NewEl: function (tag, className) {
    var htag = $(document.createElement(tag));
    if(className) {
      className = className.trim();
      if(className != "") {htag.className = className;}
    }
    return htag;
  }
};

// Stupid IE do not support Array as prototype
Jx.ArrayExtension = {
  NotInheritable: !Jx.IsGecko 
}

Jx.EventExtension = {
  RegEvent: function(evt, hevt) {
    if(this.addEventListener) {
      this.addEventListener(evt, hevt, false);
    } else if(this.attachEvent) {
      this.attachEvent("on"+evt, hevt);
    }
  },
  
  UnregEvent: function(evt, hevt) {
    if(this.removeEventListener) {
      this.removeEventListener(evt, hevt, false);
    } else if(this.detachEvent) {
      this.detachEvent("on"+evt, hevt); 
    }
  }
}

Jx.FunctionExtension = {
  Bind: function() {
    if (arguments.length < 2 && arguments[0] === undefined) return this;
    var __method = this, args = $A(arguments), object = args.shift();
    return function() {
      return __method.apply(object, args.concat($A(arguments)));
    }
  },
  
  BindEvent: function() {
    var __method = this, args = $A(arguments), object = args.shift();
    return function(e) {
      return __method.apply(object, [Jx.GetEvent(e), Jx.GetSender(e)].concat(args));
    }
  }
}

Jx.StringExtension = {
  trim: function() {
    return this.replace(/(^\s*)|(\s*$)/g, ""); 
  },

  Contains: function(t) {
    return this.indexOf(t) >= 0;
  },
  
  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();
  },

  EvalJSON: function() {
    return eval("(" + this + ")");
  }
}


Jx.Extend(Jx                  , Jx.Common           );
Jx.Extend(Array.prototype     , Jx.ArrayExtension   );
Jx.Extend(HtmlObject.prototype, Jx.EventExtension   );
Jx.Extend(document            , Jx.EventExtension   );
Jx.Extend(window              , Jx.EventExtension   );
Jx.Extend(Function.prototype  , Jx.FunctionExtension);
Jx.Extend(String.prototype    , Jx.StringExtension  );

// Javascript Extension End

Jx.Extend(HtmlObject.prototype, {
  AddText: function (text) {
    if (text) {
      this.appendChild(this.ownerDocument.createTextNode(text));
    }
    return this;
  },

  AddEl: function (tag, cls, text) {
    var newel = $(this.ownerDocument.createElement(tag));
    if (cls) { newel.className = cls; }
    if (text) { newel.AddText(text); }
    this.appendChild(newel);
    return newel;
  },

  RemoveAll: function () {
    var len = this.childNodes.length;
    for (var i = len - 1; i >= 0; i--) {
      this.removeChild(this.childNodes.item(i));
    }
  },

  GetStyleProp: function (style) {
    style = style.camelize();
    var value = this.style[style];
    if (Jx.IsIE) {
      if (!value && this.currentStyle) { value = this.currentStyle[style] };
      if (value == 'auto') {
        if ((style == 'width' || style == 'height') && (this.GetStyleProp('display') != 'none'))
          return this['offset' + style.capitalize()] + 'px';
        return null;
      }
      return value;
    } else {
      if (!value || value == 'auto') {
        var css = document.defaultView.getComputedStyle(this, null);
        value = css ? css[style] : null;
      }
      return value == 'auto' ? null : value;
    }
  },

  GetAbsTop: function () {
    if (!Jx.IsIE) {
      return this.offsetTop;
    } else { // IE sucks
      var ly, el = this;
      for (ly = 0; el != null; ly += el.offsetTop - el.scrollTop, el = el.offsetParent);
      return ly;
    }
  },

  GetAbsLeft: function () {
    if (!Jx.IsIE) {
      return this.offsetLeft;
    } else { // IE sucks
      var lx, el = this;
      for (lx = 0; el != null; lx += el.offsetLeft - el.scrollLeft, el = el.offsetParent);
      return lx;
    }
  },

  GetSize: function () {
    var display = this.GetStyleProp('display');
    if (display != 'none' && display != null)  // Safari bug
      return { Width: this.offsetWidth, Height: this.offsetHeight };
    var els = this.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    var originalWidth = this.clientWidth;
    var originalHeight = this.clientHeight;
    els.display = originalDisplay;
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return { Width: originalWidth, Height: originalHeight };
  },

  GetHeight: function () {
    return this.GetSize().Height;
  },

  GetWidth: function () {
    return this.GetSize().Width;
  },

  Fill: function (dest, clone) {
    dest = $(dest); if (!dest) { return; }
    dest.RemoveAll();
    var children = [], i;
    for (i = 0; i < this.childNodes.length; i++) {
      if (this.childNodes[i].nodeName.toLowerCase() != "script") {
        children.push(clone ? this.childNodes[i].cloneNode(true) : this.childNodes[i]);
      }
    }
    for (i = 0; i < children.length; i++) { dest.appendChild(children[i]); }
  },

  Show: function () {
    this.style.display = ""; return this;
  },

  Hide: function () {
    this.style.display = "none"; return this;
  },

  MoveIn: function (dest) {
    if (dest) {
      dest.innerHTML = "";
      dest.appendChild(this);
    }
  }
});

Jx.Extend(document, {
  ParsePre: function() {
    var ShortContent = function(elmt) {
      var txt = elmt.innerHTML;
      elmt.innerHTML = txt.replace(/[^<>]+<|[^<>]+$/g, TryInsertWBR);
    }
    var TryInsertWBR = function (txt) {
      return txt.replace(/\b((&[^;]+;)|[^&]){8,}\b/g, InsertWBR);
    }
    var InsertWBR = function(txt) {
      return txt.replace(/((&[^;]+;)|[^&]){8}/g, "$&<wbr/>");
    }
    
    this.ConvAll(this.body, "pre", ShortContent);
  },

  ConvAll: function (elmt, tag, conv) {
    tag = tag.toLowerCase();
    for(var i = 0; i < elmt.childNodes.length; i ++) {
      var child = elmt.childNodes.item(i); 
      if(child.nodeType == 1) { 
        if(child.tagName.toLowerCase() == tag) {
          conv(child);
        } else { this.ConvAll(child, tag, conv); }
      }
    }
  }
});

var _StartUp = $Class({
  Initialize: function() {
    this.Exts = [];
    this.CurrentExt = 0;
  },
  
  Reg51yes: function(host, id) {
    var url = "http://" + host + ".51yes.com/click.aspx?id=" + id + "&logo=12";
    this.Exts.push({Url:url, Charset:"gb2312", Tag:"span", Id:"xst", Func:null});
  },
  
  ScptBlk: function(url, charset) {
    return '<script type="text/javascript"'
      + ' src="' + url + '"'
      + (charset ? ' charset="' + charset + '"' : "")
      + '></script>';
  },

  WriteExtBlks: function(path) {
    if(this.Exts.length > 0) {
      var extblk = this.ScptBlk(path + "/startup.js");
      for(var i=0; i<this.Exts.length; i++) {
        var ext = this.Exts[i];
        document.write(extblk);
        document.write(this.ScptBlk(ext.Url, ext.Charset));
      }
      document.write(extblk);
    }
  },

  RunExt: function(){
    if(this.CurrentExt > 0) { this.ExtEnd(); }
    this.ExtBegin();
    this.CurrentExt ++;
  },
  
  ExtBegin: function() {
    if((this.CurrentExt<0) || (this.CurrentExt >= this.Exts.length)) { return; }
    var ext = this.Exts[this.CurrentExt];
    if(ext.Func) {ext.Func();}
    document.write("<" + ext.Tag + ' id="_' + ext.Id + '" style="display:none;">');
  },
  
  ExtEnd: function() {
    if((this.CurrentExt<=0) || (this.CurrentExt > this.Exts.length)) { return; }
    var ext = this.Exts[this.CurrentExt-1];
    document.write("</" + ext.Tag + ">");
    this.Uph(ext.Id);
  },
  
  Uph: function(id) {
    var src = $("_" + id), dest = $(id);
    if(src && dest) {
      dest.RemoveAll();
      dest.appendChild(src);
      src.style.display = "";
    }
  },
  
  GetScrollTop: function() {
    return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  },
  
  GetScrollLeft: function() {
    return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
  }
});

var StartUp = new ($Class(_StartUp, {
  Initialize: function () {
    this.Stat51yes = { Host: "", Id: "" };
    this.Bars = [];
    this.TopAds = [];
    this.TopAdLen = 3;
    this.TopAdCsns = ["topimg1", "topimg2", "topimg3"];
    this.TopBadCsns = ["tbcnt1", "tbcnt2", "tbcnt3"];
    this.BarElId = "bar";
    this.PadCsn = "padstar";
    this.AdId = "ad325";
    this.AdHtml = '<a href="http://www.bobopo.com">www.bobopo.com</a>';
    this.MenuId = "menu";
    this._MenuEl = null;
    this._LastShow = null;
  },

  Article: function (path, via) {
    this.DoMenu();
    this.ArrangeElmts();
    this.AddBars();
    this.WrtTop(via);
    this.WrtAd();
    this.WrtFooter();
    this.WriteExtBlks(path);
  },

  Index: function (path, via) {
    this.DoMenu();
    this.ArrangeElmtsIndex();
    this.AddBars();
    this.WrtTop(via);
    this.WrtFooter();
    this.WriteExtBlks(path);
  },

  Navigator: function (path, via) {
    this.DoMenu();
    this.AddBars();
    this.WrtTop(via);
    this.WrtAd();
    this.WrtFooter();
    this.WriteExtBlks(path);
  },

  ChgBanner: function (imgpath, imgext, imgnum) {
    var dt = new Date(), fdt = new Date(1970, 0, 1);
    var day = (Math.floor((dt - fdt) / 86400000) + 1) % imgnum;
    var imgid = day == 0 ? "" : (day < 10 ? "0" : "") + day.toString();
    $("banner").setAttribute("src", imgpath + imgid + imgext)
  },

  ArrangeElmts: function () {
    var el;
    el = $("c2"); if (el) { el.Fill("c1") }
    el = $("t2"); if (el) { el.Fill("t1") }
    el = $("m2"); if (el) { el.Fill("m1") }
    el = $("n2"); if (el) { el.Fill("n1") }
    if (Jx.IsGecko) { document.ParsePre(); }
  },

  ArrangeElmtsIndex: function () {
    $("n2").Fill($("n1"), true);
  },

  AddBars: function () {
    if (!this.Bars) { return; }
    var barel = $(this.BarElId);
    for (var i = 0; i < this.Bars.length; i++) {
      var bar = this.Bars[i];
      var padel = barel.AddEl("div", bar.Csn);
      padel.AddEl("s");
      padel.AddText(bar.Label);
      for (var j = 0; j < bar.Links.length; j++) {
        padel.AddText(" ");
        var link = padel.AddEl("a", "", bar.Links[j].Text);
        link.setAttribute("href", bar.Links[j].Url);
        link.setAttribute("target", "_blank");
        link.setAttribute("title", bar.Links[j].Ad);
      }
    }
  },

  WrtFooter: function () {
    var stat = "";
    if (this.Stat51yes.Host && this.Stat51yes.Id) {
      stat = ' <span id="xst"></span>';
      this.Reg51yes(this.Stat51yes.Host, this.Stat51yes.Id);
    }
    document.write("<p>&copy; 2008-2011 bopopo.com" + stat + "</p>");
  },

  WrtTop: function (via) {
    var i, sts = [];
    for (i = 0; i < this.TopAds.length; i++) {
      sts.push(false);
    }
    var topel = $("adpic");
    var el, elbig, st, elcnt, elnk, elimg, pn;
    for (i = 0; i < this.TopAdLen; i++) {
      st = -1;
      while (st < 0) {
        st = Math.floor(Math.random() * 6);
        if (sts[st]) { st = -1; } else { sts[st] = true; }
      }
      pn = Math.floor(Math.random() * this.TopAds[st].Pics) + 100;
      el = topel.AddEl("div", this.TopAdCsns[i], "");
      elimg = el.AddEl("img");
      elimg.setAttribute("src", via + "/ad/" + (st + 10).toString() + pn.toString() + ".jpg");
      elbig = topel.AddEl("div", "topbig");
      elcnt = elbig.AddEl("div", this.TopBadCsns[i]);
      elnk = elcnt.AddEl("div", "tbimg").AddEl("a");
      elnk.setAttribute("href", this.TopAds[st].Url);
      elnk.setAttribute("target", "_blank");
      elimg = elnk.AddEl("img");
      elimg.setAttribute("src", via + "/ad/b" + (st + 10).toString() + pn.toString() + ".jpg");
      elnk = elcnt.AddEl("div", "tbcap").AddEl("a", "", this.TopAds[st].Ad)
      elnk.setAttribute("href", this.TopAds[st].Url);
      elnk.setAttribute("target", "_blank");
      elbig.RegEvent("mouseout", this.HideTop.Bind(this, elbig));
      elbig.Hide();
      el.RegEvent("mouseover", this.ShowTop.Bind(this, el, elbig));
      elbig.RegEvent("mouseover", this.ShowTop.Bind(this, el, elbig));
    }
  },

  ShowTop: function (el, elbig) {
    if (this._LastShow) {
      if (this._LastShow == elbig) { return; }
      this._LastShow.Hide();
    }
    var t = el.GetAbsTop();
    var l = el.GetAbsLeft();
    var w = el.GetWidth();
    var wbig = elbig.GetWidth();
    elbig.Show();
    elbig.style.top = t.toString() + "px";
    elbig.style.left = (l + w - wbig).toString() + "px";
    this._LastShow = elbig;
  },

  HideTop: function (el) {
    el.Hide();
    this._LastShow = null;
  },

  DoIE6: function () {
    if (Jx.IsStupidIE6) { window.RegEvent("scroll", this.StickMenu.Bind(this)); }
  },

  DoMenu: function () {
    window.RegEvent("scroll", this.StickMenu.Bind(this));
  },

  StickMenu: function () {
    if (!(this._MenuEl)) { this._MenuEl = $(this.MenuId); }
    if (this._MenuEl) {
      this._MenuEl.style.top = this.GetScrollTop().toString() + "px";
      //this._MenuEl.style.left = this.GetScrollLeft().toString() + "px";
    }
  },

  WrtAd: function () {
    $(this.AdId).innerHTML = this.AdHtml;
  }
}));

StartUp.Stat51yes = { Host: "count41", Id: "414756592" };

StartUp.TopAds = [
  { Url: "http://www.blabla.cn", Text: "布啦布啦", Ad: "布啦布啦网页教程与代码", Pics: 4 },
  { Url: "http://www.woyouxian.com", Text: "我有闲", Ad: "中外名著免费公益图书馆", Pics: 4 },
  { Url: "http://www.wowstory.com", Text: "窝说", Ad: "言情侦探科幻武侠等闲书窝窝", Pics: 4 },
  { Url: "http://www.hubapo.com", Text: "胡八婆", Ad: "许多看来不相干的事其实都是相互有关联的", Pics: 4 },
  { Url: "http://www.ahanova.com", Text: "英文原著", Ad: "免费外文原版名著", Pics: 4 },
  { Url: "http://www.woyouxian.net", Text: "IT教程", Ad: "性感IT教程和撩人技术文章", Pics: 4 }
];

StartUp.TopSns = [
  { Url: "http://www.facebook.com/bobopohome", Text: "Facebook", Ad: "加波波坡为Facebook好友", Pics: 4 },
  { Url: "http://www.renren.com/bobopo", Text: "人人网", Ad: "加波波坡为人人网好友", Pics: 4 },
  { Url: "http://www.kaixin001.com/home/?uid=90828836", Text: "开心网", Ad: "加波波坡为开心网好友", Pics: 4 },
  { Url: "http://user.qzone.qq.com/1410834168", Text: "QQ空间", Ad: "加波波坡为QQ好友", Pics: 4 }
];

StartUp.TopMb = [
  { Url: "http://twitter.com/bobopo", Text: "Twitter", Ad: "透过Twitter了解波波坡", Pics: 4 },
  { Url: "http://bobopo.t.sohu.com/", Text: "搜狐", Ad: "透过搜狐微博了解波波坡", Pics: 4 },
  { Url: "http://t.sina.com.cn/bobopo", Text: "新浪", Ad: "透过新浪微博了解波波坡", Pics: 4 },
  { Url: "http://t.163.com/bobopo", Text: "网易", Ad: "透过网易微博了解波波坡", Pics: 4 },
  { Url: "http://t.qq.com/bobopo_com", Text: "腾讯", Ad: "透过腾讯微博了解波波坡", Pics: 4 },
  { Url: "http://www.plurk.com/bobopo", Text: "Plurk", Ad: "透过Plurk了解波波坡", Pics: 4 }
];

StartUp.TopRss = [
  { Url: "rss.xml", Text: "RSS订阅", Ad: "RSS订阅波波坡的最新内容", Pics: 4 }
];

StartUp.Bars = [
  { Csn: "padsns", Label: "社交: ", Links: StartUp.TopSns },
  { Csn: "padmb", Label: "微博: ", Links: StartUp.TopMb },
  { Csn: "padrss", Label: "订阅: ", Links: StartUp.TopRss },
  { Csn: "padstar", Label: "推荐: ", Links: StartUp.TopAds }
];
// eof
