﻿var userFeedValue = escape("$userfeed$");
var userFeedOptionName = "(Add your feed)";
var userFeedEditorID = "__userfeed";
var userFeedInputID = "userfeedurl";

function getService()
{
	if (document.location.pathname.indexOf("/adm/") == 0)
	{
		return '/adm/blocksxml.aspx';
	}
	else
	{
		return '/blocksxml.aspx';
	}
}

function editBlock(element, secID, blockID, settingsID, dataType)
{
	if (element.editor == null)
	{
		var xmlhttp =  new XMLHttpRequest();
		xmlhttp.open('POST', getService(), true);
		xmlhttp.onreadystatechange = function()
		{
			if (xmlhttp.readyState==4 || xmlhttp.readyState=="complete")
			{
				if (xmlhttp.status == 200)
				{
					showEditor(xmlhttp.responseXML, element);
				}
			}
		}
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		var data = 'xml=true&editor=true&type=' + dataType + '&sec_id=' + secID + '&blockid=' + blockID + '&settingsid=' + settingsID;
		xmlhttp.send(data);
	}
}

function showEditor(xml, element)
{	
	var editor = document.createElement("DIV");
	if (xml.documentElement.firstChild == null)
	{
		editor.innerHTML = xml.documentElement.text;
	}
	else
	{
		editor.innerHTML = xml.documentElement.firstChild.nodeValue;
	}
	editor.dataType = xml.documentElement.getAttribute("dataType");
	editor.levelCount = parseInt(xml.documentElement.getAttribute("levelCount"));
	editor.secID = xml.documentElement.getAttribute("secid");
	editor.blockID = xml.documentElement.getAttribute("blockid");
	editor.settingsID = xml.documentElement.getAttribute("settingsid");
	editor.pageID = getBlock(element).getAttribute('pageid');
	editor.editor = editor;
	document.body.appendChild(editor);
	editor.style.position = 'absolute';
	var left = findLeft(element) + element.offsetWidth - 30;
	if (left + editor.offsetWidth > document.body.offsetWidth - 20)
	{
		left = findLeft(element) + element.offsetWidth - editor.offsetWidth - 10;
	}
	editor.style.left = left  + 'px';
	editor.style.top = (findTop(element) + 20) + 'px';
	element.editor = editor;
	editor.onsave = function(sender, edt)
	{
		savePrefs(element, sender.form);
		hideEditor(element, edt);
	}
	editor.oncancel = function(sender, edt)
	{
		hideEditor(element, edt);
	}
	var select = findElements(editor.childNodes, "SELECT");
	for (var i = 1; i < select.length; i++)
	{
		select[i].style.display = 'none';
	}
}

function hideEditor(element, editor)
{
	element.editor = null;
	document.body.removeChild(editor);
}

function onLevelCheck(element)
{
	if (element.selectedIndex >= 0 && element.options[element.selectedIndex].text == userFeedOptionName)
	{
		showUserFeedEditor(element.form.childNodes, true);
	}
	else
	{
		showUserFeedEditor(element.form.childNodes, false);
		var editor = getEditor(element);
		if (editor != null)
		{
			if (element.id == "level_0" || element.id != ("level_" + editor.levelCount))
			{
				var select = findElements(element.form.childNodes, "SELECT");
				for (var i = 0; i < select.length; i++)
				{
					if (select[i] == element)
					{
						if (i + 1 >= select.length || select[i + 1].style.display == "none")
						{
							onLevelChangedCore(element, false);
						}
						break;
					}
				}
			}
		}
	}
}

function showUserFeedEditor(frm, show)
{
	var elements = findElementsByID(frm, userFeedEditorID);
	for (var i = 0; i < elements.length; i++)
	{
		if (show)
		{
			elements[i].style.display = '';
		}
		else
		{
			elements[i].style.display = 'none';
		}
	}
}

