// JavaScript Document
var hiddenBackgrounds = new Array();
var checked = false;
var htmlViewModule_Editors = new Array();

// Image preload
jQuery("").attr("src", rootPath + "templates/images/text_register_orange.gif");
jQuery("").attr("src", rootPath + "templates/images/text_login_grey.gif");
jQuery("").attr("src", rootPath + "templates/images/text_login_orange.gif");

$(document).ready(function()
{
	// Detect browser autocomplete for username/password
	if (document.loginForm != undefined)
	{
		if (document.loginForm.loginUsername != undefined && document.loginForm.loginUsername.value != "")
			focusText4(document.loginForm.loginUsername);
		
		if (document.loginForm.loginPassword != undefined && document.loginForm.loginPassword.value != "")
			focusText4(document.loginForm.loginPassword);
		
		//checkShowLogin();
	}
	
	if (typeof docReady == 'function')
	{
		docReady();
	}
	
	$('#header_login_button').hover(
	function()
	{
		if (document.loginForm.elements['action'].value == 'register')
		{
			$(this).attr({src: rootPath + "templates/images/text_register_orange.gif"});
		}
		else
		{
			$(this).attr({src: rootPath + "templates/images/text_login_orange.gif"});
		}
	},
	function()
	{
		if (document.loginForm.elements['action'].value == 'register')
		{
			$(this).attr({src: rootPath + "templates/images/text_register_grey.gif"});
		}
		else
		{
			$(this).attr({src: rootPath + "templates/images/text_login_grey.gif"});
		}
	});
	
		
	$('#register_link').hover(
	function ()
	{
		$(this).attr({src: rootPath + "templates/images/text_register_orange.gif"});
	},
	function ()
	{
		$(this).attr({src: rootPath + "templates/images/text_register_grey.gif"});
	});

	
});


String.prototype.htmlEntities = function () {
	return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};

function getBackgroundImage(obj)
{
	if (obj.currentStyle)
	{
		// IE Opera 
		return obj.currentStyle.backgroundImage;
	}
	else
	{
		// Firefox needs the full css code to work 
		return getComputedStyle(obj, '').getPropertyValue('background-image');
	}
}

function hideBackground(id)
{
	var e = document.getElementById(id);
	
	if (e != null && hiddenBackgrounds[id] == undefined)
	{
		// Store image url in global array so that it can be restored
		hiddenBackgrounds[id] = getBackgroundImage(e);
		
		// Remove background
		e.style.backgroundImage = "none";
	}
}

function restoreBackground(id)
{
	var e = document.getElementById(id);
	
	if (e != null)
	{
		if (hiddenBackgrounds[id] != undefined)
		{
			// Restore background
			e.style.backgroundImage = hiddenBackgrounds[id];
			
			// Remove from array
			hiddenBackgrounds[id] = undefined;
		}
	}
}

function hide(id, mode, callback)
{
	var e = document.getElementById(id);
	
	if (e != null)
	{
		if (mode == undefined || mode == 'none')
			$("#" + id).hide('0', callback);
		else if (mode == "slide")
			$("#" + id).slideUp('normal', callback);
		else if (mode == "fade")
			$("#" + id).fadeOut('normal', callback);
	}
}

function show(id, mode, callback)
{
	var e = document.getElementById(id);
	
	if (e != null)
	{
		if (mode == undefined || mode == 'none')
			$("#" + id).show('0', callback);
		else if (mode == "slide")
			$("#" + id).slideDown('normal', callback);
		else if (mode == "fade")
			$("#" + id).fadeIn('normal', callback);
	}
}

function toggle(id, mode, callback)
{
	var e = document.getElementById(id);
	
	if (e.style.display == "none")
		show(id, mode, callback);
	else
		hide(id, mode, callback);
}

function showTextboxBg(textboxId, behindId)
{
	e = document.getElementById(textboxId);
	
	if (e != null)
	{
		// Only show background if textbox is empty
		if (e.value == "")
			show(behindId);
	}
}


function hideDefaultTextboxBg(textboxId)
{
	e = document.getElementById(textboxId);
	
	if (e != null)
	{
		// Only show background if textbox is empty
		if (e.value == "")
			hideBackground(textboxId);
	}
}

function showDefaultTextboxBg(textbox)
{
	// Only show background if textbox is empty
	if (textbox.value == "")
		restoreBackground(textbox.id);
}

