var BROWSER = {};
var winarr = new Array();
function createWindows(tit, con, width, height, obj, e) {
   if(!winarr[obj]) {
	   var tx='<div id="'+obj+'">';
	   tx+='<div class="title"><h1>'+tit+'</h1><span>关闭</span></div>';
	   tx+='<div class="con">'+con+'</div>';
	   tx+='</div>';
	   $("body").append(tx);
	   winarr[obj]=1;
	   var evt = e || window.event;
	   var x = parseInt($(document).scrollLeft())+parseInt(evt.clientX);
	   var y = parseInt($(document).scrollTop())+parseInt(evt.clientY);
	   var left=x-parseInt(width);
	   var top=y+10;
       if(left<1) left=30;
	   $("#"+obj).css({'position':'absolute','z-index':'10000','width':width,'height':height,'top':top,'left':left,'padding':'4px','border':'#006D00 4px solid','background-color':'#ffffff'});
	   $("#"+obj+' .title').css({'height':'23px','padding':'7px 10px 0','background':'#006D00','color':'#fff'});
	   $("#"+obj+' .title h1').css({'float':'left','padding':'0','margin':'0','font-size':'14px','line-height':'16px'});
       $("#"+obj+' .title span').css({'float':'right','cursor':'pointer'});
	   $("#"+obj+' .con').css({'float':'left','width':'100%'});
	   $("#"+obj+' .title span').bind('click',function() {
		    $("#"+obj).hide();  
	   });
   } else {
	   $("#"+obj).show();
   } 
}

function login(e) {
	createWindows('用户登陆','','240px','150px','logindiv',e);
	$("#logindiv .con").html('<div id="logindivcon" style="margin-top:10px;">手机号:<input type="text" name="usertel" id="lmobile"  style="width:150px" /><br/><br/>密&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="userpass" id="lpassword" style="width:150px" onKeyDown="if (event.keyCode==13) postLogin();" /><br/><br/><input type="button" name="remailxx" value="确定登陆" onclick="postLogin();" /><span id="lmsg"></span></div>');
}

function register(e) {
	createWindows('快速注册','','400px','180px','regdiv',e);
	$("#regdiv .con").html('<div id="regdivcon" style="margin-top:10px;">*手机号:<input type="text" name="usertel" id="mobile"  style="width:150px" /> <br/><br/>*昵&nbsp;&nbsp;&nbsp;&nbsp;称:<input type="text" name="username" id="username"  style="width:150px" /> (用户昵称注册后不可更改)<br /><br/>  *密&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="userpass" id="password" style="width:150px" onKeyDown="if (event.keyCode==13) postRegister();" /> (6-20位)<br/><br/>  <input type="button" name="remailxx" value="确定注册" onclick="postRegister();" /><span id="rmsg"></span></div>');
}

function postLogin() {
	var mobile = $('#lmobile').val();
	var password = $('#lpassword').val();
	if ('' == mobile || '' == password) {
		alert('请输入正确的手机号或者密码');
		return false;
	}
	$.ajax({url: loginUrl,type: 'POST',dataType: 'json',data: 'mobile='+mobile+'&password='+password,beforeSend: function() {$('#lmsg').html('<img src="/images/loding.gif" />数据验证中，请稍后.....');},success: function(msg) {alert(msg.msg);if (1==msg.status) {lrSuccess(msg.userName, msg.msgCount);$('#logindiv').hide();} else {$('#lmsg').html('');}}});
}

function postRegister() {
	var mobile = $('#mobile').val();
	var password = $('#password').val();
	var userName = $('#username').val();
	if ('' == mobile || '' == password) {
		alert('请输入正确的手机号或者密码');
		return false;
	}
	if ('' == userName) {
		alert('请输入要注册的用户名称');
		return false;
	}
	$.ajax({url: registerUrl,type: 'POST',dataType: 'json',data: 'mobile='+mobile+'&password='+password+'&username='+userName,beforeSend: function() {$('#rmsg').html('<img src="/images/loding.gif" />数据验证中，请稍后.....');},success: function(msg) {alert(msg.msg);if (1==msg.status) {lrSuccess(msg.userName, msg.msgCount);$('#regdiv').hide();} else {$('#rmsg').html('');}}});
}

