function BuildHeader()
{
	if (_page == "link_list")
		return BuildAjaxPath(true) + "?IsRecycled=" + $("#IsRecycled").val() + "&IsChecked=" + $("#IsChecked").val() + "&IsRecommended=" + $("#IsRecommended").val() + "&IsHeld=" + $("#IsHeld").val() + "&Sort=" + $("#Sort").val() + "&Keyword=" + encodeURIComponent($("#Keyword").val()) + "&KeywordType=" + $("#KeywordType").val() + "&Page=" + _pageNumber;
	else if (_page == "tag_select")
		return BuildAjaxPath(true) + "?Sort=" + $("#Sort").val() + "&Keyword=" + encodeURIComponent($("#Keyword").val()) + "&KeywordType=" + $("#KeywordType").val() + "&Page=" + _pageNumber;
}	

function Search()
{
	if (arguments.length > 0 && typeof(arguments[0]) != "object")
		_pageNumber = arguments[0];
	
	SetStatusMessage(_lang_working);
	$.ajax(
	{
		url : BuildHeader(),
		data : {},
		type : "POST",
		error : function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
		},
		success : function(data)
		{
			$("#List").html(HandleFake404(data, "text"));
			Init();
			SetStatusMessage();
		}
	});
}

function MakeButton()
{
	var buttons = "";

	if (_page == "link_list")
	{
	    if ($("#IsRecycled")[0].selectedIndex == 1)
	    {
		    buttons += "<button class=\"Button\" onclick=\"UpdateLink('Recycle')\" >" + _lang_recycle + "</button>";
	    }
	    else if ($("#IsRecycled")[0].selectedIndex == 2)
	    {
		    buttons += "<button class=\"Button\" onclick=\"UpdateLink('Delete')\" >" + _lang_delete + "</button>";
		    buttons += "<button class=\"Button\" onclick=\"UpdateLink('Recover')\" >" + _lang_recover + "</button>";
	    }
	}
		
	$("#ExtraButton").html(buttons);
}

function ShowSelectDialog(type)
{
	var path;
	if (type == "Tag")
		path = "../tag/select.aspx";

	path = HandleFake404(path, "url");
	if ($.browser.msie)
		window.showModalDialog(path, window, "status=0;dialogWidth=500px;dialogHeight=500px;center=1;help=0;resizable=1;scroll=1");
	else
		window.open(path,null,"width=500,height=500,dialog=yes,modal=yes,maximize=no,menubar=no,toolbar=no,location=no,scrollbars=yes,status=no");
}

function SelectTag(tag, checked)
{
	var tags = $("[name=Tag]");
	for (var i = 0; i < tags.length; i++)
	{
		if (tags[i].id == tag.ID)
		{
			tags[i].checked = checked;
			return;
		}
	}
	
	var tagContainer = $("#TagDiv");
	var br = "";
	if (tags.length > 0 && tags.length % 5 == 0) br = "<br />";
	tagContainer.html(tagContainer.html() + br + "<input type='checkbox' checked='checked' name='Tag' id='" + tag.ID + "' tagName='" + tag.Name + "' tagPageGenerate='" + tag.PageGenerate + "' tagPageTemplate='" + tag.PageTemplate + "'' tagPageID='" + tag.PageID + "'' tagPageExtension='" + tag.PageExtension + "' /><label for='" + tag.ID + "'>" + tag.Name + "</label>");	
}

function PrepareTag()
{
    var result = {Names:"",PageIDs:"",PageGenerates:"",PageTemplates:"",PageExtensions:""};	
    var tags = $("[name=Tag]");
	
	if (typeof(_tagIndex) != "undefined")
	{
	    _tagIndex = 0;
	}
	else
	{
	    _tagAddIndex = 0;
	    _tagDeleteIndex = 0;
	    _tagAddList.length = 0;
	    _tagDeleteList.length = 0;
    	    	
	    tags.each(function()
	    {
		    if (this.checked)
		    {
			    var j = 0;
			    for (; j < _tags.length; j++)
			    {
				    if (this.id == _tags[j] || this.id == _tags[j].ID)
					    break;
			    }
			    if (j >= _tags.length)
				    _tagAddList[_tagAddList.length] = this.id;
		    }
		    else
		    {
			    for (var j = 0; j < _tags.length; j++)
			    {
				    if (this.id == _tags[j] || this.id == _tags[j].ID)
				    {
					    _tagDeleteList[_tagDeleteList.length] = this.id;
					    break;
				    }
			    }
		    }
	    });
	}

	_tags.length = 0;
	tags.each(function()
	{
		if (!this.checked)
		    return false;

		_tags[_tags.length] = this.id;

		if (result.Names == "")
			result.Names = "|";
		result.Names += this.value + "|";
		
		if (result.PageGenerates == "")
			result.PageGenerates = "|";
		result.PageGenerates += $(this).attr("PageGenerate") + "|";
		
		if (result.PageTemplates == "")
			result.PageTemplates = "|";
		result.PageTemplates += $(this).attr("PageTemplate") + "|";
		
		if (result.PageIDs == "")
			result.PageIDs = "|";
		result.PageIDs += $(this).attr("PageID") + "|";
		
		if (result.PageExtensions == "")
			result.PageExtensions = "|";
		result.PageExtensions += $(this).attr("PageExtension") + "|";
	});
	
	return result;
}

