<?php
define('IS_ADMIN', true);
require_once(dirname(__FILE__)."/../../../include/init.php");
$expire = mktime(0, 0, 0, date("m")+COOKIE_EXPIRE, date("d"), date("Y"));
$expireDate = date("Y", $expire).", ".date("n", $expire).", ".date("j", $expire);
$request = new LocalObject($_GET);
?>
document.onkeydown = DocumentKeyDown;
var path2Admin = "<?php echo PROJECT_PATH."module/catalog/"; ?>";
var pageID = "<?php echo $request->GetIntProperty("PageID"); ?>";

function DocumentKeyDown(domEvent)
{
	var ev = window.event ? window.event : domEvent;
	if (ev.keyCode == 27 && window.currentEditedDiv) window.currentEditedDiv.EndEditing();
}

function ShowNode(id)
{
	var re = /cen=\['\d+'(,'\d+')*\]/;
	if (arr = re.exec(unescape(document.cookie)))
	{
		eval("var " + arr[0]);
	}
	else
		var cen = [];

	var cookieValue = "cen=[";
	var alreadyShown = false;
	for (i = 0; i < cen.length; i++)
	{
		cookieValue += "'"+cen[i]+"',";
		if (id == unescape(cen[i]))
			alreadyShown = true;
	}

	if (alreadyShown == false)
		cookieValue += "'"+escape(id)+"',";

	cookieValue = cookieValue.substr(0, cookieValue.length - 1) + "]";
	var d = new Date(<?php echo $expireDate ?>);
	document.cookie = cookieValue + "; expires=" + d.toUTCString() + "; path=<?php echo PROJECT_PATH; ?>;";
}

function HideNode(id)
{
	var re = /cen=\['\d+'(,'\d+')*\]/;
	if (arr = re.exec(unescape(document.cookie)))
	{
		eval("var " + arr[0]);
		var cookieValue = "cen=[";
		for (i = 0; i < cen.length; i++)
		{
			if (id != unescape(cen[i]))
			{
				cookieValue += "'"+cen[i]+"',";
			}
		}
		var d = new Date(<?php echo $expireDate ?>);
		if (cookieValue == "cen=[")
		{
			document.cookie = "cen=; expires=" + d.toUTCString() + "; path=<?php echo PROJECT_PATH; ?>;";
		}
		else
		{
			cookieValue = cookieValue.substr(0, cookieValue.length - 1) + "]";
			document.cookie = cookieValue + "; expires=" + d.toUTCString() + "; path=<?php echo PROJECT_PATH; ?>;";
		}
	}
}

function NodeIsHidden(id)
{
	var re = /cen=\['\d+'(,'\d+')*\]/;
	if (arr = re.exec(unescape(document.cookie)))
	{
		eval("var " + arr[0]);
		for (i = 0; i < cen.length; i++)
		{
			if (id == unescape(cen[i]))
				return false;
		}
	}
	return true;
}

function ExchangeButtons(type, btn1ID, btn2ID)
{
	var button1 = $(type+"_button" + btn1ID);
	var button2 = $(type+"_button" + btn2ID);
	if (button1 && button2)
	{
		var tempCursor = button1.style.cursor;
		var tempSrc = button1.src;
		button1.style.cursor = button2.style.cursor;
		button1.src = button2.src;
		button2.style.cursor = tempCursor;
		button2.src = tempSrc;
	}
}

