var _pageNumber = 1;
var g_empty = "00000000-0000-0000-0000-000000000000";

function IsAllowedType(path, type)
{
	var dot = path.lastIndexOf(".");
	if (dot == -1)
		return !/^[A-Za-z]:\\/.test(path);
		
	var ext = path.substr(dot + 1).toLowerCase();
	var types = type.toLowerCase().split("|");
	for (var i = 0; i < types.length; i++)
	{
		if (types[i] == ext)
			return true;
	}
	
	return false;
}

function BuildAjaxPath()
{
	var customSearch = false;
	if (arguments.length > 0)
		customSearch = arguments[0];
	
	//对话框里调用此函数时，前面的斜杠丢了，所以在此人为地加上
	var pathName = window.location.pathname;
	if (pathName.indexOf("/") != 0)
		pathName = "/" + pathName;

	var index = window.location.href.indexOf("/ilghar.aspx?/");
	if (index != -1)
	{
		var host = "http://" + document.location.host;
		if (window.location.href.indexOf(host) != 0)
			host = "http://" + document.location.domain;
		var prefix = window.location.href.substr(host.length, 13);
		var path = window.location.search.substr(1);
		var query = "";
		index = path.indexOf("?");
		if (index == -1)
		{
			pathName = path;
		}
		else
		{
			pathName = path.substr(0, index);
			query = path.substr(index);
		}
		var slash = pathName.lastIndexOf("/");
		pathName = pathName.substr(0, slash + 1) + "ajax_" + pathName.substr(slash + 1);
		if (customSearch)
			return prefix + pathName;
		else
			return prefix + pathName + query;
	}
	else
	{
		var slash = pathName.lastIndexOf("/");
		return pathName.substr(0, slash + 1) + "ajax_" + pathName.substr(slash + 1) + (customSearch ? "" : window.location.search);
	}
}

function GetQSExcept()
{
	var result = "";

	var header = "";
	var href = window.location.href;
	var index = href.indexOf("/ilghar.aspx?/");
	if (index != -1)
	{
		index = href.indexOf("?", index + 13);
		if (index == -1)
			return "";

		header = href.substr(index + 1);
	}
	else
	{
		header = window.location.search.substr(1);
	}
	if( arguments.length < 1 )
		return header;
	
	var headerArray = header.split("&");
	for(var i = 0; i < headerArray.length; i++)
	{
		var isNext = false;
		for(var j = 0; j < arguments.length; j++)
		{
			if(headerArray[i].indexOf(arguments[j]) == 0)
			{
				isNext = true;
				break;
			}
		}
		
		if(isNext)continue;
		
		if(result == "")
			result = headerArray[i];
		else
			result += "&" + headerArray[i];
	}
	
	return result;
}

function Go(page)
{
	if (typeof(Search) == "function")
	{
		Search(page);
	}
	else
	{
		var qs = GetQSExcept("page");
		if (window.location.href.indexOf("/ilghar.aspx?/") != -1)
			window.location.href = window.location.href.substr(0, window.location.href.lastIndexOf("?")) + "?page=" + page + (qs == "" ? "" : "&" + qs);
		else
			window.location.href = "?page=" + page + (qs == "" ? "" : "&" + qs);
	}
}

