ns4=(document.layers)?1:0;
ie4=(document.all)?1:0;

if (!String.prototype.endsWith) 
{
	String.prototype.endsWith = function(suffix) 
	{
		var startPos = this.length - suffix.length;
		if (startPos < 0) 
		{
			return false;
		}
		return (this.lastIndexOf(suffix, startPos) == startPos);
	};
}

function checkSlaveControlVisibility(masterId, slaveId)
{
	master = document.getElementById(masterId);
	master.value ? $('#' + slaveId + '_tr').hide() : $('#' + slaveId + '_tr').show();
}

var preDuplicateDetachers = [];
var contentDuplicateProcessors = [];
var postDuplicateConnectors = [];

function duplicateControl(mainId, mainName)
{
	mainRow = document.getElementById(mainId + '_tr');
	if (mainRow != null)
	{
		for (i = 0; i < preDuplicateDetachers.length; i++)
		{
			preDuplicateDetachers[i](mainId, mainName, mainRow);
		}
		
		table = mainRow.parentNode;
		rowCount = table.rows.length;
		newRow = table.insertRow(rowCount - 1);
		if ($(mainRow).attr('class'))
		{
			$(newRow).attr('class', $(mainRow).attr('class'));
		}
		if ($(mainRow).attr('style'))
		{
			$(newRow).attr('style', $(mainRow).attr('style'));
		}
		if ($(mainRow).attr('title'))
		{
			$(newRow).attr('title', $(mainRow).attr('title'));
		}
		
		newName = mainName;
		idx = newName.lastIndexOf(']');
		idx1 = newName.lastIndexOf('[');
		newIdx = (rowCount - 1).toString();
		newName = newName.substring(0, idx1 + 1) + newIdx + newName.substring(idx);
		newId = newName.replace(/\[|\]/g, '_');
		
		htmlCode = mainRow.innerHTML;
		regexpName = mainName.replace(/\[/g, '\\[');
		regexpName = regexpName.replace(/\]/g, '\\]');
		htmlCode = htmlCode.replace(new RegExp(regexpName, 'g'), newName);
		htmlCode = htmlCode.replace(new RegExp(mainId, 'g'), newId);
		
		for (i = 0; i < contentDuplicateProcessors.length; i++)
		{
			htmlCode = contentDuplicateProcessors[i](mainId, mainName, mainRow, newId, newName, newRow, newIdx, htmlCode);
		}
		
		newRow.innerHTML = htmlCode;
		newRow.id = newId + '_tr';
		
		for (i = 0; i < postDuplicateConnectors.length; i++)
		{
			postDuplicateConnectors[i](mainId, mainName, mainRow, newId, newName, newRow);
		}
	}
}

function fillNLS(idBase)
{
	var id = idBase + '_' + currentLanguage;
	var tinyInst = getTinyMCEControlInstance(id);
	var data = tinyInst != null ? tinyInst.getContent() : document.getElementById(id).value;
	titleDataSrc = document.getElementById(id + '_title');
	
	for (i = 0; i < langs.length; i++)
	{
		if (langs[i] != currentLanguage)
		{
			id = idBase + '_' + langs[i];
			//TinyMCE automatically handles data change
			document.getElementById(id).value = data;
			titleData = document.getElementById(id + '_title');
			if (titleDataSrc != null && titleData != null)
			{
				titleData.innerHTML = titleDataSrc.innerHTML;
			}
		}
	}
}

function findClass(str)
{
	if (document.getElementsByClassName)
	{
		return document.getElementsByClassName(str);
	}
	var list = new Array();
	var nodes = document.getElementsByTagName('*')
	for (i = 0; i<nodes.length; i++)
	{
		if (nodes[i].className.indexOf(str) >= 0)
		{
			list.push(nodes[i]);
		}
	}
	return list;
}

function switchLanguageTo(targetLang)
{
	currentLanguage = targetLang;
	// two parts in order to fix the fucking IE issue: IE can't handle changes of style.display to 'none' or 'inline' in the same loop
	for (i = 0; i < langs.length; i++)
	{
		if (langs[i] != targetLang)
		{
			elements = findClass('ml_' + langs[i]);
			for (j = 0; j < elements.length; j++)
			{
				var id = elements[j].id;
				var tinyInst = getTinyMCEControlInstance(id);
				if (tinyInst != null)
				{
					tinyInst.hide();
					//Now an original editor instance will be shown. So, just continue execution in the default way. 
				}
				elements[j].style.display = 'none';
			}
		}
	}
	elements = findClass('language_tab');
	for (j = 0; j < elements.length; j++)
	{
		elements[j].className = elements[j].id == ('language_tab_' + targetLang) ? (elements[j].className + ' current_lang_tab') : elements[j].className.replace(' current_lang_tab', '');
	}
	
	elements = findClass('ml_' + targetLang);
	for (j = 0; j < elements.length; j++)
	{
		var id = elements[j].id;
		var tinyInst = getTinyMCEControlInstance(id);
		if (tinyInst != null)
		{
			tinyInst.show();
		}
		else
		{
			elements[j].style.display = 'inline';
		}
	}
}

