function UrlDecode(text)
{
	text = text.replace(/\\+/g, " ");
	return unescape(text);
}

function UrlEncode(text)
{
	return escape(text).replace(/\\+/g, "%2B").replace(/%20/g, "+");
}

function HtmlEncode(text)
{
	if (typeof(text) != "string")
		text = text.toString() ;

	text = text.replace(
		/&/g, "&amp;").replace(
		/"/g, "&quot;").replace(
		/</g, "&lt;").replace(
		/>/g, "&gt;") ;

	return text ;
}

function GetCookie(name)
{
	var array = document.cookie.split(";");
	for (var i=0; i < array.length; i++)
	{
		var kvp = array[i].split("=");
		
		var j = 0;
		for (; j < kvp[0].length; j++)
		{
			if (kvp[0].charAt(j) != ' ')
				break;
		}
		
		if (name == kvp[0].substr(j))
			return unescape(kvp[1]);
	}
	return "";
}

function SetCookie(name, value, expireMinutes, path)
{
	if (arguments.length == "4")
		path = ";path=" + arguments[3];
		
	var expireDate = new Date();
	expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
	
	document.cookie = name + "=" + escape(value) + ";expires=" + expireDate.toUTCString() + path;
}

function GetEvent()
{
	if (navigator.product != "Gecko")
		return window.event;
		
	func = GetEvent.caller;
	while (func != null)
	{
		var arg0 = func.arguments[0];
		if(arg0)
		{
			if ((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof(arg0) == "object" && arg0.preventDefault && arg0.stopPropagation))
			{
				return arg0;
			}
		}
		func=func.caller;
	}
	return null;
}

