﻿/// <reference path="jquery-1.3.2-vsdoc.js" />

var blogurl = '/';
var blogdir = '/';

var msie = $.browser.msie;
var locationhref = window.location.href.lastIndexOf("#") > -1 ? window.location.href.substring(0, window.location.href.lastIndexOf("#")) : window.location.href; ;
var noquerystringurl = locationhref.lastIndexOf("?") > -1 ? locationhref.substring(0, locationhref.lastIndexOf("?")) : locationhref;

function $$(_sId) { return document.getElementById(_sId) ? document.getElementById(_sId) : null }

function URLencode(sStr) {
	return (sStr).replace(/\+/g, '%2B').replace(/\"/g, '%22').replace(/\'/g, '%27').replace(/\//g, '%2F');
}
//post数据
//ajaxpost(url,data,successdo,isshowdialog) ajaxpost(data) ajaxpost(data,successdo,isshowdialog)
var ajaxpost = function() {
    var url = arguments[0], data, successdo, isshowdialog = true, iscoverdiv = false, length = arguments.length;
    if (length == 1) {
        url = noquerystringurl;
        data = arguments[0];
    }
    else {
        if (typeof url == "object") {
            url = noquerystringurl;
            data = arguments[0];
            successdo = arguments[1];
            isshowdialog = arguments[2];
        }
        else {
            if (url == '')
                url = noquerystringurl;
            data = arguments[1];
            successdo = arguments[2];
            isshowdialog = arguments[3];
        }
    }
    if (typeof isshowdialog != "boolean")
        isshowdialog = true;
    if (iscoverdiv)
        popCoverDiv();
    //alert(data.toString());
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: function(msg) {
            switch (typeof successdo) {
                default:
                    if (isshowdialog) {
                        showmsg(msg, successdo);
                    }
                    else {
                        successdo(msg);
                    }
                    break;
            }
        },
        complete: function(XMLHttpRequest, textStatus) {
        },
        error: function() {
            //请求出错处理
            if (iscoverdiv) {
                $("#cover_div").remove();
            }
            if (msie) {
                alert("操作出错，请重试");
            }
        }
    });
}
function unselectall() {
    if (document.myform.chkAll.checked) {
        document.myform.chkAll.checked = document.myform.chkAll.checked & 0;
    }
}

