// Make function callable on document load
if (document.all)
	document.attachEvent("onreadystatechange", OnCategoryTreeInit);
else
	window.addEventListener("load", OnCategoryTreeInit, false);

// Called when the document has been loaded.
function OnCategoryTreeInit()
{
	if (!document.readyState || document.readyState=="complete")
	{
		// Check if a filter was pre-selected
		var selElement = document.getElementById("FilterCategories");
		if (SelectedFilter && SelectedFilter.length)
		{
			for (var i = 0; i<selElement.options.length && selElement.options[i].value!=SelectedFilter; i++);
			if (i<selElement.options.length)
			{
				selElement.selectedIndex = i;
				OnCategoryTreeFilter(selElement);
			}
		}
		else if (selElement.options.length>0 && selElement.options[0].value.length>0)
		{
			OnCategoryTreeFilter(selElement);
		}
	}
}

// Store the currently selected folder
var CurrentCategoryTreeSelected = null;

// Called when user clicks on a folder
function OnCategoryTreeExpand(obj)
{
	var row = GetParentRow(obj);
	if (row!=null)
	{
		// Remember levels before finding all sub items in the tree
		var level = parseInt(row.getAttribute("level"));
		var expandLevel = level+1;
		var showExpanded = row.getAttribute("ExpandedBelow")!="true";
		row.setAttribute("ExpandedBelow", showExpanded ? "true":"false");
		
		// Selection highlighting
		if (CurrentCategoryTreeSelected!=null)
		{
			if (CurrentCategoryTreeSelected.prevClass)
				CurrentCategoryTreeSelected.className = CurrentCategoryTreeSelected.prevClass;
			else
				CurrentCategoryTreeSelected.removeAttribute("className");
		}
		CurrentCategoryTreeSelected = row;
		if (row.className)
			CurrentCategoryTreeSelected.prevClass = row.className;
		CurrentCategoryTreeSelected.className = "categoryTreeSelected";
		
		// Remember the current selection in input field (used for searching options)
		var selCategory = document.getElementById("CategoryTreeSelectedId");
		if (selCategory)
			selCategory.value = CurrentCategoryTreeSelected.getAttribute("CategoryId");

		// Go through all sub items in the tree, that is all rows who's level is larger than
		// the clicked row's.
		row = row.nextSibling;
		while (row!=null && (row.tagName!="TR" || parseInt(row.getAttribute("level"))>level))
		{
			// Check if this row should be set
			if (row.tagName=="TR" && ((showExpanded && parseInt(row.getAttribute("level"))==expandLevel) 
				|| (!showExpanded && parseInt(row.getAttribute("level"))>=expandLevel)))
			{
				if (showExpanded && row.getAttribute("Visible")=="true")
					row.style.display = "";
				else
					row.style.display = "none";
				row.setAttribute("Expanded", showExpanded ? "true":"false");
				row.removeAttribute("ExpandedBelow");
			}
			row = row.nextSibling;
		}
	}
}

// Called when a checkbox is clicked
function OnCategoryTreeSelect(obj)
{
	var row = GetParentRow(obj);
	var notAll = false;
	
	// Check if a folder was clicked, which means all sub items will be selected
	if (row.getAttribute("ResourceId")==null)
	{
		// Go through everything below this folder and select every item found
		var level = parseInt(row.getAttribute("level"));
		row = row.nextSibling;
		while (row!=null && (row.tagName!="TR" || parseInt(row.getAttribute("level"))>level))
		{
			var checkbox = GetChildInput(row, "checkbox");
			if (checkbox!=null && checkbox.checked!=obj.checked && row.getAttribute("ResourceId")!=null
				&& row.getAttribute("Visible")=="true")
			{
				if (!CategoryTreeSelectDocument(row, obj.checked))
				{
					notAll = true;
					checkbox = null;
				}
			}
			if (checkbox!=null)
			{
				checkbox.checked = obj.checked;
			}
			row = row.nextSibling;
		}
	}
	else
	{
		// A single document was clicked
		if (row.getAttribute("Visible")=="true")
		{
			if (!CategoryTreeSelectDocument(row, obj.checked))
			{
				obj.checked = false;
				notAll = true;
			}
		}
	}
	if (notAll)
	{
		alert(TooMuchMessage);
	}
}

