// JavaScript Document

var doctree = null;

var currentPageID = 0;

var currentOpenPageID = 0;

//$.blockUI({ message: $('#Loading') });
//$.unblockUI();
$().ajaxStop($.unblockUI);

/*
Ext.onReady(function(){
	
	//create tabs
	$("#pageTabs > ul").tabs();
		
	//create doctree
	refreshTree();

});
*/

function blockInput()
{
	$.blockUI({ message: $('#Loading') });	
}

function attachHints()
{
	$(".PagePropertyFieldHint").hover(
		function () { 
			$(this).append($("<span class=\"hint\">"+$(this).attr("hint")+"</span>")); 
		},  
		function () { 
			$(this).find("span:last").remove(); 
		} 
	); 
}


function refreshTree()
{
	$("#tree-div").html("");
	var Tree = Ext.tree;
	
	var root = new Tree.AsyncTreeNode({
		text: 'Your Site',
		draggable:false,
		id:'0',
		icon: 'images/tree/website.gif'
	});
	
	doctree = new Tree.TreePanel({
		animate:false, 
		loader: new Ext.tree.TreeLoader({
			dataUrl:'doctree.php'
		}),
		rootVisible: true,
		enableDD:true,
		root: root,
		renderTo: 'tree-div',
		autoHeight:true,
		autoScroll:true,
		containerScroll:true
	});
	
	doctree.on('contextmenu', 	function(selectedNode,e)
					 			{
									var node = selectedNode;
									node.select();
									var nodeID = node.id;
									var parentID = 0;
									if(nodeID != 0)
										parentID = node.parentNode.id;
										
									var nodeStatus = node.attributes.pagestatus;
									var nodeIsHomePage = node.attributes.ishomepage;
									var nodePath = node.getPath();

									var cMenu = new Ext.menu.Menu();
									
									cMenu.add(new Ext.menu.Item({
										text:"New Page",
										icon:"images/tree/page_add.gif",
										handler:function()
												{
													cMenu.hide();
													newPage(nodeID);
													return;
												}
									}));
									
									if(nodeID != '0')
									{
										cMenu.add(new Ext.menu.Item({
											text:"Edit",
											icon:"images/tree/page_edit.gif",
											handler:function()
													{
														cMenu.hide();
														editPage(nodeID);
														return;
													}
										}));
										
										cMenu.add(new Ext.menu.Item({
											text:"Delete",
											icon:"images/tree/page_delete.gif",
											handler:function()
													{
														cMenu.hide();
														deletePage(nodeID, parentID);
														return;
													}
										}));
										
										if(nodeIsHomePage == 0)
										{
											cMenu.add(new Ext.menu.Item({
												text:"Make Homepage",
												icon:"images/tree/website.gif",
												handler:function()
														{
															cMenu.hide();
															makeHomePage(nodeID);
															return;
														}
											}));
										}
										
										if(nodeStatus == 0)
										{
											cMenu.add(new Ext.menu.Item({
												text:"Make Active",
												icon:"images/tree/page_active.gif",
												handler:function()
														{
															cMenu.hide();
															activatePage(nodeID);
															return;
														}
											}));
										}
										else
										{
											cMenu.add(new Ext.menu.Item({
												text:"Make Inactive",
												icon:"images/tree/page_hide.gif",
												handler:function()
														{
															cMenu.hide();
															hidePage(nodeID);
															return;
														}
											}));
										}
									}
									
									
									
									cMenu.add(new Ext.menu.Item({
										text:"Refresh tree",
										icon:"images/tree/tree_refresh.gif",
										handler:function()
												{
													cMenu.hide();
													refreshTree(nodeID);
													//doctree.selectPath(nodePath);
													return;
												}
									}));
									
									cMenu.showAt(e.getXY());
								});
	
	doctree.on('movenode', 	function(tree, node, oldParent, newParent, index)
							{
								var pageID = node.id;
								var newParentID = newParent.id;
								var oldParentID = oldParent.id;
								var newPageOrder = (index+1);
								$.ajax({
									url: 'doctree.php',
									type:"POST",
									data:
									{
										"action":"updatePageParent",
										"PageID":pageID,
										"NewParentID":newParentID,
										"OldParentID":oldParentID,
										"PageOrder":newPageOrder
									}
								});
							});
	
	if(arguments[0])
	{
		var expandNodeID = arguments[0];
		doctree.on('load', 	function(node)
							{
								var nodeIdToExpand = expandNodeID;
								if(node.id == nodeIdToExpand)
								{
									doctree.selectPath(node.getPath());
									doctree.expandPath(node.getPath());
								}
							});
	}
	
	doctree.expandAll();
	
}

