/* *********** **
** Url enc/dec **
** *********** */

function encodeUrl(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	return encoded;
}

function decodeUrl(encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
}

/* ****** **
** Cookie **
** ****** */

function getCookieNames()
{
	debugger;
	return document.cookie;
}

function getCookieValue(name)
{
	debugger;
	return "";
}

function setCookieValue(name, value)
{
	debugger;
}

/* *** **
** Url **
** *** */

function getParam(name)
{
	var params;
	var index;
	var result;
 	
	if ((requestedUrl === undefined) || (requestedUrl === null))
	{
	  	params = document.location.search.substring(1, document.location.search.length);
	}
	else
	{
		params = requestedUrl.split("?")[1];
		params = decodeUrl(params);
	}
	params = params.split("&");
	result = "";	
	for (index = 0; index < params.length; index++)
	{
		var parts = params[index].split("=");
		if (parts[0] == name)
		{
			result = parts[1];
			break;
		}
	}
	return result;
}

function getSiteUrl()
{
	var result;
	var result = document.location.protocol + "//" + document.location.host + document.location.pathname;
	while (result.charAt(result.length - 1) != "/")
	{
		result = result.substring(0, result.length - 1);
	}
	result = result.substring(0, result.length - 1);
	return result;
}

function getIndexUrl()
{
	return getSiteUrl() + "/" + getIndexPath();
}

function getIndexPath()
{
	return "index.aspx?";
}

function getBaseUrl()
{
	return getSiteUrl() + "/" + getBasePath();
}

function getBasePath()
{
	return getIndexPath() + "contentId=" + getParam("contentId");
}

function getConsoleUrl()
{
	return getSiteUrl() + "/" + getIndexPath() + "action=console";
}

/* ****** **
** Window **
** ****** */

function windowOpen(url, name, toolbar, status, resizable, dependent, width, height, left, top)
{
	var windowOptions;
	
	windowOptions = "toolbar=" + (toolbar?"yes":"no") + "," +
		"status=" + (status?"yes":"no") + "," +
		"resizable=" + (resizable?"yes":"no") + "," +
		"dependent=" + (dependent?"yes":"no") + "," +
		"width=" + (width?width:"") + "," +
		"height=" + (height?height:"no") + "," +
		"left=" + (left?left:"") + "," +
		"top=" + (top?top:"");
	window.open( url, name, windowOptions);
}

/* ******** **
** Treeview **
** ******** */

function isNull(value)
{
	return ((value === null) || (value === undefined));
}

function toggleTreeviewBranch(node, plusImageSrc, minusImageSrc, hide)
{
	var rowElement;
	var childRows;
	var childIndex;
	
	rowElement = xParent(xParent(node, true), true);
	childRows = xGetElementsByTagName("tr", xParent(rowElement, true));
	// If children are visible or hide is true
	if ((node.src.indexOf(minusImageSrc) >= 0) || hide)
	{
		// Hide children
		for (childIndex = 0; childIndex < childRows.length; childIndex++)
		{
			if ((childRows[childIndex] != rowElement) && (childRows[childIndex].id.indexOf(rowElement.id) === 0))
			{
				var childRowCellImages;
				var imageIndex;
				
				childRows[childIndex].style.display = "none";
				// Recursively hide descendants
				childRowCellImages = xGetElementsByTagName("img", xFirstChild(childRows[childIndex]));
				for (imageIndex = 0; imageIndex < childRowCellImages.length; imageIndex++)
				{
					if (childRowCellImages[imageIndex].src.indexOf(minusImageSrc) >= 0)
					{
						toggleTreeviewBranch(childRowCellImages[imageIndex], plusImageSrc, minusImageSrc, true);
					}
				}
			}
		}
		node.src = plusImageSrc;
	}
	// If children are visible
	else
	{
		// Show children
		for (childIndex = 0; childIndex < childRows.length; childIndex++)
		{
			if ((childRows[childIndex] != rowElement) && (childRows[childIndex].id.indexOf(rowElement.id) === 0))
			{
				var idRest;

				idRest = childRows[childIndex].id.substr(rowElement.id.length + 1);
				if (idRest.indexOf("_") < 0)
				{
					childRows[childIndex].style.display = "";
				}
			}
		}
		node.src = minusImageSrc;
	}
}