function getTinyMCEControlInstance(id)
{
	if (typeof(tinyMCE) !== 'undefined')
	{
		return tinyMCE.get(id);
	}
	return null;
}

function addParameter(url, formName, fieldName)
{
	if (typeof(document.forms[formName]) == 'undefined' || 
		typeof(document.forms[formName].elements[fieldName]) == 'undefined')
	{
		return url;
	}
	var elt = document.forms[formName].elements[fieldName];
	var first = true;
	$(elt).each(function ()
	{
		if (!$(this).attr('disabled'))
		{
			url = addParameterImpl(url, $(this), fieldName, first);
			first = false;
		}
	});
	return url;
}

function addParameterImpl(url, elt, fieldName, first)
{
	var value = $(elt).val();
	if ($(elt).attr('type') == "checkbox" || $(elt).attr('type') == "radio")
	{
		if (!$(elt).attr('checked'))
		{
			return url;
		}
		value = fieldName + '=' + (value.length > 0 ? value : "on");
	}
	else if (value.length > 0)
	{
		value = fieldName + '=' + value;
	}

	while (first)
	{
		var idx = url.indexOf('?' + fieldName);
		if (idx == -1 && (idx = url.indexOf('&' + fieldName)) == -1)
		{
			break;
		}
		var toIdx = url.indexOf('&', idx + 1);
		url = url.substring(0, idx + 1) + (toIdx == -1 ? '' : url.substring(toIdx + 1));
	}
	if (value.length > 0)
	{
		url += (url.indexOf('?') == -1 ? '?' : '&') + value;
	}
	return url;
}

function addParameters(url, formName, fieldNames)
{
	for (i = 0; i < fieldNames.length; i++)
	{
		url = addParameter(url, formName, fieldNames[i]);
	}
	return url;
}

function checkPasswd(form, emptiness)
{
	if (emptiness === undefined) 
	{
		emptiness = true;
	}

	if (form.passwd.value != form.passwd2.value || ((form.passwd.value == "" || form.passwd2.value == "") && !emptiness))
	{
		alert("Пароли не совпадают, либо пусты. Пожалуйста повторите ввод.");
		return false;
	}
	return true;
}

function setCheckedState(expression, flag)
{
	$(expression).each(function ()
	{
		if ($(this).attr('type') == "checkbox")
		{
			$(this).attr('checked', flag);
		}
	});
}

function countSelectedByName(expression, name)
{
	var counter = 0;
	$(expression).each(function ()
	{
		if ($(this).attr('type') == "checkbox" && $(this).attr('checked') && (name == null || $(this).attr('name') == name))
		{
			counter++;
		}
	});
	return counter;
}

function countSelected(expression)
{
	return countSelectedByName(expression, null);
}

function checkRangeField(obj)
{
	var re = /^(\b[0-9]+\.([0-9]+\b)?|\.[0-9]+\b)$/;

	if (!re.test(obj.value))
	{
		var str = obj.value;
		var isContainPoint = false;
		var temp = '';
		for (i=0; i<=str.length - 1; i++)
		{
			if(parseInt(str.charAt(i)) || parseInt(str.charAt(i)) === 0)
			{
				temp += str.charAt(i);
			}
			else if(str.charAt(i)=="." && isContainPoint == false)
			{
				temp += str.charAt(i);
				isContainPoint = true;
			}
		}
		obj.value = temp;
	}
}

function performGroupAction(formName, inputSelectorFunc)
{
	var form = document.forms[formName];

	$(form).css('display', 'none');
	
	var leavePage = inputSelectorFunc(function (input)
	{
		//NOTE: no support for upload forms
		$(form).append($(input).clone());
	});

	if (leavePage)
	{
		form.submit();
	}
	else
	{
		doAjaxSubmit(form);
	}
}