function clickBgText4(textboxId)
{
	/*var textbox = document.getElementById(textboxId);
	focusText4(textbox);
	textbox.focus();*/
}

function focusText4(textbox)
{
	var wrapper = textbox.id + "_wrapper";
	hideBackground(wrapper);
}

function blurText4(textbox)
{
	if (textbox.value == "")
	{
		var wrapper = textbox.id + "_wrapper";
		restoreBackground(wrapper);
	}
}

function updateAllDOMFields(theForm)
{
	var inputNodes = getAllFormFields(theForm);
	
	for (x = 0; x < inputNodes.length; x++)
	{
		var theNode = inputNodes[x];
		updateDOMField(theNode);
	} 
}

function getAllFormFields(theForm)
{
	try
	{
		var inputFields = theForm.getElementsByTagName("input");
		var selectFields = theForm.getElementsByTagName("select");
		var textFields = theForm.getElementsByTagName("textarea");
		var array = new Array(inputFields + selectFields + textFields);
		
		for(i = 0; i < array.length; i++)
		{
			for(x = 0; x < inputFields.length; x++)
			{
				array[i] = inputFields[x];
				i++;
			}
			
			for(a = 0; a < selectFields.length; a++)
			{
				array[i] = selectFields[a];
				i++;
			}
			
			for(t = 0; t < textFields.length; t++)
			{
				array[i] = textFields[t];
				i++;
			}
		}
	}
	catch(e)
	{
		alert("Error when evoking getAllFormFields(): \nSomething is probably wrong with the form you passed in\n\n" + e.message);
	}
	
	return array;
}

function updateDOMField(inputField)
{
	// if the inputField ID string has been passed in, get the inputField object
	if (typeof inputField == "string")
	{
		inputField = document.getElementById(inputField);
	}
	
	if (inputField.type == "select-one")
	{
		for (var i = 0; i < inputField.options.length; i++)
		{
			if (i == inputField.selectedIndex)
			{
				inputField.options[inputField.selectedIndex].setAttribute("selected","selected");
			}
		}
	}
	else if (inputField.type == "text")
	{
		inputField.setAttribute("value",inputField.value);
	}
	else if (inputField.type == "textarea")
	{
		inputField.setAttribute("value",inputField.value);
	}
	else if ((inputField.type == "checkbox") || (inputField.type == "radio"))
	{
		if (inputField.checked)
		{
			inputField.setAttribute("checked","checked");
		}
		else
		{
			inputField.removeAttribute("checked");
		}
	}
}


function checkedAll(name, checkbox)
{
	var form = document.getElementById(name);
	
	if (checkbox == undefined)
	{
		if (checked == false)
		{
			checked = true
		}
		else
		{
			checked = false
		}
	}
	else
	{
		checked = checkbox.checked;
	}
	
	for (var i =0; i < form.elements.length; i++) 
	{
		form.elements[i].checked = checked;
	}
}

function noneChecked (name) 
{
	var aa= document.getElementById(name);
	var returnValue = false;
	for (var i =0; i < aa.elements.length; i++) 
	{
	 if (aa.elements[i].checked == true)
	 	returnValue = true;
	}
	if (returnValue == false)
	{
		alert("No items are selected");
		return false;
	}
	else
		return true;
}

String.prototype.replaceAll = function(
	strTarget, // The substring you want to replace
	strSubString // The string you want to replace in.
)
{
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );
	 
	// Keep looping while an instance of the target string
	// still exists in the string.
	while (intIndexOfMatch != -1)
	{
		// Relace out the current instance.
		strText = strText.replace( strTarget, strSubString )
		
		// Get the index of any next matching substring.
		intIndexOfMatch = strText.indexOf( strTarget );
	}
 

	// Return the updated string with ALL the target strings
	// replaced out with the new substring.
	return( strText );
}

function checkShowLogin()
{
	var form = document.loginForm;
	var button = document.getElementById("header_login_button")
	var reg_link = document.getElementById("register_link")
	alteration
	if (document.loginForm.loginUsername == undefined)
	{
		return;
	}
	
	if (document.loginForm.loginUsername.value != "" || document.loginForm.loginPassword.value != "")
	{
		button.src = rootPath + "templates/images/text_login_grey.gif";
		form.elements['action'].value = 'login';
			}
	else
	{
		button.src = rootPath + "templates/images/text_register_grey.gif";
		form.elements['action'].value = 'register';
		
	}
}