function onLevelChanged(element)
{
	if (element.selectedIndex >= 0 && element.options[element.selectedIndex].text == userFeedOptionName)
	{
		showUserFeedEditor(element.form.childNodes, true);
	}
	else
	{
		showUserFeedEditor(element.form.childNodes, false);
	}
	lastLevel = false;
	var editor = getEditor(element);
	if (editor != null)
	{
		var levelCount = editor.levelCount;
		if (element.id.indexOf("level_") == 0)
		{
			current = parseInt(element.id.substring("level_".length));
			if (current != 0 && current >= levelCount)
			{
				lastLevel = true;
			}
		}
	}
	if (!lastLevel)
	{
		onLevelChangedCore(element, true);
	}
}

function onLevelChangedCore(element, updateSelf)
{
	var editor = getEditor(element);
	var xmlhttp =  new XMLHttpRequest();
	xmlhttp.open('POST', getService(), true);
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState==4 || xmlhttp.readyState=="complete")
		{
			if (xmlhttp.status == 200)
			{
				updateEditor(xmlhttp.responseXML, element, updateSelf);
			}
			else
			{
				element.form.submit();
			}
		}
	}
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	var data = 'xml=true';
	if (editor != null)
	{
		data = data + '&type=' + getDataType(editor) + '&pageid=' + editor.pageID;
	}
	data = data + getSelectedValues(element.form, element);
	xmlhttp.send(data);
}

function getDataType(editor)
{
	var dataType = editor.dataType;
	if (dataType == null)
	{
		dataType = editor.getAttribute("dataType");
	}
	return dataType;
}

function savePrefs(element, frm)
{	
	var editor = getEditor(element);
	var xmlhttp =  new XMLHttpRequest();
	xmlhttp.open('POST', getService(), true);
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState==4 || xmlhttp.readyState=="complete")
		{
			if (xmlhttp.status == 200)
			{
				window.alert('Your settings have been saved.');
				updateBlock(xmlhttp.responseXML, element);
			}
			else
			{
				window.alert('An error occurred.');
			}
		}
	}
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	var data = getSelectedValues(frm, null);
	if (editor != null)
	{
		data = data + '&sec_id=' + editor.secID + '&blockid=' + editor.blockID + '&settingsid=' + editor.settingsID;
	}
	document.cookie = 'prefs' + editor.settingsID + '=' + escape(data) + '; expires=Th, 31 Dec 2099 23:59:59 UTC; path=' + document.location.pathname;
	xmlhttp.send('xml=true&save=true' + data + '&prefs' + editor.settingsID + '=' + escape(data));
}

function updateBlock(xml, element)
{
	var block = getBlock(element);
	if (block != null)
	{
		if (xml.documentElement.firstChild == null)
		{
			block.outerHTML = xml.documentElement.text;
		}
		else
		{
			block.outerHTML = xml.documentElement.firstChild.nodeValue;
		}
	}
}

function getBlock(element)
{
	var block = null;
	var parent = element;
	while (parent != null && block == null)
	{
		if (parent.id == 'ctgblock')
		{
			block = parent;
		}
		parent = parent.parentNode;
	}
	return block;
}

function findLeft(element)
{
	var current = 0;
	if (element.offsetParent)
	{
		current = element.offsetLeft;
		while ((element = element.offsetParent) != null)
		{
			current += element.offsetLeft;
		}
	}
	return current;
}

function findTop(element)
{
	var current = 0;
	if (element.offsetParent)
	{
		current = element.offsetTop;
		while ((element = element.offsetParent) != null)
		{
			current += element.offsetTop;
		}
	}
	return current;
}

function getEditor(element)
{
	var editor = null;
	var parent = element;
	while (parent != null && editor == null)
	{
		if (parent.id == "__ctgeditor")
		{
			return parent;
		}
		editor = parent.editor;
		parent = parent.parentNode;
	}
	return editor;
}

function getSelectedValues(frm, element)
{
	var data = '';
	var select = findElements(frm.childNodes, "SELECT");
	var editor = getEditor(frm);
	var levelCount = editor == null ? null : editor.levelCount;
	for (var i = 0; i < select.length; i++)
	{
		if (select[i].style.display == 'none')
		{
			break;
		}
		var val;
		if (select[i].selectedIndex >= 0 && select[i].options[select[i].selectedIndex].text == userFeedOptionName)
		{
			var el = findElementsByID(frm.childNodes, userFeedInputID);
			val = el.length > 0 ? el[0].value : "$null$";
		}
		else
		{
			val = select[i].value;
		}
		data = data + '&' + select[i].name + '=' + val;
		if (select[i] == element)
		{
			break;
		}
		if (levelCount != null && select[i].id == ('level_' + levelCount))
		{
			break;
		}
	}
	return data;
}

