if(typeof(Tools) == "undefined")
	Tools = new Object()

Tools.GetInnerText = function(obj)
{
	///http://geekswithblogs.net/timh/archive/2006/01/19/66383.aspx
	if (document.all) // IE;
		return obj.innerText;
	else if (obj.textContent)
		return obj.textContent;
	else
		return "Error: Unknown or unsupported browser"
}

Tools.SetInnerText = function(obj, newValue)
{
	if (document.all) // IE;
		obj.innerText = newValue;
	else if (obj.textContent)
		obj.textContent = newValue;
}

Tools.TextToHtml = function(text)
{
	text = text.replace(/&/g, "&amp;")
	text = text.replace(/</g, "&lt;")
	text = text.replace(/\n/g, "&nbsp;<br/>")
	return text
}

Tools.ShowMask = function(message)
{
    window.onresize = Tools.SetLayerPosition;
    window.onscroll = Tools.SetLayerPosition;
    Tools.SetLayerPosition();

    document.getElementById("masker").style.display = "block"; 
    document.getElementById("progress").style.display = "block"; 
}

Tools.SetProgress = function(message)
{
    Tools.SetInnerText(document.getElementById("ProgressMessage"), message)
}

    Tools.SetSelected = function(selectField, strValue, boolMulti)
    {
		if(typeof(selectField) == "string")
			selectField = document.getElementById(selectField);

		if(selectField.options)
    	{
    		////This is a <select> object
    		options = selectField.options;
    		for(i=0; i < options.length; i++)
    		{
    			if(options[i].value == strValue)
    			{
    				if(boolMulti)
    					options[i].selected = true;
    				else
    					selectField.selectedIndex = i;
    
    				return;
    			}
    			else
    				options[i].selected = false
    		}
    	}
    	else if(selectField.type == "checkbox")
    	{
    		if(new Boolean(strValue) == true)
    			selectField.checked = true
    		else
    			selectField.checked = false
    	}
    	else
    	{
    		////This is a <radio> object
    		for(var i=0; i < selectField.length; i++)
    		{
    			if(selectField[i].value == strValue)
    			{
    				selectField[i].checked = true;
    				return;
    			}
    			else
    				selectField[i].checked = false
    		}
    	
    	}
    }
    
    
    ////////////////////////////////////////////////////////////////////////////////
    //
    // getSelected(selectField) -
    //    Macro for returning the selected string in the input <select> object.
    
    Tools.GetSelected = function(selectField)
    {
		if(typeof(selectField) == "string")
			selectField = document.getElementById(selectField);
			
		if(selectField.options)
		{
	    	return selectField.options[selectField.selectedIndex].value
	    }
	    else
    	{
    		////This is a <radio> object
    		if(typeof(selectField.length) == "undefined")
    			if(selectField.checked)
	    			return selectField.value
	    		else
	    			return ""
    		else
    			for(var i=0; i < selectField.length; i++)
    			{
    				if(selectField[i].checked)
    					return selectField[i].value
    			}

    		return ""
    	}
    }
    


Tools.HideMask = function()
{
    window.onresize = function(){ }
    window.onscroll = function(){ }

    var masker = document.getElementById("masker");
    var progress = document.getElementById("progress");

    masker.style.display = "none"; 
    progress.style.display = "none";
}

Tools.SetLayerPosition = function() 
{
    ///Masker should mask all the screen and scrolled areas:
    
    var shadow = document.getElementById("masker");

	if(typeof window.pageYOffset != "undefined")
	{
		///FireFox
		scrollTop = window.pageYOffset
		scrollLeft = window.pageXOffset
		
		///But this INCLUDES the scrollbar sizes, causing scrollbars to change/flicker during the 
		///masking
		scrollFudge = -30
	}
	else
	{
		//IE
		scrollTop = window.scrollTop
		scrollLeft = document.scrollLeft
		scrollFudge = 0
	}
	
	if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrollTop = window.pageYOffset;
    scrollLeft = window.pageXOffset;
  } else {
    //DOM compliant
    scrollTop = document.body.scrollTop;
    scrollLeft = document.body.scrollLeft;
  }

	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		windowWidth = window.innerWidth;
		windowHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
  
	///Masker (shadow) should fill the entire scrollable area:
    shadow.style.width = windowWidth+ scrollFudge + "px";
    shadow.style.height = windowHeight + scrollFudge + "px";
	shadow.style.left = scrollLeft + "px"
	shadow.style.top = scrollTop + "px"

	///Progress div should be centered but in the current scrolled window area:
    var progress = document.getElementById("progress");
    progress.style.left = parseInt((windowWidth - 200) / 2) + scrollLeft + "px";
    progress.style.top = parseInt((windowHeight - 100) / 2) + scrollTop + "px";
}

Tools.GetUrlParam = function(name)
{
  ///http://www.netlobo.com/url_query_string_javascript.html
  
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}