// Call to select or deselect a document
var CategoryTreeTotalSize = 0;
var CategoryTreeTotalCount = 0;
var CategoryTreeSelection = new Array();
var CategoryTreeSelectionRows = new Array();
function CategoryTreeSelectDocument(row, isSelected)
{
	if (isSelected)
	{
		var size = parseInt(row.getAttribute("Size"));
		if ((CategoryTreeTotalSize+size)>=CategoryTreeMaxSize || CategoryTreeTotalCount==CategoryTreeMaxCount)
		{
			return false;
		}
		CategoryTreeTotalSize += size;
		CategoryTreeTotalCount++;
		CategoryTreeSelection.push(row.getAttribute("ResourceId"));
		CategoryTreeSelectionRows.push(row);
	}
	else
	{
		CategoryTreeTotalSize -= parseInt(row.getAttribute("Size"));
		CategoryTreeTotalCount--;
		
		for (var i = 0; i<CategoryTreeSelection.length && CategoryTreeSelection[i]!=row.getAttribute("ResourceId"); i++);
		if (i<CategoryTreeSelection.length)
		{
			CategoryTreeSelection.splice(i, 1);
			CategoryTreeSelectionRows.splice(i, 1);
		}
	}
	return true;
}

// Called when a document is clicked
function OnCategoryTreeDocument(obj)
{
	var row = GetParentRow(obj);
	if (row!=null)
	{
		// Find td where iframe should be located
		var tdFrame = document.getElementById("tdDocumentFrame");
		var tdWebPage = document.getElementById("tdWebPage");
		var openInWindowCheckBox = document.getElementById("OpenInWindow");
		
		// Find iframe
		var frame = document.getElementById("DocumentFrame");
		if (frame==null || (openInWindowCheckBox!=null && openInWindowCheckBox.checked))
		{
			window.open("/"+row.getAttribute("ResourceId"), "_blank", "menubar=yes,resizable=yes,scrollbars=yes,toolbar=yes");
		}
		else
		{
			// Turn off webpage and turn in documentframe
			if (tdFrame && tdFrame.style) tdFrame.style.display = "";
			if (tdWebPage && tdWebPage.style) tdWebPage.style.display = "none";
			
			frame.src = "/"+row.getAttribute("ResourceId");
			frame.style.display = "";
		}
		
		GoogleLog(row.getAttribute("ResourceId"), row.cells[1].title, row.getAttribute("FileType"));
	}
}

// Find first parent that is a row object
function GetParentRow(row)
{
	while (row!=null && row.tagName!="TR")
	{
		row = row.parentNode;
	}
	return row;
}

function GetChildRow(el)
{
	el = el.firstChild;
	while (el != null)
	{
		if (el.tagName && el.tagName == "TR")
			return el;
		else
		{
			var found = GetChildRow(el);
			if (found!=null)
				return found;
		}
		el = el.nextSibling;
	}
	return null;
}

// Return the first child element of tag input with type set to typeName.
function GetChildInput(obj, typeName)
{
	for (var i = 0; i<obj.childNodes.length; i++)
	{
		var child  = obj.childNodes[i];
		if (child.tagName && child.tagName=="INPUT" && child.type==typeName)
		{
			return child;
		}
		else
		{
			child = GetChildInput(child, typeName);
			if (child!=null)
				return child;
		}
	}
	return null;
}

// Called for every row that the mouse moves in over
function OnMouseOver(row)
{
	row.style.backgroundColor = "#EEEEEE";
}

// Called for every row that the mouse leaves
function OnMouseOut(row)
{
	row.style.backgroundColor = "";
}

// Call in order to download all selected files into a zip file.
function OpenCatalogTreeZip()
{
	if (CategoryTreeSelection.length==0)
	{
		alert(NoDocumentsSelectedMessage);
		return;
	}
	var url = "/common/downloadzip.aspx?id=";
	for (var i = 0; i<CategoryTreeSelection.length; i++)
	{
		if (i>0)
			url += ",";
		url += CategoryTreeSelection[i];

		var row = GetChildRow(CategoryTreeSelectionRows[i]);
		if (row!=null)
			GoogleLog(row.getAttribute("ResourceId"), row.cells[1].title, row.getAttribute("FileType"));
	}
	window.location.href = url;
}