//-------------------------------------------------
//Start : 网址管理
function AddLink()
{
    if (_isLocked)
    {
        Alert(_lang_locked);
        return false;
    }

	if (this.Name.value == "")
	{
		Alert(_lang_name_empty, function(){this.Name.select();}, this);
		return false;
	}
	
	if (!this.URL.value.match(/^http:\/\/.*/))
	{
		Alert(_lang_url_incorrect, function(){this.URL.select();}, this);
		return false;
	}
	
	if (this.Description.value.length > 250)
	{
		Alert(_lang_description_incorrect, function(){this.Description.select();}, this);
		return false;
	}
	
	if (!IsAllowedType(this.Logo.value, this.LogoAllowedType.value))
	{
		Alert(_lang_logo_must_be + this.LogoAllowedType.value, function(){this.Logo.select();}, this);
		return false;
	}
	
	var tag = PrepareTag();

	var category = $("[name=CategoryID] option:selected");
	var region = $("[name=RegionID] option:selected");
	
	var data = "IsChecked=false&Name=" + encodeURIComponent(this.Name.value);
	data += "&CategoryID=" + this.CategoryID.value;
	data += "&CategoryName=" + category.attr("Name");
	data += "&CategoryPageGenerate=" + category.attr("PageGenerate");
	data += "&CategoryPageTemplate=" + category.attr("PageTemplate");
	data += "&CategoryPageID=" + category.attr("PageID");
	data += "&CategoryPageExtension=" + category.attr("PageExtension");
	data += "&RegionID=" + this.RegionID.value;
	data += "&RegionName=" + region.attr("Name");
	data += "&RegionPageGenerate=" + region.attr("PageGenerate");
	data += "&RegionPageTemplate=" + region.attr("PageTemplate");
	data += "&RegionPageID=" + region.attr("PageID");
	data += "&RegionPageExtension=" + region.attr("PageExtension");
	data += "&URL=" + encodeURIComponent(this.URL.value);
	data += "&Logo=" + encodeURIComponent(this.Logo.value);
	data += "&Webmaster=" + encodeURIComponent(this.Webmaster.value);
	data += "&QQ=" + encodeURIComponent(this.QQ.value);
	data += "&Email=" + encodeURIComponent(this.Email.value);
	data += "&Phone=" + encodeURIComponent(this.Phone.value);
	if ($("#IsAlexaUpdateYes")[0].checked)
		data += "&AlexaUpdate=" + FormatDate(new Date());
	data += "&Description=" + encodeURIComponent(this.Description.value);
	data += "&TagNames=" + encodeURIComponent(tag.Names);
	data += "&TagPageGenerates=" + encodeURIComponent(tag.PageGenerates);
	data += "&TagPageTemplates=" + encodeURIComponent(tag.PageTemplates);
	data += "&TagPageIDs=" + encodeURIComponent(tag.PageIDs);
	data += "&TagPageExtensions=" + encodeURIComponent(tag.PageExtensions);

	$(":submit")[0].disabled = true;
	SetStatusMessage(_lang_working);

	$.ajax(
	{
		url : _webPath + "ilghar.aspx?Object=Link&Operation=Add",
		data : data,
		type : "POST",
		error : function(request)
		{
			Alert(_lang_add_link_fail);
			SetStatusMessage();
			$(":submit")[0].disabled = false;
		},
		success : function(data)
		{
			_guid = data;
		    AddLink_GetInnerID();
		}
	});
	return false;
}

function AddLink_GetInnerID()
{
    SetStatusMessage(_lang_getting_innerid);

	$.ajax(
	{
		url : _webPath + "ilghar.aspx?Object=Link&Operation=GetInnerIDFromGuid&ID=" + _guid,
		data : {},
		type : "POST",
		error : function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
		},
		success : function(data)
		{
            _id = data;
			AddLink_SetPageID();
		}
	});
}