Tools.strNullFieldMessage = "Please enter a value for #FIELD_NAME#."

Tools.WarnIfBlank = function(element, strFieldName)
{
	if(typeof(element) == "string")
		element = document.getElementById(element);

	if(element.value == "")
	{
	    message = Tools.strNullFieldMessage.replace("#FIELD_NAME#", strFieldName)
		//alert(message)
		if(element.type != "hidden") //could happen in the case of node picker, color picker, etc.
			element.focus()
	    
		if(typeof(AjaxForms) != "undefined")
		    AjaxForms.DisplayNotification("ErrorMessage", message)
	    
		return false
	}
	else
		return true
}

Tools.WarnIfNotPositiveNumber = function(element, strFieldName)
{
	if(typeof(element) == "string")
		element = document.getElementById(element);

	if(element.value == "" || isNaN(parseInt(element.value)) || parseInt(element.value) < 0)
	{
	    message = "Please enter a positive number for " + strFieldName + "."
		alert(message)
		if(element.type != "hidden") //could happen in the case of node picker, color picker, etc.
			element.focus()
	    
		if(typeof(AjaxForms) != "undefined")
		    AjaxForms.DisplayNotification("ErrorMessage", message)
	    
		return false
	}
	else
		return true
}

function showInputError(message)
{
    alert(message)
    AjaxForms.DisplayNotification("ErrorMessage", message)
}

Tools.GetCookie = function(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
    {
		if(!aCrumb[1])
		{
			//alert("returning nothing");
			return ""
		}
		else
		{
			//alert("returning: " + unescape(aCrumb[1]))
			return Tools.URLDecode(aCrumb[1]);
		}
    }
  }

  // a cookie with the requested name does not exist
  return "";
}

Tools.Logout = function()
{	
	Tools.SetProgress('Logging out...'); 

	AjaxForms.DoAjax('login.php', 'Logout=true', function(result)
	{
		AjaxForms.PostInfo("You have been logged out.");
		document.location = "login.php";
	});
}





Tools.URLDecode = function(encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output.replace(/\+/g, " ");
}


Tools.SetCookie = function(sName, sValue)
{
  document.cookie = sName + "=" + escape(sValue) + "; expires=; ; path=/"
}

Tools.DeleteCookie = function( name ) 
    {
        d = new Date()
        document.cookie = name + "=blah; expires=" + d.toGMTString() + "; ; path=/";
    }


	    function closeWindowAndReturn()
    {
		try
		{
    		if(typeof(window.opener) != "undefined")
    			if(!window.opener.closed)
    				window.opener.focus()
		}
		catch(something){ }
		    
    	window.close()
    }
   
Tools.CloseWindowRefreshAndReturn = function(strLocation)
    {
    	// if the window.open reference appends # to the URL, strip it off
    	try
    	{
    		if(typeof(strLocation) == "undefined")
	    		strLocation = new String(window.opener.location.href)
	    	
    		if (strLocation.search('#') > -1)
    			strLocation = strLocation.substring(0,strLocation.search('#'))
    		
    		window.opener.location.href = strLocation
    	}
    	catch(something)
    	{
    		///Possible to get "permission denied" exception if user browsed somewhere
    		// else or parent window was closed.
    	}
    	
    	closeWindowAndReturn()
    }


Tools.Url = new Object()

Tools.Url.GetKeys = function(strURL)
{
	if(typeof(strURL) != "undefined")
		strURL = document.location.href
	
	strQS = Tools.Url.GetParam(null, strURL)
	
	straKeyPairs = strQS.split("&")
	straKeys = new Array()
	for(i=0; i<straKeyPairs.length; i++)
		straKeys.push(straKeyPairs[i].split("=")[0])
	
	return straKeys
}

Tools.Url.GetScriptName = function()
{
    // https://something.com/somewhere/else/script.aspx?q=2&d=2
    // https://something.com/somewhere/else/script.aspx
    // https://something.com/somewhere/else/
    url = document.location.href
    
	qMark = url.indexOf("?")
	if(qMark < 0)
	{
        lastSlash = url.lastIndexOf("/")
        dot = url.lastIndexOf(".")
    }
    else
    {
        lastSlash = url.lastIndexOf("/", qMark-1)
        dot = url.lastIndexOf(".", qMark-1)
    }
    
    if(dot < 0)
        return "Default"
    else
        return url.substring(lastSlash+1, dot)
}