function TreeNode(tree, parent, html)
{
	var _id;
	var _tree;
	var _parent;
	var _children;
	var _html;
	
	if (isNull(parent))
	{
		_id = "tree_" + Math.round(Math.random() * 100);
	}
	else
	{
		_id = parent.getId() + "_" + parent.getChildCount();	
	}
	_children = new Array();
	_tree = tree;
	_parent = parent;
	_html = ((isNull(html))?(new Array()):html);
	
	this.getId = function()
	{
		return _id;
	};
	this.getChildCount = function()
	{
		return _children.length;
	};
	this.addChild = function(html)
	{
		var result;
		
		result = new TreeNode(_tree, this, html);
		_children.push(result);
		return result;
	};
	this.getChild = function(index)
	{
		return _children[index];
	};
	this.render = function(current, indent, columnCount)
	{
		var result;
		var columnIndex;
		var childIndex;
		
		if (_parent !== null)
		{
			if (indent === 0)
			{
				current += '<tr id="' + _id + '">';
			}
			else
			{
				current += '<tr id="' + _id + '" style="display: none">';
			}
			for (columnIndex = 0; columnIndex < columnCount; columnIndex++)
			{
				current += '<td class="Treeview">';
				if (columnIndex === 0)
				{
					var indentIndex;
					
					for (indentIndex = 0; indentIndex < indent; indentIndex++)
					{
						current += '<img src="' + _tree.emptyImageSrc + '" alt="" />';
						current += '<img src="' + _tree.emptyImageSrc + '" alt="" />';
					}
					if (_children.length === 0)
					{
						current += '<img src="' + _tree.leafImageSrc + '" alt="" />';
					}
					else
					{
						current += '<img src="' + _tree.plusImageSrc + '" alt="" onclick="toggleTreeviewBranch(this, ' + "'" + _tree.plusImageSrc + "'" + ", '" + _tree.minusImageSrc + "'" + ')" />';
					}
					current += "&nbsp;";
				}
				if (columnIndex < _html.length)
				{
					if ((_html[columnIndex] !== null) && (_html[columnIndex].length !== ""))
					{
						current += _html[columnIndex];
					}
					else
					{
						current += "&nbsp;";
					}
				}
				else
				{
					current += "&nbsp;";
				}
				current += "</td>";
			}
			current += "</tr>";
		}
		for (childIndex = 0; childIndex < _children.length; childIndex++)
		{
			if (_parent === null)
			{
				current = _children[childIndex].render(current, indent, columnCount);	
			}
			else
			{
				current = _children[childIndex].render(current, indent + 1, columnCount);	
			}
		}
		return current;
	};
}

function Tree()
{
	this.root = new TreeNode(this, null);
	this.emptyImageSrc = "";
	this.leafImageSrc = "";
	this.plusImageSrc = "";
	this.minusImageSrc = "";
	
	this.render = function(dataColumnCount, actionColumnCount, columnNames)
	{
		var result;
		var columnIndex;
		var rootNodeChildIndex;
		
		columnCount = dataColumnCount + actionColumnCount;
		result = '<table class="Treeview">';
		if (columnNames !== null)
		{
			result += '<tr id="TreeviewHeader"class="TreeviewHeader">';
			for (columnIndex = 0; columnIndex < dataColumnCount; columnIndex++)
			{
				if (columnIndex < columnNames.length)
				{
					result += '<th class="TreeviewData">';
					if (columnIndex === 0)
					{
						result += '<img src="' + this.emptyImageSrc + '" alt="" />&nbsp;';
					}
					result += columnNames[columnIndex] + "</th>";
				}
				else
				{
					result += '<th class="TreeviewData">&nbsp;</th>';
				}
			}
			for (columnIndex = dataColumnCount; columnIndex < columnCount; columnIndex++)
			{
				if (columnIndex < columnNames.length)
				{
					result += '<th class="TreeviewAction">' + columnNames[columnIndex] + "</th>";
				}
				else
				{
					result += '<th class="TreeviewAction">&nbsp;</th>';
				}
			}
			result += "</tr>";
		}
		result = this.root.render(result, 0, columnCount, columnNames);
		result += "</table>";
		document.write(result);
		// TODO apre tutti i nodi di primo livello
		for (rootNodeChildIndex = 0; rootNodeChildIndex < this.root.getChildCount(); rootNodeChildIndex++)
		{
			var childNode;
			var childRow;
			var childImage;

			childNode = this.root.getChild(rootNodeChildIndex);
			childRow = xGetElementById(childNode.getId());
			childImage = childRow.firstChild.firstChild;
			if (childImage.onclick != null)
			{
				toggleTreeviewBranch(childImage, this.plusImageSrc, this.minusImageSrc, false);
			}
		}  	
		xHeight("TreeviewHeader", 20);
		return result;
		
	};
}