function AddLink_SetPageID()
{
    SetStatusMessage(_lang_setting_pageid);

	$.ajax(
	{
		url : _webPath + "ilghar.aspx?Object=Link&Operation=Modify&ID=" + _id,
		data : "PageID=" + encodeURIComponent(_id),
		type : "POST",
		error : function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
		},
		success : function(data)
		{
    		AddLink_AddTag();
		}
	});
}

function AddLink_AddTag()
{
	if (_tagIndex >= _tags.length)
	{
		Alert(_lang_operation_success);
		SetStatusMessage();
		$(":submit").eq(0).attr("disabled", false);
        return;
	}
	
	var data = "LinkID=" + _guid;
	data += "&TagID=" + _tags[_tagIndex];
	
	_tagIndex++;

    SetStatusMessage(_lang_adding_tag);

	$.ajax(
	{
		url : _webPath + "ilghar.aspx?Object=Link.Tag&Operation=Add",
		data : data,
		type : "POST",
		error : function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
			$(":submit").eq(0).attr("disabled", false);
		},
		success : function(data)
		{
			AddLink_AddTag();
		}
	});
}

function EditLink()
{
    if (_isLocked)
    {
        Alert(_lang_locked);
        return false;
    }

	if (this.Name.value == "")
	{
		Alert(_lang_name_empty, function(){this.Name.select();}, this);
		return false;
	}
	
	if (!this.URL.value.match(/^http:\/\/.*/))
	{
		Alert(_lang_url_incorrect, function(){this.URL.select();}, this);
		return false;
	}
	
	if (this.Description.value.length > 250)
	{
		Alert(_lang_description_incorrect, function(){this.Description.select();}, this);
		return false;
	}
	
	if (!IsAllowedType(this.Logo.value, this.LogoAllowedType.value))
	{
		Alert(_lang_logo_must_be + this.LogoAllowedType.value, function(){this.Logo.select();}, this);
		return false;
	}
	
	var tag = PrepareTag();
	
	var category = $("[name=CategoryID] option:selected");
	var region = $("[name=RegionID] option:selected");
	
	var data = "IsChecked=false&Name=" + encodeURIComponent(this.Name.value);
	data += "&CategoryID=" + this.CategoryID.value;
	data += "&CategoryName=" + category.attr("Name");
	data += "&CategoryPageGenerate=" + category.attr("PageGenerate");
	data += "&CategoryPageTemplate=" + category.attr("PageTemplate");
	data += "&CategoryPageID=" + category.attr("PageID");
	data += "&CategoryPageExtension=" + category.attr("PageExtension");
	data += "&RegionID=" + this.RegionID.value;
	data += "&RegionName=" + region.attr("Name");
	data += "&RegionPageGenerate=" + region.attr("PageGenerate");
	data += "&RegionPageTemplate=" + region.attr("PageTemplate");
	data += "&RegionPageID=" + region.attr("PageID");
	data += "&RegionPageExtension=" + region.attr("PageExtension");
	data += "&URL=" + encodeURIComponent(this.URL.value);
	data += "&Logo=" + encodeURIComponent(this.Logo.value);
	data += "&Webmaster=" + encodeURIComponent(this.Webmaster.value);
	data += "&QQ=" + encodeURIComponent(this.QQ.value);
	data += "&Email=" + encodeURIComponent(this.Email.value);
	data += "&Phone=" + encodeURIComponent(this.Phone.value);
	if ($("#IsAlexaUpdateYes")[0].checked)
		data += "&AlexaUpdate=" + FormatDate(new Date());
	data += "&Description=" + encodeURIComponent(this.Description.value);
	data += "&TagNames=" + encodeURIComponent(tag.Names);
	data += "&TagPageGenerates=" + encodeURIComponent(tag.PageGenerates);
	data += "&TagPageTemplates=" + encodeURIComponent(tag.PageTemplates);
	data += "&TagPageIDs=" + encodeURIComponent(tag.PageIDs);
	data += "&TagPageExtensions=" + encodeURIComponent(tag.PageExtensions);

	$(":submit")[0].disabled = true;
	SetStatusMessage(_lang_working);

	$.ajax(
	{
		url : _webPath + "ilghar.aspx?Object=Link&Operation=Modify&ID=" + _id,
		data : data,
		type : "POST",
		error : function(request)
		{
			Alert(_lang_edit_link_fail);
			SetStatusMessage();
			$(":submit")[0].disabled = false;
		},
		success : function(data)
		{
			EditLink_DeleteTag();
		}
	});

	return false;
}