function checkLoginSubmit(e)
{
	e = (e) ? e : window.event;
	
	if (e.keyCode == 13)
	{
		if (document.loginForm.loginUsername.value != "")
		{
			hide('behind_login_username');
			hide('behind_login_password');
			document.getElementById("login_submit").focus();
			document.loginForm.submit();
		}
	}
}

function clearValue(id)
{
	document.getElementById(id).value = '';
}

function toggleEditComment(id)
{
	toggle('form' + id,'slide');
	toggle('p' + id,'slide');
}

function outputEditor(editorName, width, height, toolbarSet, maxLength, counterName)
{
	var sBasePath = '/templates/js/fckeditor/';
	
	if (editorName == undefined || editorName == "")
		editorName = "fckeditor1";
	
	if (width == undefined)
		width = 0;
	
	if (height == undefined)
		height = 300;
	
	if (toolbarSet == undefined || toolbarSet == "")
		toolbarSet = 'Basic';
	
	var oFCKeditor = new FCKeditor(editorName);
	oFCKeditor.BasePath	= sBasePath;
	
	var sSkinPath = sBasePath + 'editor/skins/office2003/';
	oFCKeditor.Config['SkinPath'] = sSkinPath;
	oFCKeditor.Config['PreloadImages'] =
		sSkinPath + 'images/toolbar.start.gif' + ';' +
		sSkinPath + 'images/toolbar.end.gif' + ';' +
		sSkinPath + 'images/toolbar.bg.gif' + ';' +
		sSkinPath + 'images/toolbar.buttonarrow.gif' ;
	
	oFCKeditor.Height	= height;
	oFCKeditor.ToolbarSet = toolbarSet;
	
	if (width > 0)
	{
		oFCKeditor.Width = width;
	}
	
	if (maxLength != undefined && counterName != undefined)
	{
		oFCKeditor.Config['MaxLength'] = maxLength;
		oFCKeditor.Config['CounterName'] = counterName;
	}
	
	oFCKeditor.ReplaceTextarea();
}

function submitFormAction(formName, action)
{
	var form = document.getElementsByName(formName);
	
	if (form.length < 1)
	{
		alert("Form not found.");
		return;
	}
	
	form = form[0];
	
	if (form.elements.length > 0)
	{
		for (var e = 0; e < form.elements.length; e++)
		{
			if (form.elements[e].name == 'action')
			{
				form.elements[e].value = action;
				form.submit();
				break;
			}
		}
	}
}

function clearFields(container, recursive, selectFirstDropdownItem)
{
	if (container.childNodes.length == 0)
	{
		return true;
	}
	
	for (var n = 0; n < container.childNodes.length; n++)
	{
		switch (container.childNodes[n].nodeName)
		{
			case "INPUT" :
				if (container.childNodes[n].type == 'text' || container.childNodes[n].type == 'hidden')
				{
					container.childNodes[n].value = "";
				}
				break;
				
			case "SELECT" :
				if (selectFirstDropdownItem)
				{
					container.childNodes[n].selectedIndex = 0;
				}
				else
				{
					container.childNodes[n].value = "";
				}
				break;
			
			case "TEXTAREA" :
				container.childNodes[n].value = "";
				break;
		}
		
		if (recursive)
		{
			if (container.childNodes[n].childNodes.length > 0)
			{
				clearFields(container.childNodes[n], true);
			}
		}
	}
	
	return true;
}