function addInputValueToForm(formSelector, inputSelector)
{
	if (($(inputSelector).attr('type') == "checkbox" || $(inputSelector).attr('type') == "radio") && !$(inputSelector).attr('checked'))
	{
		return;
	}
	var name = $(inputSelector).attr('name');
	var value = $(inputSelector).val();
	$(formSelector).append('<input type="hidden" name="' + name + '" value="' + value + '"/>');
}

function doAjaxSubmit(form)
{
	$(form).append('<input type="hidden" name="event" value="ajax"/>');
	$.ajax(
	{
		type: 'post',
		url: $(form).attr('action'),
		data: $(form).serialize(),
		success: function (data, textStatus, request)
		{
			window.location.reload();
		}
		//NOTE: no support for upload forms
		//contentTypeString: $(form).attr('enctype') or 'application/x-www-form-urlencoded' by default
	});
}

function selectRow(row)
{
	if (row.className.indexOf("active") != 0)
	{
		row.className += " selected";
	}
}

function deselectRow(row)
{
	if (row.className.indexOf("active") != 0)
	{
		row.className = row.className.substr(0 , row.className.indexOf(" selected"));
	}
}

function fetchAutocompleteJSONData(url, request, response)
{
	$.ajax({
		url: url,
		dataType: 'json',
		data: {term: request.term},
		success: function (data, status)
		{
			response($.map(data, function (item)
			{
				if (typeof(item.label) !== 'undefined' && item.label != null && item.label != '')
				{
					return {
						label: item.label, 
						value: item.label,
						key: item.id
					};
				}
			}));
		}
	});
}

function initializeControlDependencies(startNode, setListeners)
{
	revalidateDependencies();
	if (startNode != null)
	{
		if (setListeners)
		{
			$(startNode).find('.dmc').bind('change', revalidateDependencies);
		}
	}
	else
	{
		if (setListeners)
		{
			$('.dmc').bind('change', revalidateDependencies);
		}
		contentDuplicateProcessors.push(dependencyContentDuplicateProcessor);
		postDuplicateConnectors.push(function (mainId, mainName, mainRow, newId, newName, newRow)
		{
			initializeControlDependencies(newRow, setListeners);
		});
	}
}

function dependencyContentDuplicateProcessor(mainId, mainName, mainRow, newId, newName, newRow, newIdx, htmlCode)
{
	if ($(newRow).attr('class'))
	{
		$(newRow).attr('class', $(newRow).attr('class').replace(/(dg\d+i)\d+/gi, function (str, match1, offset, s)
		{
			return match1 + newIdx;
		}))
	}
	htmlCode = htmlCode.replace(/(dg\d+i)\d+/gi, function (str, match1, offset, s)
	{
		return match1 + newIdx;
	});
	return htmlCode;
}

