var appPrefix = "";

var scripIdPrefix = "scrip";	//字条ID的前缀

/******************************************* function.bind()函数 ******************************************/
Function.prototype.bind = function(obj) {
	var method = this,
	temp = function() {
		return method.apply(obj, arguments);
	};
	return temp;
}
 
/******************************************* 通用Ajax函数 ******************************************/
function Ajax() {
	
	var xmlHttpReq = null;
	if (window.XMLHttpRequest) {
		xmlHttpReq = new XMLHttpRequest();
	} else {
		if (window.ActiveXObject) {
			xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	
	var handler = null;
	
	this.invoke = function (url, mode, synchro, _handler) {
		handler = _handler;
		xmlHttpReq.open(mode, url, synchro);
		xmlHttpReq.onreadystatechange = this.callback;
		xmlHttpReq.send(null);
	};
	
	this.callback = function () {
		if (xmlHttpReq.readyState == 4) {
			if (xmlHttpReq.status == 200) {
				handler(xmlHttpReq.responseText);
			} else {
				//alert("There was a problem retrieving the XML data:\n" + xmlHttpReq.statusText);
				alert("Please refresh");
			}
		}
	};
}

/******************************************* Cookie操作 ******************************************/
// utility function to retrieve an expiration data in proper format;
function getExpDate(days, hours, minutes)
{
    var expDate = new Date();
    if(typeof(days) == "number" && typeof(hours) == "number" && typeof(hours) == "number")
    {
        expDate.setDate(expDate.getDate() + parseInt(days));
        expDate.setHours(expDate.getHours() + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
        return expDate.toGMTString();
    }
}

//utility function called by getCookie()
function getCookieVal(offset)
{
    var endstr = document.cookie.indexOf(";", offset);
    if(endstr == -1)
    {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}

// primary function to retrieve cookie by name
function getCookie(name)
{
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while(i < clen)
    {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
        {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if(i == 0) break;
    }
    return;
}

// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
/*
var time = new date(); 
time.setTime(time.getTime + 24 * 3600 * 1000); //过期时间为24小时. 
document.cookie = "sName = " + escape(sValue) + "; expires= " + time.toGMTString();
*/

// remove the cookie by setting ancient expiration date
function deleteCookie(name,path,domain) 
{
    if(getCookie(name))
    {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/******************************************* 通用事件函数 ******************************************/
var Event = new Object();
Event.history = new Array();
Event.apply = function(handler, args){
	return function(evt){
		Event.event = evt ? evt : window.event;
		handler(args);
	}
}
Event.observe = function(target, eventType, handler){
	var args = [];
	for ( var i = 3; i < arguments.length; i++ ) {
		args.push(arguments[i]);
	}
	if(target.attachEvent){
		target.attachEvent("on"+eventType, Event.apply(handler, args));
	}
	else if(target.addEventListener){
		target.addEventListener(eventType, Event.apply(handler, args), false);
	}
}
Event.disObserve = function(target, eventType, handler){
	if(target.detachEvent){
        target.detachEvent("on"+eventType, handler); 
    }
    else if(target.removeEventListener){ 
        target.removeEventListener("on"+eventType, handler, true); 
    }	
}

var Position = function(){
	this.x;
	this.y;
	this.z;
}
function toInt(str){
	var ret=0;
	var mid_num;
	for(var i=0;i<str.length;i++){
		mid_num=str.charAt(i);
		if(mid_num<'0' || mid_num>'9')
		{
			return -1;
		}
		ret=ret*10+(mid_num-'0');
	}
	return ret;
}

function searchMsg()
{
	var noStr = document.getElementById("scripNo").value;
	var no = parseInt(noStr);
	if(isNaN(no)  || toInt(noStr)== -1){
		alert("纸条编号必须为数字");
		return false;
	}else if(no < 1){
		alert("纸条编号必须为正整数");
		return false;
	}else{
		if(window.location.href.indexOf("index") == -1){
			return true;
		}		
		searchScrip(no);
		return false;
	}
}

function setBodyWidth(){
	//alert(document.body.clientWidth);
	var width = document.body.clientWidth <= 1000 ? "1000px": document.body.clientWidth;
	document.getElementById("wrapper").style.width = width;
	//document.getElementById("wrapper").style = width;
	//document.body.setAttribute("clientWidth", width);
}	

/******************************************* logon ******************************************/

var loginFrameIndex = 1000000;
function logout(afterLogoutURL){
	if(!afterLogoutURL || afterLogoutURL == "undefined"){
		afterLogoutURL = "";
	}
	var ajax = new Ajax();
	ajax.invoke(
		appPrefix+"/LogoutServlet?afterLogoutURL="+afterLogoutURL+"&timemark="+Math.random(),
		"GET",
		true,
		handleLogout
	);
}
function handleLogout(response){
	var jsonContent = eval("(" + response + ")");
	if(jsonContent.isLogoutOk){
		var afterLogoutURL = jsonContent.afterLogoutURL;
		if(afterLogoutURL && afterLogoutURL.length != 0 && jsonContent.afterLogoutURL != "null"){
			window.location.href = appPrefix + jsonContent.afterLogoutURL;
		}else{
			if(window.location.href.indexOf("lovewall/index.jsp") == -1){
				window.location.href = appPrefix + "/lovewall/index.jsp"
			}else{
				setHeader("false", "");
				if(typeof logoutOK != "undefined"){
					logoutOK();
				}
			}
		}
	}
}
function getTopWindow(){
	var topWindow = window;
	while(topWindow != topWindow.parent){
		topWindow = window.parent;
	}
	return topWindow;
}
function showLogonFrame(afterLoginURL){	
	var topWindow = getTopWindow();
	var doc = topWindow.document;

	var logonDivWidth = 319;
	var logonDivHeight = 248;
	
	showCover(doc,loginFrameIndex);
	
	var logonDiv = doc.createElement("div");
	logonDiv.setAttribute("id", "logonDiv");
	logonDiv.style.cssText = "position:absolute;width:"+logonDivWidth+"px;height:"+logonDivHeight+"px; z-index:"+(loginFrameIndex+1)+";";

	if(afterLoginURL && afterLoginURL != "undefined"){
		logonDiv.innerHTML = "<iframe id='logifr' src='"+appPrefix+"/home/log_ind.jsp?bu="+appPrefix+"/home/log_ok.jsp?afterLoginURL="+afterLoginURL+"?from=bulletin#pay' name='login' frameborder='0' width='"+logonDivWidth+"' height='"+logonDivHeight+"' marginheight='0' marginwidth='0' scrolling='no'></iframe>";
	}else{
		logonDiv.innerHTML = "<iframe id='logifr' src='"+appPrefix+"/home/log_ind.jsp?bu="+appPrefix+"/home/log_ok.jsp' name='login' frameborder='0' width='"+logonDivWidth+"' height='"+logonDivHeight+"' marginheight='0' marginwidth='0' scrolling='no'></iframe>";
	}
	doc.body.appendChild(logonDiv);	
	
	setLoginFrame();
	
	Event.observe(topWindow, "resize", onWinResize);
}
function onWinResize(){
	setLoginFrame();
	setCover();
}
function setLoginFrame(){
	var clientWidth = document.documentElement.clientWidth != 0 ? Math.min(document.documentElement.clientWidth, document.body.clientWidth) : document.body.clientWidth;
	var clientHeight = document.documentElement.clientHeight != 0 ? Math.min(document.documentElement.clientHeight, document.body.clientHeight) : document.body.clientHeight;
		
	var scrollLeft =  document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
	var scrollTop =  document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
	
	var target = document.getElementById("logonDiv");
	if(!target) return;
	var targetWidth = target.style.width.replace("px","");
	var targetHeight = target.style.height.replace("px","");
	target.style.left = ((clientWidth-targetWidth)/2+scrollLeft)+"px";
	target.style.top = ((clientHeight-targetHeight)/2+scrollTop)+"px";
}
function setCover(){	
	var windowWidth = document.body.scrollWidth ;
	var windowHeight = document.body.scrollHeight ;
	var cover = document.getElementById("coverDiv");
	if(!cover) return;
	cover.style.width = windowWidth;
	cover.style.height = windowHeight;
	var coverFrame = document.getElementById("coverFrame");
	coverFrame.style.width = windowWidth+"px";
	coverFrame.style.height = windowHeight+"px";
}
function showCover(doc,zIndex){
	var coverDiv = doc.createElement("div");
	coverDiv.setAttribute("id", "coverDiv");
	var windowWidth = doc.body.scrollWidth ;
	var windowHeight = doc.body.scrollHeight ;
	coverDiv.style.cssText = "position:absolute;background-color:#000;filter:alpha(Opacity=35);opacity: 0.35; left:0; top:0; width:"+windowWidth+"px; height:"+windowHeight+"px; z-index:"+zIndex+";";	
	coverDiv.innerHTML = "<iframe id='coverFrame' src='' scrolling='no' frameborder='0' style='z-index:-1;position:absolute;background-color:#000;filter:alpha(Opacity=35);opacity: 0.35; top:0px; left:0px;width:"+windowWidth+"px;height:"+windowHeight+";'></iframe>";
	doc.body.appendChild(coverDiv);
}

function closeCover(doc){
	var coverDiv = doc.getElementById("coverDiv");
	coverDiv.parentNode.removeChild(coverDiv);
}

function closeLoginFrame(){
	var logonDiv = document.getElementById("logonDiv");
	var coverDiv = document.getElementById("coverDiv");
	logonDiv.parentNode.removeChild(logonDiv);
	coverDiv.parentNode.removeChild(coverDiv);
	
	var topWindow = getTopWindow();
	Event.disObserve(topWindow, "resize", onWinResize, "logonDiv");
}

function setHeader(isLogin, qqNick){
	var loginLi 		= document.getElementById("loginLi");
	var mainPageLink 	= document.getElementById("mainPageLink");
	var scripListLink 	= document.getElementById("scripListLink");
	var personCenterLink= document.getElementById("personCenterLink");
	var onlineHelp 		= document.getElementById("onlineHelp");
	if(loginLi && isLogin && isLogin == "true"){		
		loginLi.innerHTML = "欢迎"+qqNick+" <a href='javascript:logout();'>[退出]</a>";
		mainPageLink.setAttribute("href", appPrefix+"/index.jsp");
		scripListLink.setAttribute("href", appPrefix+"/list.jsp");
		personCenterLink.setAttribute("href", appPrefix+"/personal.jsp");
		onlineHelp.setAttribute("href", appPrefix+"/lovewall/help.jsp");
	}else{
		loginLi.innerHTML = "欢迎您 <a href='javascript:showLogonFrame();'>[登录]</a>";
		mainPageLink.setAttribute("href", appPrefix+"/index.jsp");
		scripListLink.setAttribute("href", appPrefix+"/list.jsp");
		personCenterLink.setAttribute("href", "javascript:showLogonFrame('/personal.jsp');");
		onlineHelp.setAttribute("href", appPrefix+"/lovewall/help.jsp");
	}
}