function traverseDOMTree(targetDocument, currentElement, depth)
{
  if (currentElement)
  {
    var j;
    var tagName=currentElement.tagName;
    var nodeName=currentElement.nodeName;
	 var id = currentElement.id;
	 var className = currentElement.className;
	 
    // Prints the node tagName, such as <A>, <IMG>, etc
    if (tagName)
	 {
		out = "&lt;"+currentElement.tagName;
		
		if (id != "")
			out += " id='" + id + "'";
		
		if (className != "")
			out += " class='" + className + "'";
			
		out += "&gt;";
		
      targetDocument.writeln(out);
	 }
    else
	 {
		 val = currentElement.nodeValue;
		 html = val.htmlEntities();
      targetDocument.writeln(nodeName + " (" + html + ")");
	 }

    // Traverse the tree
    var i=0;
    var currentElementChild=currentElement.childNodes[i];
    while (currentElementChild)
    {
      // Formatting code (indent the tree so it looks nice on the screen)
      targetDocument.write("<BR>\n");
      for (j=0; j<depth; j++)
      {
        // &#166 is just a vertical line
        targetDocument.write("&nbsp;&nbsp;&#166");
      }								
      targetDocument.writeln("<BR>");
      for (j=0; j<depth; j++)
      {
        targetDocument.write("&nbsp;&nbsp;&#166");
      }					
      if (tagName)
        targetDocument.write("--");

      // Recursively traverse the tree structure of the child node
      traverseDOMTree(targetDocument, currentElementChild, depth+1);
      i++;
      currentElementChild=currentElement.childNodes[i];
    }
    // The remaining code is mostly for formatting the tree
    targetDocument.writeln("<BR>");
    for (j=0; j<depth-1; j++)
    {
      targetDocument.write("&nbsp;&nbsp;&#166");
    }			
    targetDocument.writeln("&nbsp;&nbsp;");
    if (tagName)
      targetDocument.writeln("&lt;/"+tagName+"&gt;");
  }
}

////////////////////////////////////////////
// This function accepts a DOM element as parameter and prints
// out the DOM tree structure of the element.
////////////////////////////////////////////
function printDOMTree(domElement, destinationWindow)
{
  // Use destination window to print the tree.  If destinationWIndow is
  //   not specified, create a new window and print the tree into that window
  var outputWindow=destinationWindow;
  if (!outputWindow)
    outputWindow=window.open();

  // make a valid html page
  outputWindow.document.open("text/html", "replace");
  outputWindow.document.write("<HTML><HEAD><TITLE>DOM</TITLE></HEAD><BODY>\n");
  outputWindow.document.write("<CODE>\n");
  traverseDOMTree(outputWindow.document, domElement, 1);
  outputWindow.document.write("</CODE>\n");
  outputWindow.document.write("</BODY></HTML>\n");
  
  // Here we must close the document object, otherwise Mozilla browsers 
  //   might keep showing "loading in progress" state.
  outputWindow.document.close();
  
  alert("Complete");
}

function addFriend(username, prefix)
{
	var url = rootPath + "ajax/addfriend.php?username=" + username + "&extra=" + prefix;
	document.getElementById(prefix + 'link_' + username).style.display = "none";
	document.getElementById(prefix + 'loader_' + username).style.display = "";
	loadXMLDoc(url, addFriendComplete, true);
}

function addFriendComplete(xmlDoc)
{
	if (xmlDoc != null)
	{
		var result = getXmlValue(xmlDoc, 'result', '');
		var username = getXmlValue(xmlDoc, 'username', '');
		var extra = getXmlValue(xmlDoc, 'extra', '');
		
		if (result == '' || result == 'Not Authenticated')
		{
			document.location = rootPath + "connectfailed.htm";
			return;
		}
		
		var statusDiv = document.getElementById('feedback_message');
		
		if (result == 'success')
		{
			var newStatus = getXmlValue(xmlDoc, 'new_status', '');
			var message = "";
			var icon = "tick";
			
			switch (newStatus)
			{
				case 'R':
					message = "A connection request was sent to ";
					break;
					
				case 'X':
					message = "Your connection request was rejected by ";
					icon = "cross";
					break;
					
				case 'A':
					message = "You are connected with ";
					break;
			}
			
			var fullName = document.getElementById(extra + icon + '_' + username).alt;
			document.getElementById(extra + icon + '_' + username).alt = message + fullName;
			document.getElementById(extra + icon + '_' + username).title = message + fullName;
			document.getElementById(extra + 'loader_' + username).style.display = "none";
			document.getElementById(extra + icon + '_' + username).style.display = "";
		}
		else
		{
			document.getElementById(extra + 'loader_' + username).style.display = "none";
			document.getElementById(extra + 'link_' + username).style.display = "";
			statusDiv.innerHTML = "<ul><li><span class='error'>There was an error connecting with the member you selected. Please try again later.</span></li></ul>";
			statusDiv.style.display = "";
			document.location = "#top";
		}
	}
}