/* ******** **
** Calendar **
** ******** */

var _dynarch_popupCalendar = null;

function calendarCreate(name, value, format)
{
	// TODO format is ignored
	format = "%d/%m/%Y";
	document.write('<input type="text" name="' + name + '" id="' + name + '" size="30" value="' + (value == null ? "" : value) + '" />');
	document.write('<img onclick="return showCalendar(' + "'" + name + "'" + ', ' + "'" + format + "'" + ')" class="Clickable" alt="" name="dateToggler" id="dateToggler_' + name + '" src="Shared.Console/Images/Console/Calendar.gif"/>');
}

function calendarEnable(name, value)
{
	xGetElementById(name).disabled = !value;
	xGetElementById("dateToggler_" + name).disabled = ! value;
}

function selected(cal, date) {
  cal.sel.value = date;
  if (cal.dateClicked)
    cal.callCloseHandler();
}

function closeHandler(cal) {
  cal.hide();
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar

  return false;
}

/* ********* **
** Text Area **
** ********* */

function textareaSelect(inputEl, selStart, selEnd) { 
 if (inputEl.setSelectionRange) { 
  inputEl.focus(); 
  inputEl.setSelectionRange(selStart, selEnd); 
 } else if (inputEl.createTextRange) { 
  var range = inputEl.createTextRange(); 
  range.collapse(true); 
  range.moveEnd('character', selEnd); 
  range.moveStart('character', selStart); 
  range.select(); 
 } 
}

function textareaOnFocus(element)
{
	if (element.value.trim() === "")
	{
		element.value = "";
	}
	textareaSelect(element, element.value.length);
}

/* **** **
** Help **
** **** */

function helpHide()
{
	try
	{
		var helpRows;
		var helpShowImage;
		
		helpRows = new Array();
		helpRows[0] = xGetElementsById("helpRow0");
		helpRows[1] = xGetElementsById("helpRow1");
		for (index = 0; index < helpRows.length; index++)
		{
			helpRows[index].className = "Hidden";
		}
		helpShowImage = xGetElementById("helpShow");
		helpShowImage.className = "Clickable";
	}
	catch(error)
	{
	}
}

function helpShow()
{
	try
	{
		var helpRows;
		var helpShowImage;
		
		helpRows = new Array();
		helpRows[0] = xGetElementsById("helpRow0");
		helpRows[1] = xGetElementsById("helpRow1");
		for (index = 0; index < helpRows.length; index++)
		{
			helpRows[index].className = "";
		}
		helpShowImage = xGetElementById("helpShow");
		helpShowImage.className = "Hidden";
	}
	catch(error)
	{
	}
}

/* ****** **
** Common **
** ****** */

function consoleOnClick()
{
	document.location.href = getConsoleUrl();	
}

function showServerMessage()
{
	try
	{
		if (serverMessage !== "")
		{
			alert(serverMessage);
		}
	}
	catch(error)
	{
	}
}

/* ********** **
** Validation **
** ********** */

function checkValidationResult(result)
{
	if ((result !== null) && (result.length !== 0))
	{
		var message = "";
		for (var index = 0; index < result.length; index++)
		{
			if (message != "")
				message = message + "\n";
			message = message + result[index];
		}
		alert(message);
		return false;
	}
	else
	{
		return true;
	}
}

function validateNotNull(value, invalidMessage, messages)
{
	if ((value === null) || (value === undefined))
	{
		messages[messages.length] = invalidMessage;
		return false;
	}
	return true;
}

function validateStringLength(value, minLength, maxLength, invalidMessage, messages)
{
	if ((value === null) || (value === undefined))
		value = "";
	if (((minLength !== null) && (value.length < minLength)) || ((maxLength !== null) && (value.length > maxLength)))
	{
		messages[messages.length] = invalidMessage;
		return false;
	}
	return true;
}

function validateEMailAddress(str, invalidMessage, messages)
{
	var result = true;
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1)
		result = false;

	if (result && (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr))
		result = false;

	if (result && (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr))
		result = false;

	if (result && (str.indexOf(at,(lat+1))!=-1))
		result = false;

	if (result && (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot))
		result = false;

	if (result && (str.indexOf(dot,(lat+2))==-1))
		result = false
	
	if (result && (str.indexOf(" ")!=-1))
		result = false

	if (!result)
		messages[messages.length] = invalidMessage;
	
	return result;

}