function updateEditor(xml, element, updateSelf)
{
	var editor = getEditor(element);
	var count = parseInt(xml.documentElement.getAttribute("levelCount"));
	if (editor != null)
	{
		editor.levelCount = count;
	}
	var levels = xml.documentElement.getElementsByTagName("level");
	var select = findElements(element.form.childNodes, "SELECT");
	for (var i = 0; i < select.length; i++)
	{
		var el = getElement(element.form, "level_" + (i + 1), "SELECT");
		if (el != null)
		{
			var currentValue = el.value;
			if (updateSelf || (element != el))
			{
				el.innerHTML = "";
				while (el.options.length > 0)
				{
					el.remove(0);
				}
			}
			if (i < levels.length)
			{
				if (updateSelf || (element != el))
				{
					var opts =  levels[i].getElementsByTagName("option");
					for (var j = 0; j < opts.length; j++)
					{
						var option = document.createElement("OPTION");
						el.options.add(option);
						var optionText;
						if (opts[j].firstChild == null)
						{
							optionText = opts[j].text;
						}
						else
						{
							optionText = opts[j].firstChild.nodeValue;
						}
						option.appendChild(document.createTextNode(optionText));
						option.value = opts[j].getAttribute("value");
						if (opts[j].getAttribute("selected") == "true")
						{
							option.selected = true;
						}
						/*if (optionText == userFeedOptionName)
						{
							var inp = findElementsByID(element.form.childNodes, userFeedInputID);
							if (inp.length > 0)
							{
								inp[0].value = option.value;
							}
						}*/
					}
				}
			}
		}
	}
	var showAllways = false;
	if (editor != null)
	{
		showAllways = editor.showAllways;
		if (showAllways == null)
		{
			showAllways = editor.getAttribute("showAllways");
		}
		if (showAllways == null)
		{
			showAllways = false;
		}
	}
	var found = false;
	var show = true;
	for (var i = 0; i < select.length; i++)
	{
		if (found)
		{
			if (show)
			{
				select[i].style.display = '';
				show = false;
			}
			else
			{
				if (!showAllways)
				{
					select[i].style.display = 'none';
				}
			}
		}
		else 
		{
			found = select[i] == element;
		}
		if (select[i].id == 'level_' + count)
		{
			show = false;
		}
	}
}

function findElements(elements, tagName)
{
	var ret = new Array();
	var count = 0;
	for (var i = 0; i < elements.length; i++)
	{
		if (elements[i].nodeName.toUpperCase() == tagName.toUpperCase())
		{
			ret[count] = elements[i];
			count++;
		}
		if (elements[i].nodeName.toUpperCase() != "#TEXT")
		{
			var tmp = findElements(elements[i].childNodes, tagName);
			for (var j = 0; j < tmp.length; j++)
			{
				ret[count] = tmp[j];
				count++;
			}
		}
	}
	return ret;
}

function findElementsByID(elements, id)
{
	var ret = new Array();
	var count = 0;
	for (var i = 0; i < elements.length; i++)
	{
		if (elements[i].id == id)
		{
			ret[count] = elements[i];
			count++;
		}
		if (elements[i].nodeName.toUpperCase() != "#TEXT")
		{
			var tmp = findElementsByID(elements[i].childNodes, id);
			for (var j = 0; j < tmp.length; j++)
			{
				ret[count] = tmp[j];
				count++;
			}
		}
	}
	return ret;
}

function getElement(parent, id, tagName)
{
	if (parent.id == id && parent.nodeName.toUpperCase() == tagName)
	{
		return parent;
	}
	var children = parent.childNodes;
	for (var i = 0; i < children.length; i++)
	{
		if (children[i].id == id && children[i].nodeName.toUpperCase() == tagName)
		{
			return children[i];
		}
		var child = getElement(children[i], id, tagName);
		if (child != null)
		{
			return child;
		}
	}
	return null;
}