function EditLink_DeleteTag()
{
	if (_tagDeleteIndex >= _tagDeleteList.length)
	{
		EditLink_AddTag();
		return;
	}

	SetStatusMessage(_lang_modifying_tag);

	$.ajax(
	{
		url : _webPath + "ilghar.aspx?Object=Link.Tag&Operation=Delete&LinkID=" + _guid + "&TagID=" + _tagDeleteList[_tagDeleteIndex++],
		data : {},
		type : "POST",
		error : function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
			$(":submit").eq(0).attr("disabled", false);
		},
		success : function(data)
		{
			EditLink_DeleteTag();
		}
	});
}

function EditLink_AddTag()
{
	if (_tagAddIndex >= _tagAddList.length)
	{
		Alert(_lang_operation_success);
		SetStatusMessage();
		$(":submit").eq(0).attr("disabled", false);
        return;
	}
	
	var data = "LinkID=" + _guid;
	data += "&TagID=" + _tagAddList[_tagAddIndex];
	
	_tagAddIndex++;

	$.ajax(
	{
		url : _webPath + "ilghar.aspx?Object=Link.Tag&Operation=Add",
		data : data,
		type : "POST",
		error : function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
			$(":submit").eq(0).attr("disabled", false);
		},
		success : function(data)
		{
			EditLink_AddTag();
		}
	});
}

function UpdateLink(action, id)
{
    if (_isLocked)
    {
        Alert(_lang_locked);
        return;
    }

	if (id == null)
	{
		id = "";
		$("[name=Sel]:checked").each(function(){id += id == "" ? this.value : "|" + this.value;});
		if(id == "")
		{
			Alert(_lang_selection_empty);
			return;
		}
		
		if(action == "Delete")
			Confirm(_lang_confirm_delete, function(returnValue){if (returnValue)UpdateLink(action, id);}, this);
		else
			UpdateLink(action, id);
	}
	else
	{
		SetStatusMessage(_lang_working);

		$.ajax(
		{
			url : _webPath + "ilghar.aspx?Object=Link&Operation=" + action + "&ID=" + id + "&Transfer=" + encodeURIComponent(BuildHeader()),
			data : {},
			type : "POST",
			error : function(request)
			{
				Alert(_lang_operation_fail);
				SetStatusMessage();
			},
			success : function(data)
			{
				Alert(_lang_operation_success);
				SetStatusMessage();

				$("#List").html(HandleFake404(data, "text"));
				Init();
			}
		});
	}
}
//End : 网址管理
//-------------------------------------------------

function Init()
{
	if (typeof (_page) == "undefined")
		return;
	
	if (_page == "link_add")
	{
		$("form").submit(AddLink);
		$("#TagSelect").click(function(){ShowSelectDialog("Tag")});
	}
	else if (_page == "link_edit")
	{
		for (var i = 0; i < _tags.length; i++)
		{
	        SelectTag(_tags[i], true)
		}
		
		if (_alexaUpdate == "")
			$("#IsAlexaUpdateNo")[0].checked = true;
		else
			$("#IsAlexaUpdateYes")[0].checked = true;
		
		$("form").submit(EditLink);
		$("#TagSelect").click(function(){ShowSelectDialog("Tag")});
	}
	else if (_page == "link_list")
	{
		MakeButton();

		if (arguments.length == 0)
		    return;

		$("#IsRecycled,#IsChecked,#IsRecommended,#IsHeld,#Sort").change(Search);
		$("#Keyword").keydown(function(e){if(e.keyCode == 13){Search(1);e.preventDefault();}});
		$("#Search").click(function(){Search(1);});
		$("#SelectAll").click(function(){$(":checkbox[name=Sel]").each(function(){this.checked = true;});});
		$("#ReverseSelect").click(function(){$(":checkbox[name=Sel]").each(function(){this.checked = !this.checked;});});
	}
	else if (_page == "tag_select")
	{
		$(":checkbox").click(function()
		{
            if ($.browser.msie)
				window.dialogArguments.SelectTag({ID:$(this).attr("ID"),Name:$(this).attr("Name"),PageGenerate:$(this).attr("PageGenerate"),PageTemplate:$(this).attr("PageTemplate"),PageID:$(this).attr("PageID"),PageExtension:$(this).attr("PageExtension")}, this.checked);
			else
				window.opener.SelectTag({ID:$(this).attr("ID"),Name:$(this).attr("Name"),PageGenerate:$(this).attr("PageGenerate"),PageTemplate:$(this).attr("PageTemplate"),PageID:$(this).attr("PageID"),PageExtension:$(this).attr("PageExtension")}, this.checked);
		});

		if (arguments.length == 0)
		    return;

		$("#Sort").change(Search);
		$("#Keyword").keydown(function(e){if(e.keyCode == 13){Search(1);e.preventDefault();}});
		$("#Search").click(function(){Search(1);});	
		$("#Ok").click(function(){window.close();});
	}
}
Init(true);