function CheckAll(form) {
    for (var i = 0; i < form.elements.length; i++) {
        var e = form.elements[i];
        if (e.Name != "chkAll")
            e.checked = form.chkAll.checked;
    }
}
//选项卡
function iboxActive(id, key, num, max) {
    var menu = document.getElementById(id + "menu");
    (menu.getElementsByTagName("INPUT")[0] || {}).value = key;
    var main = menu.parentNode;
    var applyfilter;
    var menudivs = menu.getElementsByTagName("DIV");
    for (var i = 0; i < menudivs.length; i++) {
        menudivs[i].className = id + "menuoff";
        (menudivs[i].getElementsByTagName("A")[0] || {}).className = "";
    }
    menudivs[num].className = id + "menuon" + (num % max);
    (menudivs[num].getElementsByTagName("A")[0] || {}).className = "active";
    try {
        applyfilter = main.filters && main.filters[0];
        if (applyfilter) {
            main.filters[0].apply();
        }
    } catch (e) { }
    var parent = menu.parentNode;
    var childs = parent.childNodes;
    var divs = [];
    for (var i = 0, c = childs.length; i < c; i++) {
        if (childs[i].tagName == 'DIV') {
            if (divs.length) childs[i].style.display = 'none';
            divs[divs.length] = childs[i];
        }
    }
    divs[num + 1].style.display = 'block';
    try {
        if (applyfilter) {
            main.filters[0].play();
        }
    } catch (e) { }
}
function submitpost(url, data, complete) {
	ajaxpost(url,data,complete,true);
}
function showmsg(msg, complete) {
	var facenum = 1;
	var url = '';
	if (typeof (msg) == "string") {
		if (complete) {
			complete(msg);
		}
		else {
			//			window.location = noquerystringurl;
			$(".tips").html(msg);
			setTimeout("window.location = locationhref", 1000);
		}
	}
	else if (typeof (msg) == "object") {
	    var str = $(msg).find("item").eq(0).text();
	    facenum = $(msg).find("item").eq(1).text();
		url = $(msg).find("url").text();
		//	alert(url);
		if (str == '') {
			if (url != '') {
				window.location = url;
			}
			else {
				if (complete) {
					complete(msg);
				}
			}
		}
		else {
			showdialog(str, facenum, url, complete, msg);
		}
	}
}
function showdialog(msg, facenum, url, obj, xmlobj) {
	if (facenum != "1" && facenum != "2") {
		facenum = "1";
	}
	var oDialog = new dialog(blogurl);
	oDialog.init();
	oDialog.set('src', facenum);
	oDialog.event(msg, '');
	if (typeof (obj) == "function") {
		oDialog.buttonnew('dialogOk', obj, url, xmlobj);
		oDialog.buttonnew('dialogClose', obj, url, xmlobj);
	}
	else {
		oDialog.buttonnew('dialogOk', obj, url);
		oDialog.buttonnew('dialogClose', obj, url);
	}
}
//post数据的时候覆盖一个透明层，防止服务器超时造成误操作
function popCoverDiv() {
    $("#cover_div").remove();
	var coverDiv = document.createElement('div');
	document.body.appendChild(coverDiv);
	coverDiv.id = 'cover_div';
	var coverSpan = document.createElement('span');
	coverSpan.id = "cover_span";
	coverSpan.innerHTML = "";
	coverDiv.appendChild(coverSpan);

	with (coverDiv.style) {
		position = 'absolute';
		background = '#999999';
		left = '0px';
		top = '0px';
		var bodySize = getBodySize();
		width = bodySize[0] + 'px'
		height = bodySize[1] + 'px';
		zIndex = 98;
		if (msie) {
			filter = "Alpha(Opacity=60)";
		} else {
			opacity = 0.6;
		}
	}
	with (coverSpan.style) {
		position = 'absolute';
		left = '600px';
		top = '355px';
		zIndex = 98;
	}
}
function getBodySize() {
	var bodySize = [];
	var scroll = getScroll();
	with (document.documentElement) {
		bodySize[0] = (scroll.w > clientWidth) ? scroll.w : clientWidth; //如果滚动条的宽度大于页面的宽度，取得滚动条的宽度，否则取页面宽度
		bodySize[1] = (scroll.h > clientHeight) ? scroll.h : clientHeight; //如果滚动条的高度大于页面的高度，取得滚动条的高度，否则取高度
	}
	return bodySize;
}
function getScroll() {
	var t, l, w, h;
	if (document.documentElement && document.documentElement.scrollTop) {
		t = document.documentElement.scrollTop;
		l = document.documentElement.scrollLeft;
		w = document.documentElement.scrollWidth;
		h = document.documentElement.scrollHeight;
	} else if (document.body) {
		t = document.body.scrollTop;
		l = document.body.scrollLeft;
		w = document.body.scrollWidth;
		h = document.body.scrollHeight;
	}
	return { t: t, l: l, w: w, h: h };
}
var opost = function() {
    var data = new Object();
    this.add = function(id, val) {
        if (val) {
            data[id] = val;
        }
        else {
            var obj = $("#" + id);
            if (obj.attr("type") == "radio" || obj.attr("type") == "checkbox") {
                data[id] = getinputchecked(id);
            }
            else {
                data[id] = $.trim($("#" + id).val());
            }
        }
    }
    this.send = function(url, complete, isshowdialog) {
        ajaxpost(url, data, complete, isshowdialog);
    }
}
function getselectjson(action, obj, selectid ,dodo) {
	//	alert(action);
	var $obj = $("#" + obj);
	if (!$obj.get(0))
		return false;
	$.getJSON(blogdir+"ajaxserver.aspx?action=" + action, function(data) {
		$obj.empty();
		$.each(data, function(i, item) {
			//			if (selectid == item.id) {
			//				$("<option value='" + item.id + "' selected>" + item.name + "</option>").appendTo($obj);
			//			}
			//			else {
			//					$("<option value='" + item.id + "'>" + item.name + "</option>").appendTo($obj);
			//			}
			$("#" + obj).get(0).options.add(new Option(item.name, item.id, false, false));
		});
		$obj.val(selectid);
		if (dodo)
			dodo(obj, data);
		else {
			if (data.length == 0) {
				$obj.empty();
				$("<option>无可用选项</option>").appendTo($obj);
				$obj.attr("disabled", true);
			}
		}
	});
}
function GetSelectJson(data, obj, selectid, dodo) {
    var $obj = $("#" + obj);
    if (!$obj.get(0))
        return false;
    ajaxpost(blogdir + "handlers/ajax.ashx", postdata(data), function(data) {
        $obj.empty();
        $.each(eval(data), function(i, item) {
            $("#" + obj).get(0).options.add(new Option(item.name, item.id, false, false));
        });
        if ($obj.get(0).options.length <= 1) $obj.remove(); 
        $obj.val(selectid);
        if (dodo)
            dodo(obj, data);
        else {
            if (data.length == 0) {
                $obj.empty();
                $("<option>无可用选项</option>").appendTo($obj);
                $obj.attr("disabled", true);
            }
        }
    });
}
//添加select by sk 参数：名称 再添加项 获取参数 容器 
function appendselect(selectName, item, action, container) {
    var nextItem = item + 1;
    if ($("#" + selectName + item).val() <= 0) {
        $("#" + selectName + nextItem).remove();
        return false;
    }
    if (document.getElementById(selectName + nextItem) == null) {
        $("#" + container).append("<select id=\"" + selectName + nextItem + "\" name=\"" + selectName + nextItem + "\"> <option value=\"0\">正在载入...</option></select>");
        $("#" + selectName + nextItem).bind("change", function() {
            appendselect(selectName, nextItem, action, container);
        });
    }
    GetSelectJson({ "action": action, "parentid": $("#" + selectName + item).val() }, selectName + nextItem);
    //移除nextitem后面select
    $.each($("select[id*='" + selectName + "']"), function(i, item) {
        var id = item.name.replace(selectName, "");
        if (id > nextItem)
            $("#" + selectName + id).remove();
    });

    //移除无数据项select
    //$("#Container").html(($("#" + selectName + nextItem).html()));
    //if ($("#" + selectName + nextItem).find("option").length <= 1) {
    //$("#" + selectName + nextItem).hide();
    //    return false;
    //}
}
function getinputchecked(inputname) {
	var obj = $('input[name=' + inputname + ']');
	if (obj == undefined)
		return '';
	if (obj.length == 0) {
		return '';
	}
	if (obj.length == 1) {
		if (obj.attr("checked")) {
			return obj.val();
		}
		else {
			return '';
		}
	}
	else {
		var val = "";
		obj.each(function() {
			if ($(this).attr("checked")) {
				if (val == '')
					val = $(this).val();
				else
					val = val + "," + $(this).val();
			}
		});
		return  $.trim(val);
	}
}