function lrSuccess(userName, msgCount) {
	var html = '<a href="'+userHomeUrl+'">'+userName+'</a>';
	html += ' <a href="'+progressUrl+'">书架</a> 站内信('+msgCount+')';
	html += ' <a href="javascript:void(0)" id="logout">退出</a>';
	$('#suser').html(html);
}

// 替换特殊字符
function filterString(s) {
	s = s.replace(/\'/gm,"’");
	s = s.replace(/--/gm,"—");
	s = s.replace(/\*/gm,"＊");
	
	return s;
}

// 解决跟JQ的兼容问题-_-
function $d(id) {
	return document.getElementById(id);
}

function in_array(needle, haystack) {
	if(typeof needle == 'string' || typeof needle == 'number') {
		for(var i in haystack) {
			if(haystack[i] == needle) {
					return true;
			}
		}
	}
	return false;
}

function mb_strlen(str) {
	var len = 0;
	for(var i = 0; i < str.length; i++) {
		len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
	}
	return len;
}

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

function isUndefined(variable) {
	return typeof variable == 'undefined' ? true : false;
}

function strlen(str) {
	return (BROWSER.ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}

function in_array(needle, haystack) {
	if(typeof needle == 'string' || typeof needle == 'number') {
		for(var i in haystack) {
			if(haystack[i] == needle) {
					return true;
			}
		}
	}
	return false;
}

function getCookie(Name) {
	var search = Name + "=";
	if (document.cookie.length > 0) {
		offset = document.cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = document.cookie.indexOf(";", offset);
			if (end == -1) {
				end = document.cookie.length;
			}
			return unescape(document.cookie.substring(offset, end));
		} else {
			return ("");
		}
	} else {
		return ("");
	}
}

function setCookie(name, value, times) {  
	var today = new Date();
	var expires = new Date();
	expires.setTime(times);
	document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString()+";path=/";
}

function seditor_insertunit(key, text, textend, moveend, selappend) {
	var id = key + 'message';
	document.getElementById(id).focus();
	textend = isUndefined(textend) ? '' : textend;
	moveend = isUndefined(textend) ? 0 : moveend;
	selappend = isUndefined(selappend) ? 1 : selappend;
	startlen = strlen(text);
	endlen = strlen(textend);
	if(!isUndefined(document.getElementById(id).selectionStart)) {
		if(selappend) {
			var opn = document.getElementById(id).selectionStart + 0;
			if(textend != '') {
				text = text + document.getElementById(id).value.substring(document.getElementById(id).selectionStart, document.getElementById(id).selectionEnd) + textend;
			}
			document.getElementById(id).value = document.getElementById(id).value.substr(0, document.getElementById(id).selectionStart) + text + document.getElementById(id).value.substr(document.getElementById(id).selectionEnd);
			if(!moveend) {
				document.getElementById(id).selectionStart = opn + strlen(text) - endlen;
				document.getElementById(id).selectionEnd = opn + strlen(text) - endlen;
			}
		} else {
			text = text + textend;
			document.getElementById(id).value = document.getElementById(id).value.substr(0, document.getElementById(id).selectionStart) + text + document.getElementById(id).value.substr(document.getElementById(id).selectionEnd);
		}
	} else if(document.selection && document.selection.createRange) {
		var sel = document.selection.createRange();
		if(!sel.text.length && document.getElementById(id).sel) {
			sel = document.getElementById(id).sel;
			document.getElementById(id).sel = null;
		}
		if(selappend) {
			if(textend != '') {
				text = text + sel.text + textend;
			}
			sel.text = text.replace(/\r?\n/g, '\r\n');
			if(!moveend) {
				sel.moveStart('character', -endlen);
				sel.moveEnd('character', -endlen);
			}
			sel.select();
		} else {
			sel.text = text + textend;
		}
	} else {
		document.getElementById(id).value += text;
	}
	
	hideMenu();
}

function hideMenu(layer) {
	if(isUndefined(layer)) layer = 0;
	if(jsmenu['active'][layer]) {
		try {
			$(jsmenu['active'][layer].ctrlkey).className = ctrlobjclassName;
		} catch(e) {}
		clearTimeout(jsmenu['timer'][jsmenu['active'][layer].ctrlkey]);
		jsmenu['active'][layer].style.display = 'none';
		if(is_ie && is_ie < 7 && jsmenu['iframe'][layer]) {
			jsmenu['iframe'][layer].style.display = 'none';
		}
		jsmenu['active'][layer] = null;
	}
}

//取得外部class的属性值
function getCurrentStyle(o) {
	return o.currentStyle||document.defaultView.getComputedStyle(o,null);
}
var SetAllSelects = {
	Offset:function(e) {
		var t = e.offsetTop;
		var l = e.offsetLeft;
		var w = e.offsetWidth;
		var h = e.offsetHeight;
		while(e = e.offsetParent) { t += e.offsetTop; l += e.offsetLeft; }
		t = t - 2;
		return {top:t, left:l, width:w,	height:h};
	},
	setCreated:function(obj,status) { //设置属性
		obj.setAttribute("childCreated",status);
	},
	getCreated:function(obj) { //获取属性
		if (obj.getAttribute) // 解决 obj.getAttribute方法不存在的BUG
		{
			var status = obj.getAttribute("childCreated");
			if(status == null) { status = ""; }
			return status;
		}
		return "";
	},
	setSelectStyle:function(obj,idnum,showHeight) {
		if(obj.id == null || obj.id == "") { obj.id = "selectID_"+idnum; }
		var offset = this.Offset(obj);
		obj.style.visibility = "hidden";
		var mainDiv = document.createElement("div");
		var iDiv = document.createElement("div");
		var js_select_;
		var _this = this;
		iDiv.className = "iDiv";
		iDiv.id = js_select_+obj.id;
		iDiv.style.width = offset.width + "px";
		iDiv.style.top = offset.top + "px";
		iDiv.style.left = offset.left + "px";
		this.setCreated(iDiv,"");
		mainDiv.appendChild(iDiv);
		var tValue = obj.options[obj.selectedIndex].innerHTML;
		iDiv.innerHTML = tValue;
		iDiv.onmouseover = function() { iDiv.className = "iDiv iDiv_over"; }
		iDiv.onmouseout = function() { iDiv.className = "iDiv iDiv_out"; }
		iDiv.onclick = function() {
			var created = _this.getCreated(this);
			if (created != "") {
				if (created == "open") {
					this.nextSibling.style.display = "none";
					_this.setCreated(this,"close");
				} else {
					_this.setCreated(this,"open");
					var arrLiObj = this.nextSibling.getElementsByTagName("li");
					var selOjbIndex = 0;
					for(var i=0;i<arrLiObj.length;i++) {
						var status = arrLiObj[i].getAttribute("liSelected");
						if(status == null) { status = ""; }
						if(status == "selected") { selOjbIndex = i; break; }
					}
					arrLiObj[selOjbIndex].style.background = "#fff";
					arrLiObj[selOjbIndex].style.color = "#000";
					this.nextSibling.style.display = "block";
				}
			} else {
				_this.setCreated(this,"open");
				var cDiv = document.createElement("div");
				cDiv.className = "cDiv";
				cDiv.style.width = offset.width + "px";
				cDiv.style.height = obj.options.length * 20 + "px";
				if(parseInt(cDiv.style.height)>showHeight) {
					cDiv.style.height = showHeight + "px";
				}
				cDiv.style.top = (offset.top+parseInt(getCurrentStyle(this).height)+1) + "px";
				cDiv.style.left = offset.left + "px";
				cDiv.onselectstart = function() {return false;};
				var uUl = document.createElement("ul");
				cDiv.appendChild(uUl);
				mainDiv.appendChild(cDiv);
				for (var i=0;i<obj.options.length;i++) {
					var lLi = document.createElement("li");
					lLi.id = obj.options[i].value;
					lLi.innerHTML = obj.options[i].innerHTML;
					lLi.sValue = obj.options[i].value;
					uUl.appendChild(lLi);
				}
				var liObj = uUl.getElementsByTagName("li");
				if(liObj.length>0) {
					for (var j=0;j<obj.options.length;j++) {
						liObj[j].onmouseover = function() {
							var arrLiObj = this.parentNode.getElementsByTagName("li");
							for(var i=0;i<arrLiObj.length;i++) {
								var status = "";
								var _background = "#ccc";
								var _color = "#fff";
								if(arrLiObj[i] != this) {
									_background = "#fff";
									_color = "#000";
									status = "selected";
								}
								arrLiObj[i].style.background = _background;
								arrLiObj[i].style.color = _color;
								arrLiObj[i].setAttribute("liSelected",status);
							}
						}
						liObj[j].onclick = function() {
							obj.options.length = 0;
							obj.options[0] = new Option(this.innerHTML,this.sValue);
							this.parentNode.parentNode.style.display = "none";
							_this.setCreated(this.parentNode.parentNode.previousSibling,"close");
							iDiv.innerHTML = this.innerHTML;
						};
						liObj[0].style.background = "#ccc";
						liObj[0].style.color = "#fff";
						liObj[0].setAttribute("liSelected","selected");
					}
				}
			}
		}
		document.body.appendChild(mainDiv);
	},
	setAllSelectStyle:function() {
		var s = document.getElementsByTagName("select");
		for (var i=0; i<s.length; i++) {
			if(s[i].className == "select") {
				this.setSelectStyle(s[i],i,200);
			}
		}
	}
}
document.onclick = function(e) {
	e = e || window.event;
	var target = e.target || event.srcElement;
	var s = document.getElementsByTagName("select");
	var js_select_;
	for (var i=0; i<s.length; i++) {
		if(s[i].className == "select") {
			var objdivtmp = $(js_select_+s[i].id);
			var created = SetAllSelects.getCreated(objdivtmp);
			if (created == "open") {
				if(target != objdivtmp) {
					objdivtmp.nextSibling.style.display = "none";
					SetAllSelects.setCreated(objdivtmp,"close");
				}
			}
		}
	}
}
window.onload = function() {
	SetAllSelects.setAllSelectStyle();
}
function searchTo() {
	var keyword = $('.inputout').val();
	if (keyword == '搜索很强大！强大的搜索！' || keyword == '') {
		alert('搜索很强大！强大的搜索！');
		return false;
	}
}


$(function() {
	$('.inputout').click(function() {
		$('.inputout').val('');
	});
	$('#logout').live('click', function(){
		var date = new Date();
        date.setTime(date.getTime() - 10000);
        document.cookie = 'iOrangeUser' + "=删除" + "; expires=" + date.toUTCString();
        //$('#suser').html('<a href="javascript:void(0);" onclick="login(event);">登陆</a> <a href="javascript:void(0);" onclick="register(event);">注册</a>');
		location.reload();
	});
	//设置首页
    $('#homepage').click(function() {
        if ($.browser.msie) {
            this.style.behavior = 'url(#default#homepage)';
            this.setHomePage(baseUrl);
        } else if ($.browser.mozilla) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
                var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
                prefs.setCharPref('browser.startup.homepage', baseUrl);
            } catch(e) {
                alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将[signed.applets.codebase_principal_support]设置为'true'");
            }
        }
    });
    //收藏本站
    $('#homemark').click(function() {
        var title = siteName;
        var url = baseUrl;
        // FF
        if(window.sidebar != null)
        {
            try
            {
                if(window.sidebar.addPanel != null)
                {
                    window.sidebar.addPanel(title, url, "");
                    return;
                }
            }
            catch(e)
            {
            }

            alert("请按Ctrl+D键收藏 !");
            return;
        }

        // IE
        if(window.external != null)
        {
            try
            {
                window.external.addFavorite(url, title);
                return;
            }
            catch(e){
            }

            try
            {
                window.external.addToFavoritesBar(url, title, "slice");
                return;
            }
            catch(e){
            }
        }

        alert("您的浏览器不支持此操作, 请使用浏览器的收藏夹进行添加 !");
        return;
    });
});