Tools.Url.GetParam = function(strKeyName, strURL)
{
	if(typeof(strURL) == "undefined")
		strURL = document.location.href

	////If the current URL is an <ASP_URL>, this function returns the <value>
	//  associated with the given <name>, strKeyName. Or if strKeyName is
	//  undefined, returns the entire <querystring>
	
	if(!strKeyName)
	{
		iQMark = strURL.indexOf("?")
		
		if(iQMark > 0 && iQMark < strURL.length-1)
		{
			var strReturn = strURL.substr(iQMark+1)
			if(strReturn.indexOf("#") > 0)
				return strReturn.substr(0, strReturn.indexOf("#"))
			else
				return strReturn
		}
		else
			return ""
	}
	
	iKeyPairStart = 1 + strURL.indexOf("?" + strKeyName + "=")
	if(iKeyPairStart == 0)
		iKeyPairStart = 1 + strURL.indexOf("&" + strKeyName + "=")
	
	if(iKeyPairStart == 0)
	{
		//Key not found
		return ""
	}
	else
	{
		strRightPart = strURL.substring(iKeyPairStart, strURL.length)
		iValueStart = 1 + strRightPart.indexOf("=")
		
		if(iValueStart == 0)
		{
			//Malformed URL
			return ""
		}
		
		strRightPart = strRightPart.substring(iValueStart, strRightPart.length)
		
		iAmp = strRightPart.indexOf("&")
		
		if(iAmp == -1)
		{
			// Must be the last key_pair in the querystring.
			if(strRightPart.indexOf("#") > 0)
				return unescape(strRightPart.substr(0, strRightPart.indexOf("#"))).replace(/\+/g, " ")
			else
				return unescape(strRightPart).replace(/\+/g, " ")
		}
		else
		{
			return unescape(strRightPart.substring(0, iAmp)).replace(/\+/g, " ")
		}
	}
}

Tools.Url.ReplaceParam = function(strName, strValue, strURL)
{
	if(typeof(strURL) == "undefined")
		strURL = document.location.href;
		
	////If the current URL is an <ASP_URL>...
	//  - If strName is a <name>, this function replaces the associated
	//    <value> to strName with the new <value>, strValue.
	//  - Otherwise, this function adds a new <key_pair> to the <ASP_URL>
	//    with the given <name> and <value>, strName and strValue.
	//
	//  NOTE: Returns emptystring if the URL is malformed

	strOldValue = Tools.Url.GetParam(strName, strURL)
	
	if(strOldValue == "")
	{
		//No matching pair, so add it:
		if(strValue != "")
		{
			//Add new value to the beginning of the <querystring>:
			iQMark = strURL.indexOf("?")

			if(iQMark == -1)
			{
				strURL = strURL + "?" + escape(strName) + "=" + escape(strValue)
			}
			else
			{
				strRightSide = strURL.substring(iQMark + 1, strURL.length)
				strLeftSide  = strURL.substring(0, iQMark + 1)
				
				strURL = strLeftSide + escape(strName) + "=" + escape(strValue) + "&" + strRightSide
			}
		}
		//else: actually is a delete, so leave unchanged.
	}
	else
	{
		//Replace the existing value:
		iQMark = strURL.indexOf("?")

		iValueStart = strURL.indexOf(escape(strName) + "=") + (escape(strName) + "=").length
		strLeftSide = strURL.substring(0, iValueStart)
		strRightSide = strURL.substring(iValueStart, strURL.length)

		iAmp = strRightPart.indexOf("&")
		
		if(iAmp == -1)
		{
			// Must be the last key_pair in the querystring.
			if(strValue != "")
			{
				strURL = strLeftSide + strValue
			}
			else
			{
				//actually want to delete the <name> from the querystring.
				//also delete the lefthand seperator, either '?' or '&':
				iKeypairStart = strLeftSide.lastIndexOf(escape(strName) + "=")
				strLeftSide = strLeftSide.substring(0, iKeypairStart)
				strURL = strLeftSide
			}
		}
		else
		{
			if(strValue != "")
			{
				strRightSide = strRightSide.substring(iAmp, strRightSide.length)
				strURL = strLeftSide + escape(strValue) + strRightSide
			}
			else
			{
				//actually want to delete the <name> from the querystring.
				//at this point there exists at least one other <key-pair> 
				//to the right. So delete the righthand token, either '?' or
				//'&', as well as this <key-pair>:
				strRightSide = strRightSide.substring(iAmp + 1, strRightSide.length)
				iKeypairStart = strLeftSide.lastIndexOf(escape(strName) + "=")
				strLeftSide = strLeftSide.substring(0, iKeypairStart)
				strURL = strLeftSide + strRightSide
			}
		}
	}

	return strURL
}

EditItemScreen = {};
EditItemScreen._thing = null;
EditItemScreen.DeleteItem = function(thing)
{
	if(!confirm("Really delete this " + thing + "?"))
		return;
	
	EditItemScreen._thing = thing;
	
	AjaxForms.DoAjax(document.location, "Action=Delete", function()
	{
		AjaxForms.PostInfo("The " + EditItemScreen._thing + " has been deleted.");
		///HACKHERE - need to fix script name parser to retain ext
		document.location = Tools.Url.GetScriptName().replace("edit_", "list_") + "s.php";
	});
}