var menuInterval = null;
var menuOpen = "";

function overMenu(menu)
{
	if (menuOpen != "")
	{
		closeMenu();
	}
	
	clearInterval(menuInterval);
	$("." + menu + "_dropdown").show();
	menuOpen = menu;
}

function setPreviewValue()
{
	document.getElementById("setPreview").value = "yes";
}

function leftMenu()
{
	menuInterval = setInterval(closeMenu, 1000);
}

function closeMenu()
{
	$("." + menuOpen + "_dropdown").hide();
	menuOpen = "";
	clearInterval(menuInterval);
}

function overMenuDropdown(menu)
{
	clearInterval(menuInterval);
}

function leftMenuDropdown(menu)
{
	menuInterval = setInterval(closeMenu, 1000);
}

function loadEditor(textarea, width, height, minWidth, minHeight, toolbar)
{
	CKEDITOR.replace(textarea,
		{
			width: width,
			height: height,
			resize_minWidth: minWidth,
			resize_minHeight: minHeight,
			toolbar : toolbar,
			filebrowserBrowseUrl : '/templates/js/ckfinder/ckfinder.html',
			filebrowserImageBrowseUrl : '/templates/js/ckfinder/ckfinder.html',
			filebrowserFlashBrowseUrl : '/templates/js/ckfinder/ckfinder.html?type=Flash',
			filebrowserUploadUrl : '/templates/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
			filebrowserImageUploadUrl : '/templates/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
			filebrowserFlashUploadUrl : '/templates/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash'
		});
}

function htmlViewModule_Edit(instance, width, height, minWidth, minHeight, toolbar)
{
	var textarea = "module_html_view_" + instance + "_textarea";
	var editDiv = "module_html_view_" + instance + "_edit";
	var viewDiv = "module_html_view_" + instance + "_data";
	
	if (document.getElementById(viewDiv) == null)
	{
		alert(viewDiv + ' - div was not found.');
		return;
	}
	
	if (document.getElementById(editDiv) == null)
	{
		alert(editDiv + ' - div was not found.');
		return;
	}
	
	// Check whether editor has been loaded
	if (htmlViewModule_Editors[instance] == undefined)
	{
		loadEditor(textarea, width, height, minWidth, minHeight, toolbar);
		htmlViewModule_Editors[instance] = 'loaded';
	}
	
	// Toggle divs
	var e = document.getElementById(editDiv);
	
	if (e.style.display == "none")
	{
		//hide(viewDiv, 'none', function() { show(editDiv); });
		show(editDiv);
	}
	else
	{
		//hide(editDiv, 'none', function() { show(viewDiv); });
		hide(editDiv);
	}
}

function headlinesModule_CategoryChanged(instance, dropdown)
{
	var categoryDiv = document.getElementById('module_headlines_' + instance + '-categories');
	var selectedValue = dropdown.options[dropdown.selectedIndex].value;
	var selectedCategoryDiv = null;
	var selectedCategoryDivId = '';
	
	for (var n = 0; n < categoryDiv.childNodes.length; n++)
	{
		var childNode = categoryDiv.childNodes[n];
		
		if (childNode.id)
		{
			var dashPos = childNode.id.indexOf('-');
			
			if (dashPos > 0)
			{
				var afterDash = childNode.id.substr(dashPos + 1);
				
				if (afterDash.substr(0, 9) == 'category_')
				{
					if (childNode.className.indexOf('selected') == -1)
					{
						// This category is NOT selected - hide it
						childNode.style.display = 'none';
					}
					else
					{
						// This is the selected category div
						selectedCategoryDiv = childNode;
						selectedCategoryDivId = childNode.id;
					}
				}
			}
		}
	}
	
	// Select new category
	selectedCategoryDiv.className = 'headline_category';
	var newCategoryDivId = 'module_headlines_' + instance + '-' + selectedValue;
	var newCategoryDiv = document.getElementById(newCategoryDivId);
	newCategoryDiv.className = 'headline_category selected';
	
	// Fade out currently selected category
	$('#' + selectedCategoryDivId).fadeOut(125, function()
	{
		$('#' + newCategoryDivId).fadeIn(125);
	});
}

function followingModule_StopFollowing(instance, institution)
{
	var form = document.forms['followingForm_' + instance];
	form.institution.value = institution;
	form.submit();
}