function LoadCommonDict(callback)
{
	lang = "CHS";
	if (typeof(_lang) != "undefined")
		lang = _lang;
	if ($("body").css("direction") == "ltr" && (lang == "UYG" || lang == "KZG" || lang == "KGA"))
		lang = "CHS";

	$.ajax(
	{
		url : $("body").data("CommonPath") + "dictionary/" + lang + ".xml",
		type : "GET",
		success : function(data)
		{
			$("body").data("CommonDict", $(data));
			if (callback != null)
				callback();
		}
	});
}

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) && kvp.length == 2)
			return unescape(kvp[1]);
	}
	return '';
}

function SetCookie(name, value, expireMinutes, path)
{
	if (path)
		path = ';path=' + path;
	else
		path = '';
		
	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" );
            }
        }
		
		try
		{
			var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
			prefs.setCharPref('browser.startup.homepage',url);
		}
		catch (e)
		{
		}
    }

    return false;	
}

function AddFavorite()
{
	try
	{
		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);
		}
	}
	catch (e)
	{
		//alert(e.message);
	}

    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, params)
{
	if ($("body").data("CommonDict") == null)
	{
		LoadCommonDict(function(){Alert(message, callback, scope, params);});
		return;
	}

	var dlg = $("#AlertDialog");
    if (dlg.length == 0)
	{ 
        $("body").append("<div id=\"AlertDialog\"></div>");
		dlg = $("#AlertDialog");
        dlg.dialog({ 
            autoOpen:false,
            modal:true,
            resizable:false, 
            overlay:{opacity:0.5,background:"black"}, 
			close:function()
			{
				if ($(this).data("Callback") != null)
				{
					if ($(this).data("Scope") != null)
						$(this).data("Callback").call($(this).data("Scope"));
					else
						$(this).data("Callback")();
				}
			}
        });
    }
	
	dlg.dialog("option", "title", $("body").data("CommonDict").find("Item[Name=lang_alert_title]").text());
	
	if (params != null)
	{
		var okFn = function(){dlg.dialog("close");SetCookie("AlertResult", "", 0, "/");};
		var clearFn = function(){params.Clear == null ? $("form")[0].reset() : params.Clear.reset();dlg.dialog("close");SetCookie("AlertResult", "Clear", 10*360*24*60, "/");};

		var edit = params.Edit == null ? "edit.aspx" : params.Edit;
		edit += "?ID=" + (params.EditID == null ? _id : params.EditID);
		if (typeof(_lang) != "undefined")
			edit += "&Lang=" + _lang;
		if (params.EditParams != null)
			edit += "&" + params.EditParams;
		var editFn = function(){window.location = edit;SetCookie("AlertResult", "Edit", 10*360*24*60, "/");};

		var list = params.List == null ? "list.aspx" : params.List;
		if (typeof(_lang) != "undefined")
			list += "?Lang=" + _lang;
		if (params.ListParams != null)
			list += (list.indexOf("?") != -1 ? "&" : "?") + params.ListParams;
		var listFn = function(){window.location = list;SetCookie("AlertResult", "List", 10*360*24*60, "/");};

		var isEdit = window.location.pathname.indexOf("edit.aspx") != -1;
		var cookie = GetCookie("AlertResult");
		if (cookie == "Edit" && isEdit)
			cookie = "";

		var buttons = [];
		buttons.push({text:"O K",click:cookie == "Clear" ? clearFn : (cookie == "Edit" ? editFn : (cookie == "List" ? listFn : okFn))});
		if (cookie != "")
			buttons.push({text:$("body").data("CommonDict").find("Item[Name=lang_alert_button_this]").text(),click:okFn});
		if (cookie != "Clear" && !isEdit)
			buttons.push({text:$("body").data("CommonDict").find("Item[Name=lang_alert_button_clear]").text(),click:clearFn});
		if (cookie != "Edit" && !isEdit)
			buttons.push({text:$("body").data("CommonDict").find("Item[Name=lang_alert_button_edit]").text(),click:editFn});
		if (cookie != "List")
			buttons.push({text:$("body").data("CommonDict").find("Item[Name=lang_alert_button_list]").text(),click:listFn});

		dlg.dialog("option", "buttons", buttons);
	}
	else
	{
		dlg.dialog("option", "buttons", [{text:"O K",click:function(){dlg.dialog("close");}}]);
		dlg.bind("dialogclose", 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)
			dlg.data("Callback", callback);
		if (scope != null)
			dlg.data("Scope", scope);
	}

	dlg.html(message);
    dlg.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).width() + scrollTop - width - paddingLeft - paddingRight - borderLeft - borderRight - marginLeft - marginRight) / 2);
				break;
			case "TopRight":
				status.css("top", scrollTop);
				status.css("left", $(window).width() + scrollLeft - width - paddingLeft - paddingRight - borderLeft - borderRight - marginLeft - marginRight);
				break;
			case "BottomLeft":
				status.css("top", $(window).height() + scrollTop - height - paddingTop - paddingBottom - borderTop - borderBottom - marginTop - marginBottom);
				status.css("left", scrollLeft);
				break;
			case "BottomCenter":
				status.css("top", $(window).height() + scrollTop - height - paddingTop - paddingBottom - borderTop - borderBottom - marginTop - marginBottom);
				status.css("left", ($(window).width() + scrollLeft - width - paddingLeft - paddingRight - borderLeft - borderRight - marginLeft - marginRight) / 2);
				break;
			case "BottomRight":
				status.css("top", $(window).height() + scrollTop - height - paddingTop - paddingBottom - borderTop - borderBottom - marginTop - marginBottom);
				status.css("left", $(window).width() + scrollLeft - width - paddingLeft - paddingRight - borderLeft - borderRight - marginLeft - marginRight);
				break;
			case "Center":
			default:
				status.css("top", scrollTop + ($(window).height() - height - borderTop - borderBottom) / 2);
				status.css("left", scrollLeft + ($(window).width() - 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();
		});
	});
}

function InitUtility()
{
	var js = document.getElementsByTagName("script");
	$("body").data("CommonPath", js[js.length-1].src.substring(0,js[js.length-1].src.lastIndexOf("/")+1));
}

InitUtility();