function HandleFake404()
{
	//如果不是假404，则直接返回
	var index = window.location.href.indexOf("/ilghar.aspx?/");
	if (index == -1)
	{
		if (arguments.length == 2)
			return arguments[0];
		else
			return "";
	}
	
	var host = "http://" + document.location.host;
	var prefix = window.location.href.substr(host.length, 13);
	
	//如果有一个参数并且是字符串，把它转换并且返回
	if (arguments.length == 2 && arguments[1] == "url")
	{
		var href = arguments[0];
		href = href.replace(/&amp;/g, "&");
		if (href.indexOf("/") == 0)
		{
			return prefix + href;
		}
		else if (href.indexOf("..") == 0)
		{
			var a = window.location.search.substr(1);

			var slash = a.lastIndexOf("/");
			a = a.substr(0, slash + 1);

			while (href.indexOf("../") == 0)
			{
				slash = a.lastIndexOf("/", slash - 1);
				if (slash <= 0)
				{
					tags[i].href = prefix + "/" + href.replace(/\.\.\//g, "");
					return;
				}
				
				a = a.substr(0, slash + 1);
				href = href.substr(3);
			}
			
			return prefix + a + href;
		}
		else
		{
			var path = window.location.search.substr(1);
			var lastSlash = path.lastIndexOf("/");
			return prefix + path.substr(0, lastSlash + 1) + href;
		}
	}
	
	//如果有一个参数并且是对象，表示XmlHttp对象，转换responseText里面的链接
	if (arguments.length == 2 && arguments[1] == "text")
	{
		var text = arguments[0];
		var matches = text.match(/href=".*?"/g);
		if (matches != null)
		{
			var start = text.length - 1;
			for (var i = matches.length - 1; i >= 0; i--)
			{
				var newHref = "";
				var href = matches[i].substr(6, matches[i].length - 7);

				if (href.indexOf(host) == 0 && href.substr(host.length, 1) != ":")
					href = href.substr(host.length);
				
				if (href.indexOf("http://") == 0 || href.indexOf("javascript:") == 0 || href.indexOf(prefix) == 0)
					continue;
				
				if (href.indexOf("/") == 0)
				{
					newHref = prefix + href;
				}
				else if (href.indexOf("..") == 0)
				{
					var a = window.location.search.substr(1);
		
					var slash = a.lastIndexOf("/");
					a = a.substr(0, slash + 1);
		
					while (href.indexOf("../") == 0)
					{
						slash = a.lastIndexOf("/", slash - 1);
						if (slash <= 0)
						{
							newHref = prefix + "/" + href.replace(/\.\.\//g, "");
							break;
						}
						
						a = a.substr(0, slash + 1);
						href = href.substr(3);
					}
					
					if (newHref == "")
						newHref = prefix + a + href;
				}
				else
				{
					var path = window.location.search.substr(1);
					var lastSlash = path.lastIndexOf("/");
					newHref = prefix + path.substr(0, lastSlash + 1) + href;
				}
				
				start = text.lastIndexOf(matches[i], start);
				text = text.substr(0, start) + "href=\"" + newHref + "\"" + text.substr(start + matches[i].length);
			}
		}
		
		return text;
	}

	//如果没有参数，表示处理页面里的所有连接
	$("a").each(function()
	{
		var href = $(this).attr("href");
	
		if (href.indexOf(host) == 0 && href.substr(host.length, 1) != ":")
			href = href.substr(host.length);
		
		if (href.indexOf("http://") == 0 || href.indexOf("javascript:") == 0 || href.indexOf(prefix) == 0)
			return;
		
		href = href.replace(/&amp;/g, "&");
		if (href.indexOf("/") == 0)
		{
			href = prefix + href;
		}
		else if (href.indexOf("..") == 0)
		{
			var a = window.location.search.substr(1);

			var slash = a.lastIndexOf("/");
			a = a.substr(0, slash + 1);

			var isFind = false;
			while (href.indexOf("../") == 0)
			{
				slash = a.lastIndexOf("/", slash - 1);
				if (slash <= 0)
				{
					href = prefix + "/" + href.replace(/\.\.\//g, "");
					isFind = true;
					break;
				}
				
				a = a.substr(0, slash + 1);
				href = href.substr(3);
			}
			
			if (!isFind)
				href = prefix + a + href;
		}
		else
		{
			var path = window.location.search.substr(1);
			var lastSlash = path.lastIndexOf("/");
			href = prefix + path.substr(0, lastSlash + 1) + href;
		}
		
		$(this).attr("href", href);
	}
	);
}

//点对象
function Point(iX, iY)
{
	this.x = iX;
	this.y = iY;
}

//获得一个对象（一个Html元素对象或ID）左上角
function GetObjectXY( ob )
{
	var topLeft = new Point(0,0);
	topLeft.x	= ob.offsetLeft;
	topLeft.y	= ob.offsetTop;
	var parent	= ob.offsetParent;
	while (parent != null && parent.tagName.toUpperCase() != "BODY")
	{
		topLeft.x	+= parent.offsetLeft;
		topLeft.y	+= parent.offsetTop;
		parent = parent.offsetParent;
	}
	
	return topLeft;
}

///////////////////////////////////////////////
//START : 页面内容语言相关
function ShowLanguageMenu(ob)
{
	menu = document.getElementById("LanguageMenu");
	if (menu == null)
		return;
		
	var topLeft = GetObjectXY(ob);
	menu.style.left = topLeft.x + "px";
	menu.style.top = topLeft.y + ob.offsetHeight + "px";
	menu.style.display = "";
	menu.onmouseout = function(e)
	{
		HideLanguageMenu(e);
	}
}

function ContainsNS6(a, b)
{
	while (b.parentNode)
	{
		if ((b = b.parentNode) == a)
			return true;
	}
	return false;
}

function HideLanguageMenu(e)
{
	menu = document.getElementById("LanguageMenu");
	var browser = navigator.userAgent;
	if (browser.indexOf("Gecko") != -1)//FireFox
	{
		if (ContainsNS6(menu, e.relatedTarget))
			return;
	}
	else
	{
		if (menu.contains(event.toElement))
			return;
	}

	menu.style.display = "none";
}

function ChangeContentLang(langAb)
{
	var header = GetQSExcept("Lang", "page");
	var href = window.location.href;
	var index = href.indexOf("/ilghar.aspx?/");
	if (index != -1)
	{
		index = href.indexOf("?", index + 13);
		window.location.href = href.substr(0, index == -1 ? href.length : index) + "?Lang=" + langAb + (header == "" ? "" : "&" + header);
	}
	else
	{
		window.location.href = "?Lang=" + langAb + (header == "" ? "" : "&" + header);
	}
}
//END : 页面内容语言相关
////////////////////////////////////////////////

function BuildTreeOptions(xmlDoc, parentField, idField, nameField, selectControl)
{
	var _doc = xmlDoc;
	var _parentField = parentField;
	var _idField = idField;
	var _nameField = nameField;
	var _selectControl = selectControl;
	var _nodeList = new Array();
	
	this.Run = function(parentID, isParentLast, layer)
	{
		if (_doc.documentElement == null)
			return;

		var nodeList = new Array();
		var allChild = _doc.documentElement.childNodes;
		for (var i = 0; i < allChild.length; i++)
		{
			if (typeof (allChild[i].selectSingleNode) == "undefined")
				continue;
				
			if (allChild[i].selectSingleNode(_parentField).text == parentID)
				nodeList[nodeList.length] = allChild[i];
		}
		
		for (var i = 0; i < nodeList.length; i++)
		{
			var id = nodeList[i].selectSingleNode(_idField).text;
			var nameNode = nodeList[i].selectSingleNode(_nameField);
			var name = (nameNode == null) ? "" : nameNode.text;
	
			var indent = "";
			for (var j = 0; layer > 0 && j < layer; j++)
			{
				if (j == layer - 1)
				{
					if (i == nodeList.length - 1)
						indent += "   └  ";
					else
						indent += "   ├  ";
				}
				else
				{
					indent += "   " + (isParentLast ? "" : "│");
				}
			}

			_selectControl.options.add(new Option(indent + name, id));
	
			if (i == nodeList.length - 1)
				Run(id, true, layer + 1);
			else
				Run(id, false, layer + 1);
		}
	}
	
	Run(g_empty, false, 0);
}

function CheckAndSelect(control, value)
{
	for (var i = 0 ; i < control.length ; i++)
	{
		if (control.options[i].value == value)
		{
			control.selectedIndex = i;
			break;
		}
	}
}

function GetChecked(name)
{
	var result = "";
	$("[name=" + name + "]:checkbox:checked").each(function()
	{
		if (result == "")
			result = this.value;
		else
			result += "|" + this.value;
	});

	return result;
}

function PageIDCandidate_OnChange()
{
    var pageID = $("[name=PageID]")[0];
    if (this.value == "")
    {
        pageID.value = this.value;
        return;
    }

    if ($.browser.msie)
    {
        pageID.focus();
        document.selection.createRange().text = this.value;
    }
    else
    {
        pageID.value = this.value;
    }
}

//-------------------------------------------------
//Start : 登陆
function Login()
{
	if (this.Name.value == "")
	{
		Alert(_lang_name_empty, function(){this.Name.select();}, this);
		return false;
	}
	
	if (this.Password.value == "")
	{
		Alert(_lang_password_empty, function(){this.Password.select();}, this);
		return false;
	}
	
	if (this.CheckCode != null && this.CheckCode.value == "")
	{
		Alert(_lang_check_code_empty, function(){this.CheckCode.select();}, this);
		return false;
	}
	
	var data = "Name=" + encodeURIComponent(this.Name.value);
	data += "&Password=" + encodeURIComponent(this.Password.value);
	if (this.CheckCode != null)
	    data += "&CheckCode=" + encodeURIComponent(this.CheckCode.value);
	
	$(":submit").eq(0).attr("disabled", true);

	$.ajax(
	{
		url : _webPath + "ilghar.aspx?Lang=" + _lang + "&Object=Admin&Operation=Login",
		data : data,
		type : "POST",
		error : function(request)
		{
			Alert(_lang_operation_fail);
	        $(":submit").eq(0).attr("disabled", false);
	        
	        var img = $("#CheckCodeImage");
	        if (img.length == 1)
	            img.attr("src", img.attr("src") + "&" + Math.random());
		},
		success : function(data)
		{
		    window.location.href = window.location.href.replace("login", "index");
		}
	});

	return false;
}
//End : 登陆
//-------------------------------------------------

//-------------------------------------------------
//Start : 修改资料
function ModifyMaterial()
{
	if (this.Name.value == "")
	{
		Alert(_lang_name_empty, function(){this.Name.select();}, this);
		return false;
	}
	
	if (!this.Email.value.match(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/))
	{
		Alert(_lang_email_incorrect, function(){this.Email.select();}, this);
		return false;
	}
	
	var data = "Name=" + encodeURIComponent(this.Name.value);
	if (this.Password.value != "")
		data += "&Password=" + encodeURIComponent(this.Password.value);
	data += "&Email=" + encodeURIComponent(this.Email.value);
	data += "&RealName=" + encodeURIComponent(this.RealName.value);
	data += "&QQ=" + encodeURIComponent(this.QQ.value);
	data += "&MSN=" + encodeURIComponent(this.MSN.value);

	$(":submit").eq(0).attr("disabled", true);
	SetStatusMessage(_lang_working);
	
	$.ajax(
	{
		url : _webPath + "ilghar.aspx?Lang=" + _lang + "&Object=Admin&Operation=Modify&ID=" + _id,
		data : data,
		type : "POST",
		error : function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
			$(":submit").eq(0).attr("disabled", false);
		},
		success : function(data)
		{
		    Alert(_lang_operation_success);
		    SetStatusMessage();
		    $(":submit").eq(0).attr("disabled", false);
		}
	});
	
	return false;
}
//End : 修改资料
//-------------------------------------------------

function CommonInit()
{
    self.focus();
	HandleFake404();
	
	//处理上一页，下一页和刷新的键盘事件
	$("html").keyup(function(e)
	{
	    if (e.ctrlKey && e.keyCode == 83 && typeof(_page) != "undefined" && (_page.indexOf("add") != -1 || _page.indexOf("edit") != -1))//保存
	    {
	        $("form").eq(0).submit();
	        return;
	    }
	
		if (e.target.tagName == "INPUT" || e.target.tagName == "TEXTAREA")
			return;

		if (e.keyCode == 37)//上一页
		{
			if ($("#PrevPage").length > 0)
				window.location = $("#PrevPage").attr("href");
		}
		else if (e.keyCode == 39)//下一页
		{
			if ($("#NextPage").length > 0)
				window.location = $("#NextPage").attr("href");
		}
		else if (e.keyCode == 82)//R -> Refresh -> 刷新
		{
			window.location.reload();
		}
	});

	$(".WhiteHeader .Left img").click(function()
	{
		var me = $(this);
		var frameset = $(parent.document.getElementById("Frame"));
		if (me.attr("src").indexOf("close") != -1)
		{
			frameset.attr("cols", frameset.attr("cols").replace(/\d+/, "0"));
			me.attr("src", me.attr("src").replace("close", "open"));
		}
		else
		{
			frameset.attr("cols", frameset.attr("cols").replace(/\d+/, "180"));
			me.attr("src", me.attr("src").replace("open", "close"));
		}
	});
	
	$(".WhiteHeader .Right img").mouseover(function(){this.src = _imagePath + "dropdown_over.gif";ShowLanguageMenu(this)}).mouseout(function(){this.src = _imagePath + "dropdown.gif"});
	
	if (typeof (_page) == "undefined")
		return;

	if (_page == "login")
	{
		if (window.top != window.self)
			window.top.location = window.location;
		
		$("form:first").submit(Login);
		$("#CheckCodeImage").click(function(){this.src += "&" + Math.random();});
	}
	else if (_page == "index")
	{
	    var main = $("#Main");
	    main.height($("html").height() - $(".Header").height() - $("#MenuBar").height());
	    main.attr("src", window.location.href.replace("index", "desktop"));
    	
	    CheckAndSelect($("[name=LanguageID]")[0], GetCookie("DefaultContentLanguage"));
	    
	    $("body").bind("contextmenu", function(){return false;});
	    window.onresize = function(){main.height($("html").height() - $(".Header").height() - $("#MenuBar").height());};
	    $("[name=LanguageID]").change(function(){SetCookie("DefaultContentLanguage", this.value, 10*360*24*60, "/");});
	    
		$("#MenuBar li").each(function()
		{
		    this.onmouseover = function(){$(this).addClass("iehover");};
		    this.onmouseout = function(){$(this).removeClass("iehover");};
		});
	}
	else if (_page == "left")
	{
	    CloseAll();
	    $("table").css("display", "");
	}
	else if (_page == "material")
	{
		$("form").eq(0).submit(ModifyMaterial);
	}
}
CommonInit();