function postdata(data) {
    var tdata = '';
    for (var key in data) {
        tdata += "&" + escape(key) + "=" + escape(data[key]);
    }
    tdata = tdata.replace(/^&/g, "");
    return tdata
}
function generateMixed(n) {
	var res = "";
	for (var i = 0; i < n; i++) {
		var id = Math.ceil(Math.random() * 9);
		res += id;
	}
	return res;
}
function showlogin() {
	popCoverDiv();
	ajaxpost(blogurl + "ajaxserver.aspx", "action=getlogincode", function(msg) {
		var loginstr;
	    if (msg == 999) {
			loginstr = "请勿重复登录";
		}
		else {
			loginstr = "用户名：<input type='text' value='' id='UserName'><br /><br />密　码：<input type='password' value='' id='Password'><br /><br />" + msg + "<div id='loginerr' style='color:red;padding-top:5px'></div>";

		}
	    var oDialog = new dialog(blogurl);
		oDialog.init();
		oDialog.set('title', "登录窗口");
	    oDialog.set('src', blogurl+"images/login.png");
		oDialog.event(loginstr);
	    if (msg == 999) {
			oDialog.button('dialogCancel', '$("#cover_div").remove()');
			oDialog.button('dialogClose', '$("#cover_div").remove()');
		}
		else {
			oDialog.button('dialogOk', "chklogin()");
			oDialog.button('dialogCancel', '$("#cover_div").remove()');
			oDialog.button('dialogClose', '$("#cover_div").remove()');
		}
	}, false);
}
function chklogin() {
    var p = new opost();
	p.add("UserName");
	p.add("Password");
	p.add("returnUrl", $.query.get("returnUrl"));
	p.add("comeurl", noquerystringurl);
	p.add("action", "login");
	p.add("loginfrom", "userpage");
	p.add("codestr");
	p.add("ob_codename");
	p.send(blogurl + "login.aspx", userlogindo, false);
}
function userlogindo(msg) {
    var str = $(msg).find("item").eq(0).text();
    var state = $(msg).find("item").eq(1).text();
    if (state == "1") {
        $("#loginerr").html(str);
        var codeimgscr = $("#ob_codeimg").attr("src");
        $("#ob_codeimg").attr("src", codeimgscr + "&t=" + Math.random());
    }
    else if (state == "2") {
        new dialog(blogurl).reset(0);
        $("#cover_div").remove();
        $("#userlogin").html($(msg).find("item").eq(0).text());
        ajaxpost(blogurl + "ajaxserver.aspx", "action=getwebheader", function(msg) {
            if (msg != '') {
                $(".BlogLogin").html(msg);
            }
        }, false);
    }
}
function noshowdialogdo(msg) {
	if (typeof (msg) == "object") {
		var str = $(msg).find("item").eq(0).text();
		var state = $(msg).find("item").eq(1).text();
		var gurl = $(msg).find("url").text();
		if (str == '') {
		    new dialog(blogurl).reset(0);
			$("#cover_div").remove();
//			if (gurl != '') {
//				window.location = gurl;
//			}
		}
		else {
		    $("#loginerr").html(str.split('##')[0]);
			if (state == 2) {
			    setTimeout("$('#cover_div').remove();new dialog('" + blogurl + "').reset(0);", 1000);
			    if (gurl != '') {
			        // window.location = gurl;
			        setTimeout("window.location =' " + gurl + " '", 1500);
			    }
			}
		}
	}
	if (typeof (msg) == "string") {
		showlogin();
	}
}
function showpm(incept,topic) {
	popCoverDiv();
	if (!incept) incept = '';
	if (!topic) topic = '';
	var strfriendslist = "<select id='friendslist'><option value='-1'>载入中...</option></select>";
	if (incept != '' || topic != '')
		strfriendslist = '';
    var oDialog = new dialog(blogurl);
	oDialog.init();
	oDialog.set('title', "发送短消息");
	oDialog.set('src', blogurl+ "images/login.png");
	oDialog.event("收件人：<input type='text' value='" + incept + "' id='incept'>" + strfriendslist + "<br /><br />标　题：<input type='text' value='" + topic + "' id='pmtopic'><br /><br />内　容：<br /><textarea name='pmcontent' id='pmcontent' cols='30' rows='8' maxlength='240'></textarea><div id='loginerr' style='color:red;padding-top:5px'></div>");
	oDialog.button('dialogOk', "sendpm()");
	oDialog.button('dialogCancel', '$("#cover_div").remove()');
	oDialog.button('dialogClose', '$("#cover_div").remove()');
	if (incept != '') {
		$("#incept").attr("readonly",true);
	}
	if (strfriendslist != '') {
		getselectjson("getuserfriend", "friendslist");
		$("#friendslist").change(function() {
			var svalue = $.trim($("#incept").val());
			var fvalue = $("#friendslist").val();
			if (svalue != "") {
				if (svalue.indexOf(fvalue + ',') >= 0 || svalue.indexOf(',' + fvalue) >= 0 || svalue == fvalue) {
					//				$("#loginerr").html('请勿重复选择');
					return false;
				}
				if (fvalue != "0") {
					$("#incept").val(svalue + "," + fvalue);
				}
			}
			else {
				$("#incept").val(fvalue);
			}
		});
	}
}
function sendpm() {
	var content = $("#pmcontent").val();
	var topic = $("#pmtopic").val();
	var incept = $("#incept").val();
	if (incept == '') {
		$("#loginerr").html('请输入接受站内短信的用户名！');
		return false;
	}
	if (topic == '') {
		$("#loginerr").html('请输入标题！');
		return false;
	}
	if (content == '') {
		$("#loginerr").html('请输入内容！');
		return false;
	}
	var p = new opost();
	p.add("incept", incept);
	p.add("topic", topic);
	p.add("content", content);
	p.add("action", "savepm");
	p.send(blogurl+"ajax.aspx", noshowdialogdo, false);
}
function showaddfriend(state,friendname) {
	popCoverDiv();
	var oDialog = new dialog(blogurl);
	oDialog.init();
	if (state == 0) {
		oDialog.set('title', "添加好友");
	}
	else {
		oDialog.set('title', "添加黑名单");
	}
	oDialog.set('src',blogurl+ "images/login.png");
	oDialog.event("用户名：<input type='text' value='' id='friendname'><br /><br /><div id='loginerr' style='color:red;padding-top:5px'></div>");
	oDialog.button('dialogOk', "addfriend(" + state + ")");
	oDialog.button('dialogCancel', '$("#cover_div").remove()');
	oDialog.button('dialogClose', '$("#cover_div").remove()');
	if (!friendname)
		friendname = '';
	$("#friendname").val(friendname);
}
function addfriend(state) {
	var p = new opost();
	p.add("friendname");
	p.add("state", state);
	p.add("action", "savefriend");
	p.send(blogurl+"ajax.aspx", noshowdialogdo, false);
}
function resetImageSize(e, mWidth) {
    var image = new Image();
    image.src = e.src;
    var w = image.width;
    var h = image.height;
    if (w > mWidth) {
        e.width = mWidth;
        e.height = h * mWidth / w;
    }
}