function revalidateDependencies(step)
{
	var actionTaken = false;
	$('.dmf').each(function ()
	{
		var dmfClass = $(this).attr('class');
		var dgiReg = /dg(\d+)i(\d+)/gi;
		var dgiId = dgiReg.exec(dmfClass);
		var dvaFound = false;
		var dvaReg = /dva(\d+)/gi;
		var enable = false;
		var stateChanged = false;
		while ((dvaId = dvaReg.exec(dmfClass)) != null)
		{
			dvaFound = true;
			$('.dvd' + dvaId[1]).each(function ()
			{
				var skip = false;
				if (dgiId != null)
				{
					var ctrl = $(this).is('option') ? $(this).parent() : this;
					var tDmfClass = $(ctrl).attr('class');
					var dgiReg = /dg(\d+)i(\d+)/gi;
					if ((tDgiId = dgiReg.exec(tDmfClass)) != null && dgiId[1] == tDgiId[1] && dgiId[2] != tDgiId[2])
					{
						skip = true;
					}
				}
				if (!skip)
				{
					stateChanged = true;
					enable |= isDependencyEnabled(this) && ($(this).attr('checked') || $(this).attr('selected'));
				}
			});
		}
		if (stateChanged && isDependencyCouldBeChanged(this) && (isDependencyEnabled(this) != enable))
		{
			changeDependencyState(this, !enable);
			actionTaken = true;
		}
		if (!dvaFound)
		{
			var daReg = /da(\d+)/gi;
			while ((daId = daReg.exec(dmfClass)) != null)
			{
				var enable = false;
				var stateChanged = false;
				$('.dd' + daId[1]).each(function ()
				{
					var skip = false;
					if (dgiId != null)
					{
						var tDmfClass = $(this).attr('class');
						var dgiReg = /dg(\d+)i(\d+)/gi;
						if ((tDgiId = dgiReg.exec(tDmfClass)) != null && dgiId[1] == tDgiId[1] && dgiId[2] != tDgiId[2])
						{
							skip = true;
						}
					}
					if (!skip)
					{
						stateChanged = true;
						var type = $(this).attr('type');
						enable |= isDependencyEnabled(this) && ((type == "checkbox" || type == "radio") && $(this).attr('checked') || type != "checkbox" && type != "radio" && $(this).val().length > 0);
					}
				});
				if (stateChanged && isDependencyCouldBeChanged(this) && (isDependencyEnabled(this) != enable))
				{
					changeDependencyState(this, !enable);
					actionTaken = true;
				}
			}
		}
	});
	$('.dmo').each(function ()
	{
		var dmoClass = $(this).attr('class');
		var ctrl = $(this).is('option') ? $(this).parent() : this;
		var dmfClass = $(ctrl).attr('class');
		var dgiReg = /dg(\d+)i(\d+)/gi;
		var dgiId = dgiReg.exec(dmfClass);
		var dvaReg = /dva(\d+)/gi;
		while ((dvaId = dvaReg.exec(dmoClass)) != null)
		{
			var enable = false;
			var stateChanged = false;
			$('.dvd' + dvaId[1]).each(function ()
			{
				var skip = false;
				if (dgiId != null)
				{
					var ctrl = $(this).is('option') ? $(this).parent() : this;
					var tDmfClass = $(ctrl).attr('class');
					var dgiReg = /dg(\d+)i(\d+)/gi;
					if ((tDgiId = dgiReg.exec(tDmfClass)) != null && dgiId[1] == tDgiId[1] && dgiId[2] != tDgiId[2])
					{
						skip = true;
					}
				}
				if (!skip)
				{
					stateChanged = true;
					enable |= isDependencyEnabled(this) && ($(this).attr('checked') || $(this).attr('selected'));
				}
			});
			if (stateChanged && isDependencyCouldBeChanged(this) && (isDependencyEnabled(this) != enable))
			{
				changeDependencyState(this, !enable);
				actionTaken = true;
			}
		}
	});
	if (actionTaken)
	{
		revalidateDependencies(2);
	}
}

function changeDependencyState(item, disable)
{
	if (disable)
	{
		$(item).parents('.dmw:first').addClass('dh');
		$(item).addClass('dh');
		$(item).attr('disabled', 'disabled');
		if (!$(item).is('option'))
		{
			$(item).find('input').attr('disabled', 'disabled');
			$(item).find('select').attr('disabled', 'disabled');
			$(item).find('textarea').attr('disabled', 'disabled');
		}
		else
		{
			$(item).removeAttr('selected');
			$(item).selected = false;
		}
	}
	else
	{
		$(item).parents('.dmw:first').removeClass('dh');
		$(item).removeClass('dh');
		$(item).removeAttr('disabled'); 
		if (!$(item).is('option'))
		{
			// this code could cause conflicts with the options enablement, so that is why when checking for enablement we will also check for .dh presence
			$(item).find('input').each(function () 
			{
				if (isDependencyCouldBeChanged($(this)))
				{
					$(this).removeAttr('disabled')
				}
			});
			$(item).find('select').each(function () 
			{
				if (isDependencyCouldBeChanged($(this)))
				{
					$(this).removeAttr('disabled')
				}
			});
			$(item).find('textarea').each(function () 
			{
				if (isDependencyCouldBeChanged($(this)))
				{
					$(this).removeAttr('disabled')
				}
			});
		}
	}
}

function isDependencyEnabled(item)
{
	type = $(item).attr('disabled');
	enabled = (typeof(type) == 'undefined' || type == false) && !$(item).hasClass('disabled') && !$(item).hasClass('dh');

	if ($(item).is('option'))
	{
		parent = $(item).parent();
		type = $(parent).attr('disabled');
		if (typeof(type) != 'undefined' && type != false || $(parent).hasClass('disabled') || $(parent).hasClass('dh'))
		{
			enabled = false;
		}
	}
	return enabled;
}

function isDependencyCouldBeChanged(item)
{
	// forced disable do not overrule it!
	isInForcedDisable = $(item).hasClass('disabled') || $(item).is('option') && $(item).parent().hasClass('disabled');
	return !isInForcedDisable;
}

function jsHoverFn()
{
	$(this).mouseover(function()
	{
		$(this).addClass('jshover');
	});
	$(this).mouseout(function()
	{
		$(this).removeClass('jshover');
	});
}