function MyTree() { this._construct() }
(function() { // to create local-scope variables
	var nodeList = new Object();

	MyTree.prototype = {
		_construct: function()
		{
			nodeList[0] = new Object();
			nodeList[0].active = 'Y';
			prevID = 0;
			prevParentID = 0;
		},

		AppendTo: function(id)
		{
			nodeList[0].childDiv = $(id);
		},

		DisableDownButton: function()
		{
			var downButton = $("down_button" + prevID);
			if (downButton)
			{
				downButton.style.cursor = "default";
				downButton.src = IconDownDisabled;
			}
		},

		InitNodeDiv: function(id, parentID, jsTitle, jsDescription, active, itemCount)
		{
			if (nodeList[parentID])
			{
				// Color legend
				// #000000/#8C8E8D - active/inactive black
				var titleColor = "#000000";
				var descriptionColor = "#8C8E8D";
				if (active == 'Y' && nodeList[parentID].active == 'Y')
				{
					active = 'Y';
					titleColor = "#000000";
				}
				else
				{
					active = 'N';
					titleColor = "#8C8E8D";
				}

				if (!jsDescription.length)
				{
					jsDescription = GetTranslation("no-description");
				}

				// Add node
				var newNode = document.createElement("div");
				newNode.id = "node_div"+id;
				var nodeContent = '<div id="title_div'+id+'" class="title_div">\r\n';
				nodeContent += '	<div class="toolbar_div">\r\n';
				nodeContent += '		<img src="'+jsIconPath+'ico_down_grey.gif" width="10" height="7" align="absmiddle" id="down_button'+id+'" title="'+GetTranslation("icon-down")+'" />\r\n';
				nodeContent += '		<img src="'+jsIconPath+'ico_up_grey.gif" width="10" height="7" align="absmiddle" id="up_button'+id+'" title="'+GetTranslation("icon-up")+'" />&nbsp;&nbsp;\r\n';
				nodeContent += '		<img src="'+jsIconPath+'seo.png" width="33" height="16" style="cursor: pointer;" align="absmiddle" id="edit_meta_button'+id+'" title="'+GetTranslation("click-to-edit-meta")+'" />&nbsp;&nbsp;&nbsp;\r\n';
				nodeContent += '		<img src="'+jsIconPath+'edit.png" width="16" height="16" style="cursor: pointer;" align="absmiddle" id="edit_button'+id+'" title="'+GetTranslation("icon-edit")+'" />&nbsp;&nbsp;&nbsp;\r\n';
				nodeContent += '		<img src="'+jsIconPath+'delete.png" width="16" height="16" style="cursor: pointer;" align="absmiddle"  id="delete_button'+id+'" title="'+GetTranslation("icon-delete")+'" />\r\n';
				nodeContent += '	</div>\r\n';
				nodeContent += '	<img src="'+jsIconPath+'page-pctgr.png" id="plus_minus'+id+'" width="16" height="16" style="vertical-align: top;" />\r\n';
				nodeContent += '	<span id="title_span'+id+'" style="cursor: pointer; color: '+titleColor+'">'+jsTitle+' ('+itemCount+')&nbsp;</span>\r\n';
				nodeContent += '</div>\r\n';
				nodeContent += '<div id="description_div'+id+'" class="description_div">\r\n';
				nodeContent += '	<span id="description_span'+id+'" style="color: '+descriptionColor+'"><i>'+jsDescription+'&nbsp;</i></span>\r\n';
				nodeContent += '</div>\r\n';
				nodeContent += '<div class="child_div" id="child_div'+id+'"></div>\r\n';
				newNode.innerHTML = nodeContent;
				// Assign node to its parent
				nodeList[parentID].childDiv.appendChild(newNode);
				if (parentID > 0)
				{
					// Define plus/minus icon for parent node
					nodeList[parentID].plusMinusButton.style.cursor = "pointer";
					if (NodeIsHidden(parentID))
					{
						nodeList[parentID].childDiv.style.display = "none";
						nodeList[parentID].plusMinusButton.src = iconPlus;
					}
					else
					{
						nodeList[parentID].plusMinusButton.src = iconMinus;
					}
				}
			}
			else
			{
				alert("ERROR: parent '" + parentID + "' is not found for '" + id + "'");
				return;
			}

			nodeList[id] = new Object();
			nodeList[id].parentID = parentID;
			nodeList[id].jsTitle = jsTitle+' ('+itemCount+')';
			nodeList[id].active = active;
			nodeList[id].itemCount = itemCount;

			nodeList[id].nodeDiv = newNode;
			nodeList[id].childDiv = $("child_div"+id);
			nodeList[id].nodeDiv.hashID = id;

			nodeList[id].titleSpan = $("title_span"+id);
			nodeList[id].descriptionSpan = $("description_span"+id);
			nodeList[id].editMetaButton = $("edit_meta_button"+id);

			nodeList[id].titleDiv = this._InitTitleDiv(id);
			nodeList[id].descriptionDiv = this._InitDescriptionDiv(id);

			nodeList[id].plusMinusButton = this._InitPlusMinusButton(id);

			// Init move down button
			nodeList[id].downButton = this._InitDownButton(id);
			if (prevParentID != parentID)
			{
				this.DisableDownButton();
			}

			// Init move down up
			if (nodeList[parentID].childDiv.childNodes.length == 1)
				nodeList[id].upButton = this._InitUpButton(id, true);
			else
				nodeList[id].upButton = this._InitUpButton(id, false);

			nodeList[id].editButton = this._InitEditButton(id);
			nodeList[id].deleteButton = this._InitDeleteButton(id);

			prevID = id;
			prevParentID = parentID;
		},

		_InitTitleDiv: function(id)
		{
			var div = $("title_div"+id);
			div.hashID = id;
			div.emptyText = "<i>"+GetTranslation("no-title")+"</i>";
			div.titleSpan = nodeList[id].titleSpan;
			div.editMetaButton = nodeList[id].editMetaButton;
			div.type = "Title";
			div = this._InitNonEditableDiv(div);

			nodeList[id].titleSpan.className = "title_span";
			div.title = GetTranslation("open-item-list");
			div = this._InitEditableDiv(div);

			return div;
		},

		_InitDescriptionDiv: function(id)
		{
			var div = $("description_div"+id);
			div.hashID = id;
			div.emptyText = GetTranslation("no-description");
			div.editPart = nodeList[id].descriptionSpan;
			div.type = "Description";

			div.SetEmptyText = function()
			{
				if (this.emptyText && (this.editPart.innerHTML == "&nbsp;" || this.editPart.innerHTML == " " || this.editPart.innerHTML.charCodeAt(0) == 160))
				{
					this.editPart.innerHTML = div.emptyText;
				}
			}

			return div;
		},

		_InitNonEditableDiv: function(div)
		{
			div.onmouseover = function()
			{
				this.Highlight();
			}

			div.onmouseout = function()
			{
				this.UnHighlight();
			}

			div.Highlight = function()
			{
				div.style.backgroundColor = "#CCDBEA";
			}

			div.UnHighlight = function()
			{
				this.style.backgroundColor = "";
			}

			div.SetEmptyText = function()
			{
				if (this.emptyText && (this.titleSpan.innerHTML == "&nbsp;" || this.titleSpan.innerHTML == " " || this.titleSpan.innerHTML.charCodeAt(0) == 160))
				{
					this.titleSpan.innerHTML = div.emptyText;
				}
			}

			div.SetEmptyText();

			return div;
		},

		_InitEditableDiv: function(div)
		{
			div.titleSpan.onclick = function()
			{
				document.location.href = moduleURL+"&ViewCategoryID="+div.hashID;
			}

			div.editMetaButton.onclick = function()
			{
				if (window.isLoading) return;
				if (window.currentEditedDiv)
					window.currentEditedDiv.EndEditing();

				if (!div.form_div)
				{
					div.form_div = document.createElement("div");
					div.parentNode.insertBefore(div.form_div, div);
					div.form_div.display_div = div;
				}
				window.isLoading = true;

				JsHttpRequest.query(
					path2Admin+'ajax.php',
					{
						'Action': "LoadMeta",
						'CategoryID': div.hashID,
						'PageID': pageID
					},
					// Function is called when an answer arrives.
					function(result, errors)
					{
					    if (!result) return;

					    if (result["SessionExpired"])
						{
							document.location.href = "index.php";
							return;
						}

						div.form_div.className = "option_div";
						var width = 500;
						var r = getAbsolutePos(div.editMetaButton);
						div.form_div.style.left = (r.x-width-3)+"px";
						div.form_div.style.top = (r.y-100)+"px";
						div.form_div.style.display = "block";
						var form = '<form onsubmit="window.currentEditedDiv.SaveChanges(this); return false;" class="display_inline"><table border=\"0\" cellpadding=\"4\" cellspacing=\"0\" width="'+width+'">';
						form += "<tr><td colspan=\"2\" class=\"meta_info\"><div style=\"display: inline; float: left;\">"+GetTranslation("meta-info")+"</div><div style=\"display: inline; float: right;\"><a href=\"javascript:window.currentEditedDiv.EndEditing();\" title=\""+GetTranslation("close")+"\">X</a></div></td></tr>";
						form += "<tr><td valign=\"top\" width=\"30%\">"+GetTranslation("meta-title")+"</td><td width=\"70%\"><input name=\"MetaTitle\" class=\"title_input\" value=\""+result["MetaTitle"].replace(/\"/g,"&#34;")+"\" /></td></tr>";
						form += "<tr><td valign=\"top\">"+GetTranslation("meta-keywords")+"</td><td><textarea rows=\"4\" name=\"MetaKeywords\" class=\"title_input\" />"+result["MetaKeywords"].replace(/\"/g,"&#34;")+"</textarea></td></tr>";
						form += "<tr><td valign=\"top\">"+GetTranslation("meta-description")+"</td><td><textarea rows=\"4\" name=\"MetaDescription\" class=\"title_input\" />"+result["MetaDescription"].replace(/\"/g,"&#34;")+"</textarea></td></tr>";
						form += '<tr><td align="center" colspan="2"><input type="submit" class="btn_big" value="' + GetTranslation("save") + '" />&nbsp;&nbsp;<span style="font-family:arial; font-size:12px;"> </span>&nbsp;&nbsp;<input type="button" class="btn_big" value="' + GetTranslation("cancel") + '" onclick="window.currentEditedDiv.EndEditing();"></td></tr>';
						form += '</table></form>';

						div.form_div.innerHTML = form;

						div.form_div.childNodes[0].elements[0].focus();
						window.currentEditedDiv = div;

						window.isLoading = false;
					},
					true
				);
			}

			div.EndEditing = function()
			{
				this.isEditing = false;
				var formDiv = this.form_div;
				formDiv.innerHTML = "";
				formDiv.style.display = "none";
				this.style.display = "block";
			}

			div.SaveChanges = function(form)
			{
				var metaTitle = form.elements["MetaTitle"].value;
				var metaKeywords = form.elements["MetaKeywords"].value;
				var metaDescription = form.elements["MetaDescription"].value;

				if (window.isLoading) return;
				window.isLoading = true;

				this.EndEditing();

				JsHttpRequest.query(
					path2Admin+'ajax.php',
					{
						'Action': "UpdateMeta",
						'MetaTitle': metaTitle,
						'MetaKeywords': metaKeywords,
						'MetaDescription': metaDescription,
						'CategoryID': this.hashID,
						'PageID': pageID
					},
					function(result, errors)
					{
					    if (!result) return;

					    if (result["SessionExpired"])
						{
							document.location.href = "index.php";
							return;
						}

						window.isLoading = false;
					},
					true
				);
			}

			div.SetEmptyText();

			return div;
		},

		_InitPlusMinusButton: function(id)
		{
			var plusMinusButton = $("plus_minus" + id);
			if (plusMinusButton)
			{
				plusMinusButton.onclick = function()
				{
					if (window.isLoading) return;
					if (nodeList[id].childDiv.childNodes.length > 0)
					{
						if (nodeList[id].childDiv.style.display == "none")
						{
							ShowNode(id);
							nodeList[id].childDiv.style.display = "block";
							this.src = iconMinus;
						}
						else
						{
							HideNode(id);
							nodeList[id].childDiv.style.display = "none";
							this.src = iconPlus;
						}
					}
				}
			}
			return plusMinusButton;
		},

		_InitDownButton: function(id)
		{
			var downButton = $("down_button" + id);
			if (downButton)
			{
				downButton.style.cursor = "pointer";
				downButton.src = IconDownEnabled;
				downButton.onclick = function()
				{
					var position = 0;
					for (var i = 0; i < nodeList[id].nodeDiv.parentNode.childNodes.length; i++)
					{
						if (nodeList[id].nodeDiv.parentNode.childNodes[i].hashID == id)
							position = i + 1;
					}
					if (position > 0 && position < nodeList[id].nodeDiv.parentNode.childNodes.length)
					{
						if (window.isLoading) return;
						window.isLoading = true;
						nodeList[id].titleDiv.UnHighlight();

						var nodeUp = nodeList[id].nodeDiv.parentNode.childNodes[position];
						var nodeDown = nodeList[id].nodeDiv;

						JsHttpRequest.query(
							path2Admin+'ajax.php',
							{
								'Action': "SwitchCategories",
								'UpCategoryID': nodeUp.hashID,
								'DownCategoryID': nodeDown.hashID
							},
							function(result, errors)
							{
							    if (!result) return;

							    if (result["SessionExpired"])
								{
									document.location.href = "index.php";
									return;
								}

								if (result["Answer"])
								{
									nodeList[id].nodeDiv.parentNode.insertBefore(nodeUp, nodeDown);
									// Exchange up & down buttons
									ExchangeButtons('up', nodeUp.hashID, nodeDown.hashID);
									ExchangeButtons('down', nodeUp.hashID, nodeDown.hashID);
								}
								else
								{
									alert(GetTranslation("error-moving-category"));
								}
								window.isLoading = false;
							},
							true
						);
					}
				}
			}
			return downButton;
		},

		_InitUpButton: function(id, firstElement)
		{
			var upButton = $("up_button" + id);
			if (upButton)
			{
				if (firstElement)
				{
					upButton.style.cursor = "default";
					upButton.src = IconUpDisabled;
				}
				else
				{
					upButton.style.cursor = "pointer";
					upButton.src = IconUpEnabled;
				}
				upButton.onclick = function()
				{
					var position = 0;
					for (var i = 0; i < nodeList[id].nodeDiv.parentNode.childNodes.length; i++)
					{
						if (nodeList[id].nodeDiv.parentNode.childNodes[i].hashID == id)
							position = i + 1;
					}
					if (position > 1)
					{
						if (window.isLoading) return;
						window.isLoading = true;
						nodeList[id].titleDiv.UnHighlight();

						var nodeUp = nodeList[id].nodeDiv;
						var nodeDown = nodeList[id].nodeDiv.parentNode.childNodes[position - 2];

						JsHttpRequest.query(
							path2Admin+'ajax.php',
							{
								'Action': "SwitchCategories",
								'UpCategoryID': nodeUp.hashID,
								'DownCategoryID': nodeDown.hashID
							},
							function(result, errors)
							{
							    if (!result) return;

							    if (result["SessionExpired"])
								{
									document.location.href = "index.php";
									return;
								}

								if (result["Answer"])
								{
									nodeList[id].nodeDiv.parentNode.insertBefore(nodeUp, nodeDown);
									// Exchange up & down buttons
									ExchangeButtons('up', nodeUp.hashID, nodeDown.hashID);
									ExchangeButtons('down', nodeUp.hashID, nodeDown.hashID);
								}
								else
								{
									alert(GetTranslation("error-moving-category"));
								}
								window.isLoading = false;
							},
							true
						);
					}
				}
			}
			return upButton;
		},

		_InitEditButton: function(id)
		{
			var editButton = $("edit_button" + id);
			if (editButton)
			{
				editButton.onclick = function()
				{
					document.location.href = moduleURL+"&CategoryID="+id;
				}
			}
			return editButton;
		},

		_InitDeleteButton: function(id)
		{
			var deleteButton = $("delete_button" + id);
			if (deleteButton)
			{
				deleteButton.onclick = function()
				{
					if (nodeList[id].itemCount > 0)
					{
						alert(GetTranslation("delete-restricted"));
						return;
					}
					// Form confirmation message
					var confirmMsg = GetTranslation("delete-category-confirm");
					confirmMsg = confirmMsg.replace(/%CategoryTitle%/g, "'" + nodeList[id].jsTitle + "'");
					if (nodeList[id].childDiv.childNodes.length > 0)
					{
						confirmMsg += "\n"+GetTranslation("has-subcategories");
					}
					if (!confirm(confirmMsg))
						return;

					if (window.isLoading) return;
					window.isLoading = true;

					// Hide node & show removing message
					nodeList[id].nodeDiv.style.display = "none";
					var removingDiv = document.createElement("div");
					removingDiv.innerHTML = GetTranslation("removing");
					nodeList[id].nodeDiv.parentNode.insertBefore(removingDiv, nodeList[id].nodeDiv);

					JsHttpRequest.query(
						path2Admin+'ajax.php',
						{
							'Action': "RemoveCategory",
							'CategoryID': id,
							'PageID': pageID
						},
						function(result, errors)
						{
						    if (!result) return;

							if (result["SessionExpired"])
							{
								document.location.href = "index.php";
								return;
							}

							nodeList[id].nodeDiv.parentNode.removeChild(removingDiv);
							if (result["Answer"])
							{
								// Hide parent node if it has no more childs
								if (nodeList[id].nodeDiv.parentNode.childNodes.length == 1 && nodeList[id].parentID > 0)
								{
									nodeList[nodeList[id].parentID].plusMinusButton.src = iconBlank
									HideNode(nodeList[id].parentID);
								}
								nodeList[id].nodeDiv.parentNode.removeChild(nodeList[id].nodeDiv);
							}
							else
							{
								alert(GetTranslation("error-removing-category"));
								nodeList[id].nodeDiv.style.display = "block";
							}
							window.isLoading = false;
						},
						true
					);
				}
			}
			return deleteButton;
		}
	}
})();