function newPage(nodeID)
{
	var msg = "Are you sure you want to create a new page?\nThe new page will be created as a child of the selected page.";
	if(confirm(msg))
	{
		var newNodeName = prompt('Enter a name for the new content page');
		if(newNodeName && newNodeName.trim() != "")
		{
			newNodeName = newNodeName.trim();
			newNodeName = newNodeName.replace(/[';",_@]/g,"");
			
			blockInput();
			$("#editTab").load("inc_page_edit.php", {"action":"new", "PageName":newNodeName, "parentID":nodeID},
								function()
								{
									refreshTree(currentPageID);
									msgBox("Page created successfully!", "normal");
									return true;
								});
		}
		
	}
}

function editPage(nodeID)
{
	blockInput();
	$("#editTab").load("inc_page_edit.php", {"action":"edit", "pageID":nodeID});
	currentOpenPageID = nodeID;
	
}

function deletePage(nodeID, parentID)
{
	var msg = "WARNING!\nThis will also delete any child pages?\n\nAre you sure you want to delete this page?";
	if(confirm(msg))
	{
		blockInput();
		$("#dummy").load("inc_page_edit.php", {"action":"delete", "pageID":nodeID, "parentID":parentID},
							function()
							{
								refreshTree(currentPageID);
								$("#editTab").load("inc_page_edit.php");
								msgBox("Page deleted!", "warning");
							});
	}
}

function makeHomePage(nodeID)
{
	var msg = "Are you sure you want to make this page\nthe Homepage of the site?";
	if(confirm(msg))
	{
		blockInput();
		$("#dummy").load("inc_page_edit.php", {"action":"makehomepage", "pageID":nodeID},
							function()
							{
								refreshTree(currentPageID);
								msgBox("Page is now the Homepage!", "normal");
								return true;
							});
	}
}

function activatePage(nodeID)
{
	var msg = "Are you sure you want to activate this page?";
	if(confirm(msg))
	{
		blockInput();
		$("#dummy").load("inc_page_edit.php", {"action":"activate", "pageID":nodeID},
							function()
							{
								refreshTree(currentPageID);
								msgBox("Page is now active!", "normal");
								if(currentOpenPageID == currentPageID)
								{
									$("#editTab").load("inc_page_edit.php", {"action":"edit", "pageID":currentPageID});
								}
							});
	}
}

function hidePage(nodeID)
{
	var msg = "Are you sure you want to hide this page?";
	if(confirm(msg))
	{
		blockInput();
		$("#dummy").load("inc_page_edit.php", {"action":"hide", "pageID":nodeID},
							function()
							{
								refreshTree(currentPageID);
								msgBox("Page is now hidden!", "warning");
								if(currentOpenPageID == currentPageID)
								{
									$("#editTab").load("inc_page_edit.php", {"action":"edit", "pageID":currentPageID});
								}
							});
	}
}

/*

FCKEditor related functions

*/

// called on save
function editTabSave(options){
	/*
	options.pageName,
	options.pageID,
	options.pageStatus,
	options.pageContent
	*/
	blockInput();
	$("#dummy").load("inc_page_edit.php",{
			"action":"save",
			"pageName":options.pageName,
			"pageNameSEO":options.pageNameSEO,
			"pageDescription":options.pageDescription,
			"pageStatus":options.pageStatus,
			"pageID":options.pageID,
			"pageContent":options.pageContent
		},
		function()
		{
			refreshTree(currentPageID);
			msgBox("Page saved!", "normal");
			
		}
	);
	
	return false; //this disables default action (submitting the form)
	
}

function msgBox(msg, type)
{
	var box = $("#MessageBox");
	box.html(msg+"<div class=\"clicktoclose\">[close]</div>");
	box.addClass(type);
	var msgHeight = box.height();
	var msgWidth = box.width();
	var windowHeight = $(window).height();
	var windowWidth = $(window).width();
	//.show("slow");
	box.css({left:((windowWidth/2)-(msgWidth/2)), top:((windowHeight/2)-(msgHeight/2))});
	
	box.click(function()
	{
		$(this).stop().fadeOut("fast", function()
										{
											$(this).removeClass(type);
										});
	});
	
	box.fadeIn("fast",function()
					{
						box.animate({opacity: 1.0}, 3000).fadeOut("fast", 	function()
																		   {
																			   box.removeClass(type);
																		   });
						
					});
}

function doLogout()
{
	if(confirm("Are you sure you want to log out?"))
	{
		blockInput();
		$.ajax({
			type:"POST",
			url:"inc_login.php",
			dataType:"json",
			data:{
				dologout:"yes"
			},
			success: function(ret)
			{
				if(ret.success)
				{
					$.getScript("js/loader.php?load="+ret.loader);
				}
				else
				{
					msgBox("Logout failed!", "error");
				}
			}
		});
	}
}

function doLogin(frm)
{
	var uname = frm.Username.value;
	var pword = frm.Password.value;
	
	blockInput();
	$.ajax({
		type:"POST",
		url:"inc_login.php",
		dataType:"json",
		data:{
			dologin:"yes",
			username:uname,
			password:pword
		},
		success: function(ret)
		{
			if(ret.success)
			{
				//alert('its a match');
				$.getScript("js/loader.php?load="+ret.loader);
				/*$("body").fadeOut("slow", 	function()
				{
					$("body").load(ret.loader, function()
					{
						$("body").fadeIn("slow");
					});
				});*/
			}
			else
			{
				//alert('Login failed!');
				msgBox("Login failed!", "error");
			}
		}
	});
	return false;
}

// called when FCKeditor is done starting..
function FCKeditor_OnComplete( editorInstance ){
	var instanceName = editorInstance.Name;
	var linkedForm = editorInstance.LinkedField.form;
	
	switch(instanceName)
	{
		case 'contentEditor':
			linkedForm.onsubmit = 	function (event)
									{
										cleanPageNameSEO(linkedForm.PageNameSEO);
										return editTabSave({
												pageName:linkedForm.PageName.value,
												pageNameSEO:linkedForm.PageNameSEO.value,
												pageDescription:linkedForm.PageDescription.value,
												pageStatus:linkedForm.Status.value,
												pageID:linkedForm.PageID.value,
												pageContent:editorInstance.GetHTML()
										});
									};
			break;
			
		default:
			alert("DP_CMSERROR:_OnComplete\n\nIt appears this is a new module\nfor which a 'Save' action has not been defined.");
			linkedForm.onsubmit = 	function (event)
									{
										return false;
									}
			break;
	}
	
	$("#SaveBtn").click(linkedForm.onsubmit);
}

function savePageContent()
{
	var oEditor = FCKeditorAPI.GetInstance('contentEditor') ;
	var linkedForm = oEditor.LinkedField.form;
	cleanPageNameSEO(linkedForm.PageNameSEO);
	return editTabSave({
			pageName:linkedForm.PageName.value,
			pageNameSEO:linkedForm.PageNameSEO.value,
			pageDescription:linkedForm.PageDescription.value,
			pageStatus:linkedForm.Status.value,
			pageID:linkedForm.PageID.value,
			pageContent:oEditor.GetHTML()
	});
}

function makePageNameSEO(src, target)
{
	target.value = src.value.replace(/([^0-9a-zA-Z]){1,}/gi,"-");
}

function cleanPageNameSEO(src)
{
	src.value = src.value.replace(/^-(\.*)/gi,"$1");
	src.value = src.value.replace(/(\.*)-$/gi,"$1");
}