// Call in order to show form before e-mailing a zip file of the selected documents
function MailCatalogTreeZip()
{
	// Has any document been selected?
	if ( CategoryTreeSelection.length == 0 )
	{
		// No, so notify the user about this by using an alert
		alert(NoDocumentsSelectedMessage);
		
		// Return to cancel further processing
		return;
	}
	
	// Save URL leading to the page that will contain the e-mail form
	var url = "/common/emailzip.aspx?lang=" + LanguageId + "&siteid=" + SiteId + "&id=";
	
	// Process all possible categories that have been choosen
	for ( var currentCategory = 0; currentCategory < CategoryTreeSelection.length; currentCategory++ )
	{
		// Is this the first category being processed?
		if ( currentCategory > 0 )
		{
			// No, so append a ',' to the URL (the URL will 
			// look something like this: cat1,cat2,cat3...)
			url += ",";
		}
			
		// Append the resource ID to the query string
		url += CategoryTreeSelection[currentCategory];
	}
	
	// The pop-up window's width and height
	var argWidth = 400;	
	var argHeight = 400;
	
	// The pop-up window's starting X and Y
	var argLeft = (screen.width / 2) - (argWidth / 2);	
	var argTop = (screen.height / 2) - (argHeight / 2);
	
	// Local variable for holding additional arguments
	// sent to the open-method of the window-object
	var additionalArguments = "";
	
	// Among other things, the additional arguments make sure
	// the pop-up window appears in the center of the screen
	additionalArguments = "width=" + argWidth + ",height=" + argHeight + ",left=" + argLeft + ",top=" + argTop + ",resizable=yes,toolbar=no,status=no";
	
	// Open, or pop-up, window
	window.open(url, '_MailCatalogTreeZip', additionalArguments);
}

// Called when the filter choice is changed from the drop down.
function OnCategoryTreeFilter(select)
{
	// Check through and set Visible attribute for all documents
	var filterCategoryId = select.options[select.selectedIndex].value;
	if (filterCategoryId=="*")
		filterCategoryId = "";
	
	// Special case where we assume no value and staring with "-" (separator) is the same as 'all'
	if (filterCategoryId=="" && select.options[select.selectedIndex].text.charAt(0)=='-')
	{
		// Find other option that has an empty value
		for (var i = 0; i<select.options.length; i++)
		{
			if (select.options[i].value=="" && select.options[i].text.charAt(0)!='-')
			{
				select.selectedIndex = i;
				break;
			}
		}
	}
	
	var tree = document.getElementById("CategoryTree");
	for (var i = 0; i<tree.rows.length; i++)
	{
		var row = tree.rows[i]; 
		
		// Check if this folder or document should be visible
		var show = false;
		if (filterCategoryId=="" || (","+row.getAttribute("Categories")+",").indexOf(","+filterCategoryId+",")>=0)
		{
			show = true;
		}
		
		if (show && row.getAttribute("Visible")!="true")
		{
			// Show after being hidden
			row.setAttribute("Visible", "true");
			if (row.style.display=="none" && row.getAttribute("Expanded")=="true")
			{
				row.style.display = "";
			}
		}
		else if (!show && row.getAttribute("Visible")=="true")
		{
			// Hide after being shown
			row.setAttribute("Visible", "false");
			if (row.style.display=="")
			{
				row.style.display = "none";
			}
			
			// Remove document as selected
			var checkbox = GetChildInput(row, "checkbox");
			if (checkbox!=null && checkbox.checked)
			{
				checkbox.click();
			}
		}
	}
}
// Called when the filter choice is changed from the BUTTONS /(FH)
function OnCategoryTreeFilterBtn(select)
{
	// Check through and set Visible attribute for all documents
	var filterCategoryId = select;
	if (filterCategoryId=="*")
		filterCategoryId = "";
	
	// Special case where we assume no value and staring with "-" (separator) is the same as 'all'
	if (filterCategoryId=="" && select=='-')
	{
		// Find other option that has an empty value
		for (var i = 0; i<select.options.length; i++)
		{
			if (select.options[i].value=="" && select.options[i].text.charAt(0)!='-')
			{
				select.selectedIndex = i;
				break;
			}
		}
	}
	
	var tree = document.getElementById("CategoryTree");
	for (var i = 0; i<tree.rows.length; i++)
	{
		var row = tree.rows[i];
		
		// Check if this folder or document should be visible
		var show = false;
		if (filterCategoryId=="" || (","+row.getAttribute("Categories")+",").indexOf(","+filterCategoryId+",")>=0)
		{
			show = true;
		}
		
		if (show && row.getAttribute("Visible")!="true")
		{
			// Show after being hidden
			row.setAttribute("Visible", "true");
			if (row.style.display=="none" && row.getAttribute("Expanded")=="true")
			{
				row.style.display = "";
			}
		}
		else if (!show && row.getAttribute("Visible")=="true")
		{
			// Hide after being shown
			row.setAttribute("Visible", "false");
			if (row.style.display=="")
			{
				row.style.display = "none";
			}
			
			// Remove document as selected
			var checkbox = GetChildInput(row, "checkbox");
			if (checkbox!=null && checkbox.checked)
			{
				checkbox.click();
			}
		}
	}
}