function SetHome()
{
	var url = window.location;
		
	if (document.all)
	{
        document.body.style.behavior = "url(#default#homepage)";
		if (!document.body.isHomePage(url))
			document.body.setHomePage(url);
	}
	else if (window.sidebar)
	{
        if(window.netscape)
		{
            try
			{
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
			catch (e)
			{
                alert( "该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 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);
    }

    return false;	
}

function AddFavorite()
{
	var title = document.title
	var url = document.location.href
	if (window.sidebar)
	{
		window.sidebar.addPanel(title, url, "");
	}
	else if (window.opera && window.print)
	{
		var mbm = document.createElement("A");
		mbm.setAttribute("rel", "sidebar");
		mbm.setAttribute("href", url);
		mbm.setAttribute("title", title);
		mbm.click();
	}
	else if (document.all)
	{
		window.external.AddFavorite( url, title);
	}

    return false;
}

function CopyToClipboard(txt)
{ 
	if(window.clipboardData)  
	{ 
		window.clipboardData.clearData(); 
		window.clipboardData.setData("Text", txt); 
	} 
	else if(navigator.userAgent.indexOf("Opera") != -1)  
	{
		window.location = txt; 
	}  
	else if (window.netscape)  
	{
		try  
		{ 
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
		}  
		catch (e)  
		{ 
			alert("您的firefox安全限制限制您进行剪贴板操作，请在地址栏中输入“about:config”将“signed.applets.codebase_principal_support”设置为“true”之后重试"); 
			return; 
		} 
		var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard); 
		if (!clip) 
		  return; 
		var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable); 
		if (!trans) 
		  return; 
		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 = txt; 
		str.data = copytext; 
		trans.setTransferData("text/unicode",str,copytext.length*2); 
		var clipid = Components.interfaces.nsIClipboard; 
		if (!clip) 
		  return; 
		clip.setData(trans,null,clipid.kGlobalClipboard); 
	} 
}

function FormatDate(date, format)   
{
	if (format == null)
		format = "YYYY-MM-DD hh:mm:ss";
	
	var year = date.getFullYear().toString();
	format = format.replace(/YYYY/g, year);
	format = format.replace(/YY/g, year.substr(2));
	
	var month = (date.getMonth()+1).toString();
	format = format.replace(/MM/g, month.length == 1 ? "0" + month : month);
	format = format.replace(/M/g, month);
	
	var day = date.getDate().toString();
	format = format.replace(/DD/g, day.length == 1 ? "0" + day : day);
	format = format.replace(/D/g, day);
	
	var hour = date.getHours().toString();
	format = format.replace(/hh/g, hour.length == 1 ? "0" + hour : hour);
	format = format.replace(/h/g, hour);
	
	var minute = date.getMinutes().toString();
	format = format.replace(/mm/g, minute.length == 1 ? "0" + minute : minute);
	format = format.replace(/m/g, minute);
	
	var second = date.getSeconds().toString();
	format = format.replace(/ss/g, second.length == 1 ? "0" + second : second);
	format = format.replace(/s/g, second);
	
	var ms = date.getMilliseconds().toString();
	format = format.replace(/SSS/g, ms.length == 1 ? "00" + ms : (ms.length == 2 ? "0" + ms : ms));
	format = format.replace(/SS/g, ms.length == 1 ? "0" + ms : ms);
	format = format.replace(/S/g, ms);

	return format;
}

function Alert(message, callback, scope)
{
	var dialog = $("#AlertDialog");
    if (dialog.length == 0)
	{ 
        $("body").append("<div id=\"AlertDialog\"></div>");
		dialog = $("#AlertDialog");
        dialog.dialog({ 
            autoOpen:false, 
            title:"Alert Dialog", 
            modal:true,
            resizable:false, 
            overlay:{opacity:0.5,background:"black"}, 
            buttons:{"O K":function(){$(this).dialog("close");}},
			close:function()
			{
				if ($(this).data("Callback") != null)
				{
					if ($(this).data("Scope") != null)
						$(this).data("Callback").call($(this).data("Scope"));
					else
						$(this).data("Callback")();
				}
			}
        }); 
    } 
    
	if (callback != null)
		dialog.data("Callback", callback);
	if (scope != null)
		dialog.data("Scope", scope);
    dialog.html(message); 
    dialog.dialog("open");
}

function Confirm(message, callback, scope)
{
	var dialog = $("#ConfirmDialog");
    if (dialog.length == 0)
	{ 
        $("body").append("<div id=\"ConfirmDialog\"></div>");
		dialog = $("#ConfirmDialog");
        dialog.dialog({ 
            autoOpen:false, 
            title:"Confirm Dialog", 
            modal:true,
            resizable:false, 
            overlay:{opacity:0.5,background:"black"}, 
            buttons:{
					"O K":function(){$(this).data("ReturnValue", true);$(this).dialog("close");}, 
	                "Cancel":function(){$(this).dialog("close");} 
  			        },
			close:function()
			{
				if ($(this).data("Callback") != null)
				{
					if ($(this).data("Scope") != null)
						$(this).data("Callback").call($(this).data("Scope"), $(this).data("ReturnValue"));
					else
						$(this).data("Callback")($(this).data("ReturnValue"));
				}
			}
        }); 
    } 
    
	if (callback != null)
		dialog.data("Callback", callback);
	else
		dialog.removeData("Callback");
	if (scope != null)
		dialog.data("Scope", scope);
	else
		dialog.removeData("Scope");
	dialog.data("ReturnValue", false);
    dialog.html(message); 
    dialog.dialog("open");
}

function Prompt(message,defaultValue,callback, scope)
{
	var dialog = $("#PromptDialog");
    if (dialog.length == 0)
	{ 
        $("body").append("<div id=\"PromptDialog\"><p id=\"PromptDialogMessage\" ></p><input type='text' name='PromptValue' style='width:400px'/></div>");
		dialog = $("#PromptDialog");
        dialog.dialog({ 
            autoOpen:false, 
            title:"Prompt Dialog", 
            modal:true,
			width:450,
            resizable:false, 
			stack:true,
            overlay:{opacity:0.5,background:"black"}, 
            buttons:{
					"O K":function(){$("#PromptDialog").data("ReturnValue", $("[name=PromptValue]").val());$(this).dialog("close");}, 
	                "Cancel":function(){$(this).dialog("close");} 
  			        },
			close:function()
			{
				if ($(this).data("Callback") != null)
				{
					if ($(this).data("Scope") != null)
						$(this).data("Callback").call($(this).data("Scope"), $(this).data("ReturnValue"));
					else
						$(this).data("Callback")($(this).data("ReturnValue"));
				}
			}
        }); 
    } 
    $("#PromptDialogMessage").html(message);
	$("[name=PromptValue]").val(defaultValue);
	
	if (callback != null)
		dialog.data("Callback", callback);
	else
		dialog.removeData("Callback");
	if (scope != null)
		dialog.data("Scope", scope);
	else
		dialog.removeData("Scope");
	dialog.data("ReturnValue", null);
    dialog.dialog("open");
}

function SetStatusMessage(message, pos)
{
	var status = $("#StatusDialog");
    if (status.length == 0)
	{
        $("body").append("<div id=\"StatusDialog\"></div>");
		status = $("#StatusDialog");
	}
	
	if (message == null || message == "")
	{
		status.hide();
		return;
	}
	
	status.css("position", "absolute");
	status.html(message);
	
	function SetPosition()
	{
		if (status.css("display") == "none")
			return;
			
		var width = status.width();
		var height = status.height();
		var paddingTop = parseInt(status.css("padding-top").replace(/\w*/g, ""));
		if (isNaN(paddingTop))
			paddingTop = 0;
		var paddingLeft = parseInt(status.css("padding-left").replace(/\w*/g, ""));
		if (isNaN(paddingLeft))
			paddingLeft = 0;
		var paddingBottom = parseInt(status.css("padding-bottom").replace(/\w*/g, ""));
		if (isNaN(paddingBottom))
			paddingBottom = 0;
		var paddingRight = parseInt(status.css("padding-right").replace(/\w*/g, ""));
		if (isNaN(paddingRight))
			paddingRight = 0;
		var borderTop = parseInt(status.css("border-top-width").replace(/\w*/g, ""));
		if (isNaN(borderTop))
			borderTop = 0;
		var borderLeft = parseInt(status.css("border-left-width").replace(/\w*/g, ""));
		if (isNaN(borderLeft))
			borderLeft = 0;
		var borderBottom = parseInt(status.css("border-bottom-width").replace(/\w*/g, ""));
		if (isNaN(borderBottom))
			borderBottom = 0;
		var borderRight = parseInt(status.css("border-right-width").replace(/\w*/g, ""));
		if (isNaN(borderRight))
			borderRight = 0;
		var marginTop = parseInt(status.css("margin-top").replace(/\w*/g, ""));
		if (isNaN(marginTop))
			marginTop = 0;
		var marginLeft = parseInt(status.css("margin-left").replace(/\w*/g, ""));
		if (isNaN(marginLeft))
			marginLeft = 0;
		var marginBottom = parseInt(status.css("margin-bottom").replace(/\w*/g, ""));
		if (isNaN(marginBottom))
			marginBottom = 0;
		var marginRight = parseInt(status.css("margin-right").replace(/\w*/g, ""));
		if (isNaN(marginRight))
			marginRight = 0;

		var scrollLeft = $("html").scrollLeft();
		var scrollTop = $("html").scrollTop();
		
		switch (pos)
		{
			case "TopLeft":
				status.css("top", scrollTop);
				status.css("left", scrollLeft);
				break;
			case "TopCenter":
				status.css("top", scrollTop);
				status.css("left", (window.screen.availWidth + scrollTop - width - paddingLeft - paddingRight - borderLeft - borderRight - marginLeft - marginRight) / 2);
				break;
			case "TopRight":
				status.css("top", scrollTop);
				status.css("left", window.screen.availWidth + scrollLeft - width - paddingLeft - paddingRight - borderLeft - borderRight - marginLeft - marginRight);
				break;
			case "BottomLeft":
				status.css("top", window.screen.availHeight + scrollTop - height - paddingTop - paddingBottom - borderTop - borderBottom - marginTop - marginBottom);
				status.css("left", scrollLeft);
				break;
			case "BottomCenter":
				status.css("top", window.screen.availHeight + scrollTop - height - paddingTop - paddingBottom - borderTop - borderBottom - marginTop - marginBottom);
				status.css("left", (window.screen.availWidth + scrollLeft - width - paddingLeft - paddingRight - borderLeft - borderRight - marginLeft - marginRight) / 2);
				break;
			case "BottomRight":
				status.css("top", window.screen.availHeight + scrollTop - height - paddingTop - paddingBottom - borderTop - borderBottom - marginTop - marginBottom);
				status.css("left", window.screen.availWidth + scrollLeft - width - paddingLeft - paddingRight - borderLeft - borderRight - marginLeft - marginRight);
				break;
			case "Center":
			default:
				status.css("top", scrollTop + (window.screen.availHeight - height - borderTop - borderBottom) / 2);
				status.css("left", scrollLeft + (window.screen.availWidth - width - borderLeft - borderRight) / 2);
				break;
		}
	}
	
	status.show();
	SetPosition();
	
	$(window).scroll(SetPosition);
}

function ShowLoginDialog(callback, scope)
{
	var dialog = $("#LoginDialog");
    if (dialog.length == 0)
	{
		var title = typeof(_lang_login_dialog_title) == "undefined" ? "Login" : _lang_login_dialog_title;
		var name = typeof(_lang_login_dialog_name) == "undefined" ? "Name" : _lang_login_dialog_name;
		var password = typeof(_lang_login_dialog_password) == "undefined" ? "Password" : _lang_login_dialog_password;
		
        $("body").append("<div id=\"LoginDialog\"><table><tr><th>" + name + "：<th><td><input type='text' /></td></tr><tr><th>" + password + "：<th><td><input type='password' /></td></tr></table></div>");
		dialog = $("#LoginDialog");
        dialog.dialog({ 
            autoOpen:false, 
            title:title, 
            modal:true,
            resizable:false, 
            overlay:{opacity:0.5,background:"black"}, 
            buttons:{"Login":function()
			{
				var inputs = this.getElementsByTagName("INPUT");
				if ($.trim(inputs[0].value) == "")
				{
					Alert(_lang_login_dialog_name_incorrect, function(){$(this).dialog("close");$(this).dialog("open");inputs[0].select();}, this);
					return;
				}
				if ($.trim(inputs[1].value) == "")
				{
					Alert(_lang_login_dialog_password_incorrect, function(){$(this).dialog("close");$(this).dialog("open");inputs[0].select();}, this);
					return;
				}
				
				if ($(this).data("Callback") != null)
				{
					if ($(this).data("Scope") != null)
						$(this).data("Callback").call($(this).data("Scope"), inputs[0].value, inputs[1].value);
					else
						$(this).data("Callback")(inputs[0].value, inputs[1].value);
				}
				
				$(this).dialog("close");
			}}
        }); 
    } 
    
	if (callback != null)
		dialog.data("Callback", callback);
	if (scope != null)
		dialog.data("Scope", scope);
    dialog.dialog("open");
}

function SetTip(path, className)
{
	var tip = $("#Tip");
    if (tip.length == 0)
	{
		var align = "left";
		if ($("body").css("direction") == "rtl")
			align = "right";
		
        $("body").append("<div id=\"Tip\"" + (className == null ? " style=\"display:none;position:absolute;padding:2px;text-align:" + align + ";line-height:150%;border:1px solid #666;background:#FF0\"" : " style=\"display:none;position:absolute\" class=\"" + className + "\"") + "></div>");
		tip = $("#Tip");
	}
	
	$((path == null ? "" : path + " ") + "a").each(function()
	{
		var me = $(this);

		if (me.attr("title") == "")
			return;
		
		me.attr("tip", me.attr("title"));
		me.removeAttr("title");
		
		$(this).mousemove(function(e)
		{
			tip.html($(this).attr("tip"));
			tip.css("top", e.pageY + 18);
			tip.css("left", e.pageX - 18);
			tip.show();
		});
		
		$(this).mouseout(function()
		{
			tip.hide();
		});
	});
}