function rsimg(o, w) {
    if (o.width > w) {
        var tw = w > 0 ? w : o.width;
        o.resized = true;
        o.width = tw;
        o.height = (tw / o.width) * o.height;
    }
}
function bbimg(o) {
    var zoom = parseInt(o.style.zoom, 10) || 100; zoom += event.wheelDelta / 12; if (zoom > 0) o.style.zoom = zoom + '%';
    return false;
}
function DrawImage(ImgD, iwidth, iheight) {
	//参数(图片,允许的宽度,允许的高度)    
	var image = new Image();
	image.src = ImgD.src;
	if (image.width > 0 && image.height > 0) {
		if (image.width / image.height >= iwidth / iheight) {
			if (image.width > iwidth) {
				ImgD.width = iwidth;
				ImgD.height = (image.height * iwidth) / image.width;
			} else {
				ImgD.width = image.width;
				ImgD.height = image.height;
			}
		} else {
			if (image.height > iheight) {
				ImgD.height = iheight;
				ImgD.width = (image.width * iheight) / image.height;
			} else {
				ImgD.width = image.width;
				ImgD.height = image.height;
			}
		}
	}
}
//设置首页
function sethome(obj, url) {
    try {
        obj.style.behavior = 'url(#default#homepage)'; obj.setHomePage(url); return (false);
    }
    catch (e) {
        if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch (e) {
                alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将[signed.applets.codebase_principal_support]设置为’true’");
            }
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
            prefs.setCharPref('browser.startup.homepage', url);
        }
    }
}
//加入收藏夹
function AddFavorite(sURL, sTitle) {
    try {
        window.external.addFavorite(sURL, sTitle);
    }
    catch (e) {
        try {
            window.sidebar.addPanel(sTitle, sURL, "");
        }
        catch (e) {
            alert("加入收藏失败，请使用Ctrl+D进行添加");
        }
    }
}
function copyclip(meintext) {
	if (window.clipboardData) {
		if (window.clipboardData.setData("Text", meintext)) {
			alert('复制成功');
			return true;
		}
		else {
			alert('复制失败\n');
			return false;
		}
	} else if (window.netscape) {
		try {
			netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
		} catch (e) {
			alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");
			return false;
		}

		var clip = Components.classes['@mozilla.org/widget/clipboard;1']
				 .createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return false;


		var trans = Components.classes['@mozilla.org/widget/transferable;1']
				  .createInstance(Components.interfaces.nsITransferable);
		if (!trans) return false;

		trans.addDataFlavor('text/unicode');

		var str = new Object();
		var len = new Object();

		var str = Components.classes["@mozilla.org/supports-string;1"]
				.createInstance(Components.interfaces.nsISupportsString);

		var copytext = meintext;

		str.data = copytext;

		trans.setTransferData("text/unicode", str, copytext.length * 2);

		var clipid = Components.interfaces.nsIClipboard;

		if (!clip) return false;

		clip.setData(trans, null, clipid.kGlobalClipboard);

	}
	alert('复制成功');
	return true;
}
/* innerhtml.js
* Copyright Ma Bingyao <andot@ujn.edu.cn>
* Version: 1.9
* LastModified: 2006-06-04
* This library is free.  You can redistribute it and/or modify it.
* http://www.coolcode.cn/?p=117
*/

var global_html_pool = [];
var global_script_pool = [];
var global_script_src_pool = [];
var global_lock_pool = [];
var innerhtml_lock = null;
var document_buffer = "";

function set_innerHTML(obj_id, html, time) {
    if (innerhtml_lock == null) {
        innerhtml_lock = obj_id;
    }
    else if (typeof (time) == "undefined") {
        global_lock_pool[obj_id + "_html"] = html;
        window.setTimeout("set_innerHTML('" + obj_id + "', global_lock_pool['" + obj_id + "_html']);", 10);
        return;
    }
    else if (innerhtml_lock != obj_id) {
        global_lock_pool[obj_id + "_html"] = html;
        window.setTimeout("set_innerHTML('" + obj_id + "', global_lock_pool['" + obj_id + "_html'], " + time + ");", 10);
        return;
    }

    function get_script_id() {
        return "script_" + (new Date()).getTime().toString(36)
          + Math.floor(Math.random() * 100000000).toString(36);
    }

    document_buffer = "";

    document.write = function(str) {
        document_buffer += str;
    }
    document.writeln = function(str) {
        document_buffer += str + "\n";
    }

    global_html_pool = [];

    var scripts = [];
    html = html.split(/<\/script>/i);
    for (var i = 0; i < html.length; i++) {
        global_html_pool[i] = html[i].replace(/<script[\s\S]*$/ig, "");
        scripts[i] = { text: '', src: '' };
        scripts[i].text = html[i].substr(global_html_pool[i].length);
        scripts[i].src = scripts[i].text.substr(0, scripts[i].text.indexOf('>') + 1);
        scripts[i].src = scripts[i].src.match(/src\s*=\s*(\"([^\"]*)\"|\'([^\']*)\'|([^\s]*)[\s>])/i);
        if (scripts[i].src) {
            if (scripts[i].src[2]) {
                scripts[i].src = scripts[i].src[2];
            }
            else if (scripts[i].src[3]) {
                scripts[i].src = scripts[i].src[3];
            }
            else if (scripts[i].src[4]) {
                scripts[i].src = scripts[i].src[4];
            }
            else {
                scripts[i].src = "";
            }
            scripts[i].text = "";
        }
        else {
            scripts[i].src = "";
            scripts[i].text = scripts[i].text.substr(scripts[i].text.indexOf('>') + 1);
            scripts[i].text = scripts[i].text.replace(/^\s*<\!--\s*/g, "");
        }
    }

    var s;
    if (typeof (time) == "undefined") {
        s = 0;
    }
    else {
        s = time;
    }

    var script, add_script, remove_script;

    for (var i = 0; i < scripts.length; i++) {
        var add_html = "document_buffer += global_html_pool[" + i + "];\n";
        add_html += "document.getElementById('" + obj_id + "').innerHTML = document_buffer;\n";
        script = document.createElement("script");
        if (scripts[i].src) {
            script.src = scripts[i].src;
            if (typeof (global_script_src_pool[script.src]) == "undefined") {
                global_script_src_pool[script.src] = true;
                s += 2000;
            }
            else {
                s += 10;
            }
        }
        else {
            script.text = scripts[i].text;
            s += 10;
        }
        script.defer = true;
        script.type = "text/javascript";
        script.id = get_script_id();
        global_script_pool[script.id] = script;
        add_script = add_html;
        add_script += "document.getElementsByTagName('head').item(0)";
        add_script += ".appendChild(global_script_pool['" + script.id + "']);\n";
        window.setTimeout(add_script, s);
        remove_script = "document.getElementsByTagName('head').item(0)";
        remove_script += ".removeChild(document.getElementById('" + script.id + "'));\n";
        remove_script += "delete global_script_pool['" + script.id + "'];\n";
        window.setTimeout(remove_script, s + 10000);
    }

    var end_script = "if (document_buffer.match(/<\\/script>/i)) {\n";
    end_script += "set_innerHTML('" + obj_id + "', document_buffer, " + s + ");\n";
    end_script += "}\n";
    end_script += "else {\n";
    end_script += "document.getElementById('" + obj_id + "').innerHTML = document_buffer;\n";
    end_script += "innerhtml_lock = null;\n";
    end_script += "}";
    window.setTimeout(end_script, s);
}
function openWin(obj, url, target) {
	if (!target)
		target = "_self";
	obj.target = target;
	obj.href = url;
	obj.click();
}
function loginedo() {
	var codeimgscr = $("#ob_codeimg").attr("src");
	$("#ob_codeimg").attr("src", codeimgscr + "&t=" + Math.random());
}
//编辑器提交，提交按钮的id必须为submiteditor
$(document).ready(function() {
    $("#submiteditor").click(function() {
        $('#savestate').html('<img src="' + blogurl + 'images/loading.gif" align="absmiddle" />数据提交中…请稍候…');
        $(this).attr("disabled", "true");
        var action = "save" + $.query.get("action");
        var p = new opost();
        p.add("action", action);
        $("input").each(function(i) {
            p.add($(this).attr("name"), $(this).val());
        });
        p.add("id");
        p.add("ob_codename");
        p.add("codestr");
        p.add("edit", URLencode(oEdit1.getHTMLBody()));
        p.send(noquerystringurl, complete, true);
    });
    var complete = function() {
        $('#savestate').html('');
        $("#submiteditor").removeAttr("disabled");
        var codeimgscr = $("#ob_codeimg").attr("src");
        $("#ob_codeimg").attr("src", codeimgscr + "&t=" + Math.random());
    }
    $("#Login").click(function() {
        var CookieDate = $("input[name=CookieDate][checked]");
        var p = new opost();
        p.add("UserName");
        p.add("Password");
        p.add("returnUrl", $.query.get("returnUrl"));
        p.add("comeurl", noquerystringurl);
        p.add("codestr");
        p.add("ob_codename");
        if (CookieDate != undefined) {
            p.add("CookieDate", CookieDate.val());
        }
        p.add("action", "login");
        p.send(blogdir + "login.aspx", loginedo, true);
    });
    $("#Password").keydown(function(e) {
        var key = window.event ? event.keyCode : e.which;
        key == 13 && $("#Login").click();
        //event.keyCode == 13 && $("#Login").click();
    });
    $("#codestr").keydown(function(e) {
        var key = window.event ? event.keyCode : e.which;
        key == 13 && $("#Login").click();
        //event.keyCode == 13 && $("#Login").click();
    });
$("#Search").click(function () {      var regionid = 0;       var region = $("select[id*='select-linkage']");       var lastId = region[region.length - 1].value;        if (region.length > 1) {           if (region[0].value == "0") return false;          regionid = lastId > 0 ? lastId : region[region.length - 2].value;       }        location.href = blogdir + "blog.aspx?regionid=" + regionid + "&selecttype=" + $("#selecttype").val() + "&q=" + encodeURIComponent($("#q").val());   });    //导航条 固定置顶
    //    $(window).scroll(function() {
    //        $("#BlogWebHeader").css({ position: 'absolute', top: $('body').scrollTop() });
    //        if ($('body').scrollTop() == "0") $("#BlogWebHeader").css({ position: 'fixed' });
    //    });
    //搜索
    if ($("#J_Select_type")) {

        var selectObj = $(".select-options ul li");
        //        var count = 0;
        //        selectObj.toggleClass("display", count++ % 2 == 0);
        $(".select-value").bind("click", function() {
            $(".select-options").css({ display: 'block' });
        });
        //$(".select-options").bind("mouseout", function() { $(this).css({ display: 'none' }); });
        selectObj.hover(function() { $(this).className = "over"; }, function() { $(this).className = ""; });
        //        selectObj.bind("mouseover", function() {
        //            $(this).className = "over";
        //        });
        //        selectObj.bind("mouseout", function() {
        //            $(this).className = "";
        //        });
        selectObj.bind("click", function() {
            $(".select-value").text($(this).text());
            $(".select-options").css({ display: 'none' });
            var type = $(this).attr('name');
            var pn;
            $("#type").val(type);
            switch (type) {
                case "username":
                    pn = "blog";
                    break;
                case "blogname":
                    pn = "blog";
                    break;
                case "log":
                    pn = "blog";
                    break;
                default:
                    pn = "blog";
            }
            $("form[name='search']").attr("action", "{0}.aspx?type={1}&q={2}".format(pn, $("#type").val(), escape($("#q").val())));
        });

    }
});


String.prototype.Trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); }
String.prototype.LTrim = function() { return this.replace(/(^\s*)/g, ""); }
String.prototype.RTrim = function() { return this.replace(/(\s*$)/g, ""); }
//String.format = function(str) {
//    var args = arguments, re = new RegExp("%([1-" + args.length + "])", "g");
//    return String(str).replace(
//        re,
//        function($1, $2) {
//            return args[$2];
//        }
//    );
//};
String.prototype.format = function() { 
    var args = arguments; 
    return this.replace(/{(\d{1})}/g, function(){ 
        return args[arguments[1]]; 
    }); 
};
//FF支持 obj.outerHTML
if (typeof (HTMLElement) != "undefined" && !window.opera) {
    HTMLElement.prototype.__defineGetter__("outerHTML", function() {
        var a = this.attributes, str = "<" + this.tagName, i = 0; for (; i < a.length; i++)
            if (a[i].specified) str += "   " + a[i].name + '="' + a[i].value + '"';
        if (!this.canHaveChildren) return str + "   />";
        return str + ">" + this.innerHTML + "</" + this.tagName + ">";
    });
    HTMLElement.prototype.__defineSetter__("outerHTML", function(s) {
        var d = document.createElement("DIV"); d.innerHTML = s;
        for (var i = 0; i < d.childNodes.length; i++)
            this.parentNode.insertBefore(d.childNodes[i], this);
        this.parentNode.removeChild(this);
    });
    HTMLElement.prototype.__defineGetter__("canHaveChildren", function() {
        return !/^(area|base|basefont|col|frame|hr|img|br|input|isindex|link|meta|param)$/.test(this.tagName.toLowerCase());
    });
}
if (window.HTMLElement) {
    HTMLElement.prototype.insertAdjacentHTML = function(sWhere, sHTML) {
        var df;  // : DocumentFragment
        var r = this.ownerDocument.createRange();
        switch (String(sWhere).toLowerCase()) {
            case "beforebegin":
                r.setStartBefore(this);
                df = r.createContextualFragment(sHTML);
                this.parentNode.insertBefore(df, this);
                break;
            case "afterbegin":
                r.selectNodeContents(this); r.collapse(true);
                df = r.createContextualFragment(sHTML);
                this.insertBefore(df, this.firstChild);
                break;
            case "beforeend":
                r.selectNodeContents(this);
                r.collapse(false);
                df = r.createContextualFragment(sHTML);
                this.appendChild(df);
                break;
            case "afterend":
                r.setStartAfter(this);
                df = r.createContextualFragment(sHTML);
                this.parentNode.insertBefore(df, this.nextSibling);
                break;
        }
    };
    HTMLElement.prototype.__defineGetter__("all", function() {
        var a = this.getElementsByTagName("*");
        var node = this;
        a.tags = function(sTagName) {
            return node.getElementsByTagName(sTagName);
        }
        return a;
    });
}
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}
	
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
//addEvent(window,'unload',EventCache.flush);
