var whitespace = " \t\n\r";
var browser = new BrowserDetectLite();

function BrowserDetectLite()
{
	var ua = navigator.userAgent.toLowerCase();

	this.ua = ua;

	this.isSafari = (ua.indexOf('safari') != -1);
	this.isFireFox = (ua.indexOf('firefox') != -1);
	this.isGecko     = (ua.indexOf('gecko') != -1);
	this.isMozilla   = (this.isGecko && ua.indexOf("gecko/") + 14 == ua.length);
	this.isNS        = ( (this.isGecko) ? (ua.indexOf('netscape') != -1) : ( (ua.indexOf('mozilla') != -1) && (ua.indexOf('spoofer') == -1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('opera') == -1) && (ua.indexOf('webtv') == -1) && (ua.indexOf('hotjava') == -1) ) );
	this.isIE        = ( (ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1) ); 
	this.isOpera     = (ua.indexOf("opera") != -1); 
	this.isKonqueror = (ua.indexOf("konqueror") != -1); 
	this.isAol       = (ua.indexOf("aol") != -1); 
	this.isOmniweb   = (ua.indexOf("omniweb") != -1);
	this.isDreamcast = (ua.indexOf("dreamcast") != -1);

	this.isIECompatible = ( (ua.indexOf("msie") != -1) && !this.isIE);
	this.isNSCompatible = ( (ua.indexOf("mozilla") != -1) && !this.isIE && !this.isNS && !this.isMozilla);

	this.versionMinor = parseFloat(navigator.appVersion); 

	if (this.isNS && this.isGecko)
	{
		this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('/') + 1 ) );
	}

	else if (this.isIE && this.versionMinor >= 4)
	{
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );
	}

	else if (this.isOpera)
	{
		if (ua.indexOf('opera/') != -1)
		{
			this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera/') + 6 ) );
		}
		else
		{
			this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera ') + 6 ) );
		}
	}
	else if (this.isKonqueror)
	{
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('konqueror/') + 10 ) );
	}

	this.versionMajor = parseInt(this.versionMinor);
	this.geckoVersion = ( (this.isGecko) ? ua.substring( (ua.lastIndexOf('gecko/') + 6), (ua.lastIndexOf('gecko/') + 14) ) : -1 );

	this.isWin   = (ua.indexOf('win') != -1);
	this.isWin32 = (this.isWin && ( ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1) );
	this.isMac   = (ua.indexOf('mac') != -1);
	this.isUnix  = (ua.indexOf('unix') != -1 || ua.indexOf('linux') != -1 || ua.indexOf('sunos') != -1 || ua.indexOf('bsd') != -1 || ua.indexOf('x11') != -1)

	this.isNS4x = (this.isNS && this.versionMajor == 4);
	this.isNS40x = (this.isNS4x && this.versionMinor < 4.5);
	this.isNS47x = (this.isNS4x && this.versionMinor >= 4.7);
	this.isNS4up = (this.isNS && this.versionMinor >= 4);
	this.isNS6x = (this.isNS && this.versionMajor == 6);
	this.isNS6up = (this.isNS && this.versionMajor >= 6);

	this.isIE4x = (this.isIE && this.versionMajor == 4);
	this.isIE4up = (this.isIE && this.versionMajor >= 4);
	this.isIE5x = (this.isIE && this.versionMajor == 5);
	this.isIE55 = (this.isIE && this.versionMinor == 5.5);
	this.isIE5up = (this.isIE && this.versionMajor >= 5);
	this.isIE6x = (this.isIE && this.versionMajor == 6);
	this.isIE6up = (this.isIE && this.versionMajor >= 6);

	this.isIE4xMac = (this.isIE4x && this.isMac);
}

function setEnableDisable(control, state)
{
	var c = findObject(control);

	if (c != null)
	{
		c.disabled = !state;

		if (c.tagName == 'INPUT' && c.type == 'text') {
			c.readOnly = !state;
		}

		if (c.tagName == 'A') {
			c.style.color = state ? '' : '#ACA899';
		}

		if (c.tagName != 'SELECT' && c.childNodes.length > 0) {
			disableEnableChildren(c, state, setEnableDisable.arguments.length < 3);
		}
	}

	c = null;
}

function disableEnableChildren(control, enable, disableTextTag)
{
	if (control.tagName == 'INPUT')
	{
		if (control.type != 'text')
		{
			control.disabled = !enable;
		}
		else
		{
			if (disableTextTag)
			{
				control.disabled = !enable;
			}

			control.readOnly = !enable;
		}
	}

	if (control.tagName == 'SELECT' || control.tagName == 'A' || control.tagName == 'TD' || control.tagName == 'SPAN')
	{
		control.disabled = !enable;
		control.style.disabled = !enable;
	}

	if (control.tagName == 'TD' || control.tagName == 'A' || control.tagName == 'SPAN')
	{
		if (!control.disabled)
		{
			control.removeAttribute('disabled', false);
		}
		else
		{
			control.setAttribute('disabled', 'disabled');
		}
	}
	
	if (control.tagName == 'A')
	{
		control.style.color = enable ? '' : '#ACA899';
	}

	if (control.tagName != 'SELECT')
	{
		for (var i = 0; i < control.childNodes.length; i++)
		{
			disableEnableChildren(control.childNodes.item(i), enable, disableTextTag);
		}
	}
}

function findObject(n, d)
{
	var p, i, x;

	if (!d)
	{
		d = document;

		if ((p = n.indexOf("?")) > 0 && parent.frames.length)
		{
			d = parent.frames[n.substring(p + 1)].document;
			n = n.substring(0, p);
		}

		if (!(x=d[n]) && d.all) x = d.all[n];

		for (i=0; !x && i < d.forms.length; i++) x = d.forms[i][n];

		for (i=0; !x && d.layers && i < d.layers.length; i++) x = findObject(n, d.layers[i].document);

		if (!x && d.getElementById) x = d.getElementById(n);

		return x;
	}
	else
	{
		return findObject_recursive(n, d);
	}
}

function findAttribute(control, attribute)
{
	var __val_IE = (document.all);
	var __val_DOM = (document.getElementById);

	var attrib;

	if (__val_DOM)
	{
		attrib = control.getAttribute(attribute, false);
	}
	else
	{
		attrib = eval("document." + (__val_IE) ? "all." : (__val_DOM) ? "getElementById(\"" : ""
			+ control.id + "." + attribute + (_val_DOM && !__val_IE) ? "\")" : "");
	}

	return attrib;
}

function findObject_recursive(n, d)
{
	for (var i = 0; i < d.childNodes.length; i++)
	{
		if (d.childNodes.item(i).id == n)
		{
			return d.childNodes.item(i);
		}
		var fObj = findObject_recursive(n, d.childNodes.item(i));

		if (fObj != null) return fObj;
	}

	return null;
}

function findRowSelector_recursive(n, d)
{
	for (var i = 0; i < d.childNodes.length; i++)
	{
		var elementID = d.childNodes.item(i).id;

		if (elementID != null)
		{
			var pos = elementID.indexOf(n);

			if (pos >= 0) {
				return d.childNodes.item(i);
			}

			var fObj = findRowSelector_recursive(n, d.childNodes.item(i));

			if (fObj != null) return fObj;
		}
	}

	return null;
}

function changeImage()
{
	var i, j = 0, x, a = changeImage.arguments;

	for (i = 0; i < (a.length - 1); i += 2)
	{
		if ((x = findObject(a[i])) != null)
		{
			x.src = a[i + 1];
		}
	}
}

function preloadImages()
{
	var d = document;

	if (d.images)
	{
		if (!d.MM_p) d.MM_p = new Array();

		var i, j = d.MM_p.length, a = preloadImages.arguments;

		for (i = 0; i < a.length; i++)
		{
			if (a[i].indexOf("#") != 0)
			{
				d.MM_p[j] = new Image;
				d.MM_p[j++].src = a[i];
			}
		}
	}
}

function setFocus(control)
{
	var c = findObject(control);

	if (c != null && c.focus)
	{
		c.focus();
	}
}

function textCounter(itemName, maxLimit)
{
	var field = findObject(itemName);

	if ((field != null) && (field.value.length > maxLimit))
	{
		field.value = field.value.substring(0, maxLimit);
	}
}

function replaceAll(s, fromStr, toStr)
{
	var new_s = s;

	for (var i = 0; i < 100 && new_s.indexOf (fromStr) != -1; i++)
	{
		new_s = new_s.replace (fromStr, toStr);
	}

	return new_s;
}

function isEmpty(s)
{
	return ((s == null) || (s.length == 0))
}

function isEmptyT(s) {
	return isEmpty(s.trim());
}

function RTrim(strTrim)
{
	var str = new String(strTrim);
	var i = 0;
	var c = "";
	var endpos = 0

	for (i = str.length; i >= 0 && endpos == 0; i = i - 1)
	{
		c = str.charAt(i);

		if (whitespace.indexOf(c) == -1)
		{
			endpos = i;
		}
	}

	return str.substring(0, endpos + 1);
}

function regularExpressionValidator(value, expression)
{
	var rx = new RegExp(expression);
	var matches = rx.exec(value);

	return r = (matches != null && value == matches[0]);
}

function isFileName(value)
{
	if (navigator.appVersion.toLowerCase().indexOf("mac") > 0)
	{
		return true;
    }

    if (browser.isFireFox) 
    {        
        value = "c:\\" + value;
    }
//    if (browser.isSafari || browser.isOpera || browser.isFireFox) 
//    {        
//	    value = "c:\\" + value;
//	}
	
	return regularExpressionValidator(value, "([a-zA-Z]:\\\\[^/:\\*\\?<>\\|]+\\.\\w{2,6})|(\\\\{2}[^/:\\*\\?<>\\|]+\\.\\w{2,6})");
}

function isEmailList(value)
{
	return regularExpressionValidator(value, "^(([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25})+)*$");
}

function getCheckBoxEnabled(val)
{
	var isEnabled = false;
	
	if (val != null && val.tagName == 'INPUT')
	{
		if (val.type == 'checkbox' && !val.disabled)
		{
			isEnabled = true;
		}
	}

	var childItems = val.childNodes;

	if (childItems != null && isEnabled == false)
	{
		for (var i = 0; i < childItems.length; i++)
		{
			isEnabled = getCheckBoxEnabled(childItems.item(i));
			
			if (isEnabled)
			{
				break;
			}
		}
	}

	return isEnabled;
}

function getCheckBoxChecked(val)
{
	var isChecked = false;

	if (val != null && val.tagName == 'INPUT')
	{
		if (val.type == 'checkbox' && !val.disabled)
		{
			if (val.checked)
			{
				isChecked = true;
			}
		}
	}

	var childItems = val.childNodes;

	if (childItems != null && isChecked == false)
	{
		for (var i = 0; i < childItems.length; i++)
		{
			isChecked = getCheckBoxChecked(childItems.item(i));
			
			if (isChecked)
			{
				break;
			}
		}
	}

	return isChecked;
}

function CheckBoxListValidation(val)
{
	var target = findObject(dom_getAttribute(val, "controltovalidate"));

	if (target != null)
	{
		var panel = target.parentNode;

		if (panel == null)
		{
			return false;
		}

		var hasEnabledItems = getCheckBoxEnabled(panel);
		
		if (hasEnabledItems)
		{
			return getCheckBoxChecked(panel);
		}
		else
		{
			return true;
		}
	}

	return false;
}

function EnabledTextBoxValidation(val)
{
	var valid = true;
	var textBox = findObject(dom_getAttribute(val, "controltovalidate"));

	if ((textBox.tagName == 'INPUT') || (textBox.tagName == 'TEXTAREA'))
	{
		if ((textBox.type == 'text') || (textBox.type == 'file') || textBox.type == 'textarea')
		{
			if ((textBox.readOnly) || (textBox.disabled) || (textBox.value.length > 0))
			{
				valid = true;
			}
			else
			{
				valid = false;
			}
		}
	}

	return valid;
}

function EnabledTextBoxValidationSelectedRadio(val)
{
	var radio = findObject(dom_getAttribute(val, "controllingradiobutton"));

	if (radio == null)
	{
		return false;
	}

	var valid = EnabledTextBoxValidation(val);

	return radio.checked ? valid : true;
}

function GetCountCheckedItem(parentName)
{
	var target = findObject(parentName);

	return getCheckedCount(target);
}

function getCheckedCount(target)
{
	var count = 0;

	if (target != null)
	{
		var col = target.childNodes;

		if (col != null)
		{
			for (var i = 0; i < col.length; i++)
			{
				if (col.item(i).tagName == 'INPUT')
				{
					var id_element = col.item(i).getAttribute('id');

					if (id_element != null)
					{
						var index = id_element.indexOf("AllSelector");

						if (col.item(i).checked)
						{
							count++;

							if (index != -1)
							{
								count--;
							}
						}
					}
				}
				else
				{
					count += getCheckedCount(col.item(i));
				}
			}
		}
	}

	return count;
}
function GetCountCheckedItemWithSpecificAttribut(parentName, attribut)
{
	var targetObj = findObject(parentName);

	return getCheckedCountWithSpecificAttribut(targetObj, attribut);
}

function getCheckedCountWithSpecificAttribut(target, attribut)
{
	var count = 0;

	if (target != null)
	{
		var col = target.childNodes;

		if (col != null)
		{
			for (var i = 0; i < col.length; i++)
			{
				if (col.item(i).tagName == 'INPUT')
				{
					var id_element = col.item(i).getAttribute('id');
					var attr = col.item(i).getAttribute(attribut);

					if (id_element != null && attr != null)
					{
						if (col.item(i).checked)
						{
							count++;
						}
					}
				}
				else
				{
					count += getCheckedCountWithSpecificAttribut(col.item(i), attribut);
				}
			}
		}
	}

	return count;
}

function GetCountCheckedItemEx(parentName)
{
	var target = findObject(parentName);

	return getCheckedCountEx(target);
}

function getCheckedCountEx(target)
{
	var count = 0;

	if (target != null)
	{
		var col = target.childNodes;

		if (col != null)
		{
			for (var i = 0; i < col.length; i++)
			{
				if (col.item(i).tagName == 'INPUT')
				{
					if(col.item(i).checked)
					{
						count++;
					}
				}
				else if (col.item(i).tagName != 'TABLE')
				{
					count += getCheckedCountEx(col.item(i));
				}
			}
		}
	}

	return count;
}

function disableFileInputs()
{
	var objects = document.all;

	for (var i = 0; i < objects.length; i++)
	{
		if ((objects.item(i).tagName == 'INPUT') && (objects.item(i).type == 'file'))
		{
			objects.item(i).disabled = true;
		}
	}
}

function validateUploadFile(control, message)
{
	var c = findObject(control);

	var result = true;

	if ((c != null) && !isEmpty(c.value))
	{
		result = isFileName(c.value);
	}

	if (!result)
	{
		alert(message);
	}

	return result;
}
function validateTextFields()
{
	var params = validateTextFields.arguments;
	var curElem, curForm, allForms = document.forms;

	for (var i = 0; i < params.length; i += 2)
	{
		for (var j = 0; j < allForms.length; j++)
		{
			curForm = allForms.item(j);

			for(var k = 0; k < curForm.elements.length; k++)
			{
				curElem = curForm.elements.item(k);

				if ((curElem.tagName == "INPUT") && (curElem.type == "text") 
												 && (curElem.id.indexOf(params[i]) == 0))
				{
					if (isEmpty(curElem.value))
					{
						if(params[i + 1] != "")
						{
							alert(params[i + 1]);
						}
						curElem.focus();

						return false;
					}
				}
			}
		}
	}

	return true;
}

function validateOneFieldsFill(fieldID, type, message)
{
	var curElem, curForm, allForms = document.forms, countFillElem = 0;

	for (var i = 0; i < allForms.length; i++)
	{
		curForm = allForms.item(i);

		for (var j = 0; j < curForm.elements.length; j++)
		{
			curElem = curForm.elements.item(j);

			if ((curElem.tagName == "INPUT") && (curElem.type == type)
											 && (curElem.id.indexOf(fieldID) != -1))
			{
				if (curElem.disabled == true) return true;

				if (!isEmpty(curElem.value)) countFillElem++;

				curElem.focus();
			}
		}
	}

	if (countFillElem > 0) return true;
	
	if (message != "") alert(message);

	return false;
}

function validateFileFields(fieldID, message, expression, allowEmpties, allowLike)
{
	var curElem, curForm, allForms = document.forms;

	if(allowLike == null)
	{
		allowLike = true;
	}

	for (var i = 0; i < allForms.length; i++)
	{
		curForm = allForms.item(i);

		for (var j = 0; j < curForm.elements.length; j++)
		{
			curElem = curForm.elements.item(j);

			if ((curElem.tagName == "INPUT") && (curElem.type == "file")
											 && ((allowLike && curElem.id.indexOf(fieldID) != -1) || curElem.id == fieldID))
			{
				if (curElem.disabled == true) return true;
				if (allowEmpties && isEmpty(curElem.value)) continue;

				var isValidExpression = true;

				if ((expression != null) && (expression.length > 0))
				{
					isValidExpression = regularExpressionValidator(curElem.value, expression);
				}

				if ((isEmpty(curElem.value)) || (!isFileName(curElem.value)) || (!isValidExpression))
				{
					if (message != "") alert(message);

					curElem.focus();

					return false;
				}
			}
		}
	}

	return true;
}

function validateStatusFilter(statusID, stateID, conditionID, daysID, relatedDateID, message)
{
	var curElem, curForm, allForms = document.forms;
	var statusControl, stateControl, conditionControl;

	for (var i = 0; i < allForms.length; i++)
	{
		curForm = allForms.item(i);

		for (var j = 0; j < curForm.elements.length; j++)
		{
			curElem = curForm.elements.item(j);

			if ((curElem.tagName == "SELECT") && (curElem.value == "-1" || curElem.value == "")
				&& curElem.disabled != true && curElem.id.indexOf(stateID) != -1)
			{
				alert(message);
				
				curElem.focus();

				return false;
			}

			if ((curElem.tagName == "INPUT") && (curElem.type == "text") &&
				(curElem.id.indexOf(daysID) != -1) && curElem.disabled != true && (curElem.value == "" || Number(curElem.value).toString() == "NaN"))
			{
				alert(message);

				curElem.focus();

				return false;
			}
		}
	}

	return true;
}

function validateUploadRegionFields(txtControl, txtMessage, fileControl, fileMessage, fileRegExp)
{
	var curElem, curForm, allForms = document.forms;

	for (var j = 0; j < allForms.length; j++)
	{
		curForm = allForms.item(j);

		for(var k = 0; k < curForm.elements.length; k++)
		{
			curElem = curForm.elements.item(k);

			if ((curElem.tagName == "INPUT") && (curElem.id.indexOf(txtControl) == 0))
			{
				var pairElem = findObject(fileControl + curElem.id.substr(txtControl.length));

				if (pairElem != null)
				{
					if (isEmptyT(curElem.value) && isEmptyT(pairElem.value)) continue;

					if (isEmptyT(curElem.value))
					{
						alert(txtMessage);
						curElem.focus();

						return false;
					}
					else if (isEmptyT(pairElem.value) || !isFileName(pairElem.value) || !regularExpressionValidator(pairElem.value, fileRegExp))
					{
						alert(fileMessage);
						pairElem.focus();

						return false;
					}
				}
			}
		}
	}

	return true;
}

function generateProfileDomain(outputControl, textBoxControl)
{
	var c = findObject(outputControl);

	if (c != null)
	{
		var expr = /[\W\s]/g;

		c.innerHTML = c.innerHTML.substring(0, c.innerHTML.lastIndexOf('/') + 1) + textBoxControl.value.replace(expr, '_');
	}
}

// Session watcher
var clientTimeout = 0;
var expiredLimit = 7200 - 20; // Session Timeout minus some amount of forestalling time
var warningLimit = expiredLimit - 300;
var warnWnd = null;
var warnWndPath = null;
var timerID;

function attachWatch(wndPath)
{
	warnWndPath = wndPath;

	if (window.addEventListener)
	{
		window.addEventListener('load', startWatch, false);
		window.addEventListener('unload', closeWarning, false);
	}
	else
	{
		window.attachEvent('onload', startWatch);
		window.attachEvent('onunload', closeWarning);
	}
}

function resetWatch()
{
	if (warnWnd == null) clientTimeout = 0;
		else if(!warnWnd.closed) warnWnd.focus();
}

function startWatch()
{
	if (timerID != null)
	{
		window.clearInterval(timerID);
	}

	timerID = window.setInterval("watchDog()", 1000);
}

function watchDog()
{
	var el;

	clientTimeout++;

	if (clientTimeout > expiredLimit)
	{
		closeWarning();

		location = "logout.aspx";
	}
	else if (clientTimeout > warningLimit)
	{
		var positionLeft = Math.round (document.body.offsetWidth / 2) - 150 + document.body.scrollLeft;
		var positionTop = Math.round (document.body.offsetHeight / 2) - 125 + document.body.scrollTop;

		if (warnWnd == null)
		{
			warnWnd = window.open(warnWndPath, "_blank", "width=300,height=250,menubar=no,toolbar=no,scrollbars=no,resizable=no,statusbar=no,left=" + positionLeft + ",top=" + positionTop);

			warnWnd.focus();
		}

		if (warnWnd != null && !warnWnd.closed && (el = warnWnd.document.getElementById("expire")))
		{
			el.value = expiredLimit - clientTimeout;
		}
	}
}

function closeWarning()
{
	if (warnWnd != null && !warnWnd.closed)
	{
		warnWnd.close();
	}

	warnWnd = null;

	resetWatch();
}

/* Multiline script */

var names = new Array;
var count;

function addRow(elem, isEnabled){
	tableObj=findParent(elem,'TABLE')
	if (!tableObj.processed) {
		recursive(tableObj,'save')
		tableObj.processed=true
	}

	tableObj.tBodies[0].insertBefore(tableObj.rows[tableObj.rows.length-2].cloneNode(true),tableObj.rows[tableObj.rows.length-1])

	if (isEnabled != null)
	{
		if (isEnabled) {
			recursive(tableObj.rows[tableObj.rows.length-2], 'clear&enabled')
		}
		else
		{
			recursive(tableObj.rows[tableObj.rows.length-2], 'clear&disabled')
		}
	}
	else
	{
		recursive(tableObj.rows[tableObj.rows.length-2], 'clear')
	}
	setIndex(tableObj)
}

function remRow(elem){
	tableObj=findParent(elem,'TABLE')
	if (tableObj.rows.length>3){
		trObj=findParent(elem,'TR')
		tableObj.deleteRow(trObj.sectionRowIndex)
	}
}

function remRowCount(elem, count) {
	tableObj = findParent(elem, 'TABLE')
	if (tableObj.rows.length > count) {
		trObj = findParent(elem, 'TR')
		tableObj.deleteRow(trObj.sectionRowIndex)
	}
}

function remRowNotUploaded(elem){
	tableObj=findParent(elem,'TABLE')
	if (tableObj.rows.length>4){
		trObj=findParent(elem,'TR')
		tableObj.deleteRow(trObj.sectionRowIndex)
	}
}
function remRowUploaded(elem){
	tableObj=findParent(elem,'TABLE')
	trObj=findParent(elem,'TR')
	tableObj.deleteRow(trObj.sectionRowIndex)
}

function findParent(childObj,parentTag){
	try {while (childObj.parentNode.tagName!=parentTag) childObj = childObj.parentNode} catch(childObj){return null}
	return childObj.parentNode
}

function setIndex(tableObj){
	for (i=1;i<tableObj.rows.length;i++){
		count=0
		recursive(tableObj.rows[i-1], 'set', i)
	}
}

function recursive(parentObj, mode, row){
	var i, childObj, mode;
	childObj=parentObj.childNodes
	for (i=0; i<childObj.length; i++){
		if (childObj[i].tagName=='INPUT' || childObj[i].tagName=='SELECT' || childObj[i].tagName=='TEXTAREA')
			switch (mode){
				case "save":
					names[tableObj,names.length]=childObj[i].name
				break
				case "set":
					childObj[i].id=childObj[i].name=names[tableObj,count]+row.toString()
					count++
				break
				case "clear":
				case "clear&enabled":
				case "clear&disabled":
					if (childObj[i].tagName=='INPUT' && childObj[i].type=='file'){
						var MyObject = new Object();
						
						MyObject = document.createElement('INPUT')
						MyObject.setAttribute('type', 'file')
						MyObject.setAttribute('size', childObj[i].getAttribute('size'))
						if (this.isIE){
							MyObject.setAttribute('className', childObj[i].className)
						}
						else {
							MyObject.setAttribute('class', childObj[i].getAttribute('class'))
						}
						
						parentObj.removeChild(childObj[i])
						parentObj.appendChild(MyObject)
					}
					else childObj[i].value=''
					if (mode == "clear&enabled")
					{
						if (childObj[i].tagName == 'INPUT' && childObj[i].type == 'text')
						{
							childObj[i].readOnly = false;
							childObj[i].disabled = false;
						}
						else
						{
							childObj[i].disabled = false;
						}
					}
					if (mode == "clear&disabled")
					{
						if (childObj[i].tagName == 'INPUT' && childObj[i].type == 'text')
						{
							childObj[i].readOnly = true;
							childObj[i].disabled = true;
						}
						else
						{
							childObj[i].disabled = true;
						}
					}
				break
			}
			
			if (childObj[i] != null)
			{
				if (childObj[i].childNodes.length>0) recursive(childObj[i], mode, row)
			}
	}
}

// Fan's and Artist's personal pages popups

function showPersonalPage(pageName, cypheredID)
{
/*
	will use this code block when smart navigation is enable
	var positionLeft = Math.round (document.body.offsetWidth / 2) - 400 + document.body.scrollLeft;
	var positionTop = Math.round (document.body.offsetHeight / 2) - 250 + document.body.scrollTop;
*/
	var positionLeft = Math.round (document.body.offsetWidth / 2) - 400;
	var positionTop = Math.round (document.body.offsetHeight / 2) - 250;

	var pWnd;
	var url = "forms/" + pageName + ".aspx?code=" + cypheredID;

	pWnd = window.open(url, null, "width=800,height=500,menubar=no,toolbar=no,scrollbars=yes,resizable=yes,statusbar=no,left=" + positionLeft + ",top=" + positionTop);
	pWnd.focus();
}

function checkServerTicketNumber(serverTicketKey, pageClassNameKey, formID)
{
	if (typeof(EPM3IE) != "undefined")
	{
		var t = findObject(serverTicketKey);
		var c = findObject(pageClassNameKey);

		if (t != null && c != null)
		{
			var result = EPM3IE.CheckServerTicketNumber(t.value, c.value);

			if (result != null && typeof(result) == "object" && result.error != true)
			{
				var value = result.value;

				if (value != null && value == false)
				{
					var pageUrl = window.location.href;

					if (pageUrl.match(/\?/))
					{
						pageUrl = removeQueryStringParameter(pageUrl, "tsid");

						if (pageUrl.substring(pageUrl.length - 1) != "?")
						{
							pageUrl += "&";
						}
					}
					else
					{
						pageUrl += "?"
					}

					window.location.replace(pageUrl + "tsid=" + new Date().getTime());
				}
			}
		}
	}

	var mainFormObject = document.getElementById(formID);

	if (mainFormObject == null)
	{
		mainFormObject = document.forms[0];
	}

	updateFormAction(mainFormObject);
}

function updateFormAction(form)
{
	if (typeof(form.action) == "undefined") form.action = "";

	if (form.action.match(/\?/))
	{
		form.action = removeQueryStringParameter(form.action, "tsid");

		if (form.action.substring(form.action.length - 1) != "?")
		{
			form.action += "&";
		}
	}
	else
	{
		form.action += "?"
	}

	form.action += "tsid=" + new Date().getTime();
}

function removeQueryStringParameter(queryString, parameter)
{
	var parameterRegExp = new RegExp("&?" + parameter + "=[^&]*");

	if (queryString.match(parameterRegExp))
	{
		return queryString.replace(parameterRegExp, "");
	}

	return queryString;
}

// Itinerary

var validatorsState;

function initValidatorsState(disabledValidators)
{
	if (disabledValidators != null)
	{
		var controls = disabledValidators.split(",");

		for (j = 0; j < controls.length; j++)
		{
			var object = findObject(controls[j]);

			if (object != null)
			{
				object.enabled = false;
			}
		}
	}
}

function saveValidatorsState(enabledValidators)
{
	if (validatorsState == null)
	{
		validatorsState = new Array(Page_Validators.length);
	}

	for (i = 0; i < Page_Validators.length; i++)
	{
		validatorsState[i] = Page_Validators[i].enabled;

		Page_Validators[i].enabled = false;
	}

	if (enabledValidators != null)
	{
		var controls = enabledValidators.split(",");

		for (j = 0; j < controls.length; j++)
		{
			var object = findObject(controls[j]);

			if (object != null)
			{
				object.enabled = true;
			}
		}
	}
}

function restoreValidatorsState()
{
	for (i = 0; i < Page_Validators.length; i++)
	{
		Page_Validators[i].enabled = validatorsState[i];
	}
}

// Loading panel

var loadObj, blockObj, scrollTimeout, syncLoadTimer, winObj;

function loading()
{
	if (!blockObj)
	{
		if (isIE)
		{
			document.write("<iframe id=block frameborder=0></iframe>");
			blockObj = document.getElementById("block");
		}
		else
		{
			document.write("<img id=block></img>");
			blockObj = document.getElementById("block");
		}
	}

	if (isIE) {
		blockObj.setAttribute('src', 'javascript:""');
		blockObj.className = "frLookupDialog";

		blockObj.style.position = "absolute";
		blockObj.style.width = top.document.body.clientWidth + 'px';
		blockObj.style.height = (top.document.body.scrollHeight ? top.document.body.scrollHeight : top.document.body.offsetHeight) + 'px';
		blockObj.style.display = "block";
		blockObj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=70)";
	}
	else
	{
		blockObj.className = "lookupDialogPad";
		blockObj.setAttribute('src', "img/bkg-error" + (pngNormal ? '.png' : '.gif'));
		blockObj.setAttribute('id', 'formLocker');

		blockObj.style.width = document.body.scrollWidth + 'px';
		blockObj.style.height = Math.max(document.body.scrollHeight, document.body.offsetHeight) + 'px';
	}

	if (!loadObj)
	{
		document.write("<div id=loading><img src=img/popup-loading.gif></div>");
		loadObj = document.getElementById("loading");
	}

	loadObj.style.position = "absolute";
	loadObj.style.zIndex = "10100";
	loadObj.style.top = document.body.scrollTop + document.body.clientHeight / 2 - loadObj.offsetHeight;
	loadObj.style.left = document.body.clientWidth / 2 - loadObj.offsetWidth / 2;
	loadObj.style.visibility = "visible";
	
	document.body.onscroll = document.body.onresize = function(){
		if (scrollTimeout) clearTimeout(scrollTimeout)
		scrollTimeout=setTimeout("syncObj()",50)
	}

	if (window.addEventListener)
	{
		window.addEventListener('load', hideLoading, false);
	}
	else
	{
		window.attachEvent('onload', hideLoading);
	}

}

function hideLoading()
{
	loadObj.style.visibility = blockObj.style.visibility = "hidden";
	document.body.onscroll = null;
	if (scrollTimeout) clearTimeout(scrollTimeout);
	if (syncLoadTimer) clearTimeout(syncLoadTimer);
	
}

function syncObj()
{
	var repeat=false, obj;
	var step=10;
	
	if (syncLoadTimer) clearTimeout(syncLoadTimer);

	if (loadObj.style.visibility=="visible") obj = loadObj; else obj = winObj;

	/* Fast position 
	obj.style.top=document.body.scrollTop+document.body.clientHeight/2-obj.offsetHeight/2
	obj.style.left=document.body.clientWidth/2-obj.offsetWidth/2
	*/

	topReq = document.body.scrollTop + document.body.clientHeight / 2 - obj.offsetHeight / 2;
	leftReq = document.body.clientWidth / 2 - obj.offsetWidth / 2;

	if (obj.offsetTop < topReq)
	{
		obj.style.top = obj.offsetTop+step;
		if (obj.offsetTop + step>topReq) obj.style.top=topReq; else repeat=true;
	}

	if (obj.offsetTop > topReq) {
		obj.style.top = obj.offsetTop - step;
		if (obj.offsetTop - step < topReq) obj.style.top = topReq; else repeat = true;
	}

	if (obj.offsetLeft < leftReq) {
		obj.style.left = obj.offsetLeft + step;
		if (obj.offsetLeft + step > leftReq) obj.style.left = leftReq; else repeat = true;
	}
	if (obj.offsetLeft > leftReq) {
		obj.style.left = obj.offsetLeft - step;
		if (obj.offsetLeft - step < leftReq) obj.style.left = leftReq; else repeat = true;
	}

	if (repeat) syncLoadTimer = setTimeout("syncObj()", 0)
}

function PostBackRegisterEditors()
{
	/*if (isOPERA)
	{
		if (RadEditorGlobalArray != null)
		{
			for (var i = 0; i < RadEditorGlobalArray.length; i++)
			{
				if (typeof(RadEditorGlobalArray[i].PostBackRegisterEditor) == "function")
				{
					RadEditorGlobalArray[i].PostBackRegisterEditor(RadEditorGlobalArray[i]);
				}
			}
		}
	}*/
}

function SetStatusName(selectObject, selectedObjectName, stateName, conditionName, daysName, dateName)
{
	var prefix = selectObject.id.substring(0, selectObject.id.indexOf(selectedObjectName))
	var suffix = selectObject.id.substring(selectObject.id.indexOf(selectedObjectName) + selectedObjectName.length)

	var stateID = prefix + stateName + suffix;
	var conditionID = prefix + conditionName + suffix;
	var daysID = prefix + daysName + suffix;
	var dateID = prefix + dateName + suffix;

	if (selectObject != null)
	{
		if (selectObject.value == "")
		{
			setEnableDisable(stateID, false);
			setEnableDisable(conditionID, false);
			setEnableDisable(daysID, false);
			setEnableDisable(dateID, false);
		}
		else
		{
			setEnableDisable(stateID, true);

			var object = findObject(stateID);

			SetStatusState(object, stateName, conditionName, daysName, dateName);
		}
	}
}

function SetStatusState(selectObject, selectedObjectName, conditionName, daysName, dateName)
{
	var prefix = selectObject.id.substring(0, selectObject.id.indexOf(selectedObjectName))
	var suffix = selectObject.id.substring(selectObject.id.indexOf(selectedObjectName) + selectedObjectName.length)

	var conditionID = prefix + conditionName + suffix;
	var daysID = prefix + daysName + suffix;
	var dateID = prefix + dateName + suffix;

	if (selectObject != null && selectObject.value != "")
	{
		var selectedID = selectObject.value;

		if (selectedID == -1)
		{
			setEnableDisable(conditionID, false);
			setEnableDisable(daysID, false);
			setEnableDisable(dateID, false);
		}
		else if (selectedID == 1 || selectedID == 0)
		{
			setEnableDisable(conditionID, true);

			var object = findObject(daysID);

			SetStatusCondition(object, conditionName, daysName, dateName);
		}
	}
}

function SetStatusCondition(selectObject, selectedObjectName, daysName, dateName)
{
	var prefix = selectObject.id.substring(0, selectObject.id.indexOf(selectedObjectName))
	var suffix = selectObject.id.substring(selectObject.id.indexOf(selectedObjectName) + selectedObjectName.length)

	var daysID = prefix + daysName + suffix;
	var dateID = prefix + dateName + suffix;

	if (selectObject != null && selectObject.value != "")
	{
		var selectedID = selectObject.value;

		if (selectedID == -1)
		{
			setEnableDisable(daysID, false);
			setEnableDisable(dateID, false);
		}
		else
		{
			setEnableDisable(daysID, true);
			setEnableDisable(dateID, true);
		}
	}
}

function RefreshNewRow(object, selectedObjectName, stateName, conditionName, daysName, dateName)
{
	var tableObj=findParent(object,'TABLE');

	var selectObject = tableObj.rows[tableObj.rows.length-2].children[0].children[0];

	SetStatusName(selectObject, selectedObjectName, stateName, conditionName, daysName, dateName);

	var prefix = selectObject.id.substring(0, selectObject.id.indexOf('ddlStatus'))
	var suffix = selectObject.id.substring(selectObject.id.indexOf('ddlStatus') + 'ddlStatus'.length)

	var stateID = prefix + 'ddlState' + suffix;

	findObject(stateID).value = -1;
}

// TASK LIST
var taskIdForWinPopup;

function ChangeTaskStatus(taskID, userID, ownerID, ConfirmID, IsAssigned, status)
{
	if (typeof(ToDoPanel) != "undefined")
	{
		var control = findObject("tdlc" + taskID);

		if (control)
		{
			control.style.textDecoration = status ? "line-through" : "none";

			var result = ToDoPanel.ChangeTaskStatus(taskID, userID, status);

			if (result.error)
			{
				alert(result.error);
			}
			else if (userID == ownerID && IsAssigned != 0)
			{
				taskIdForWinPopup = taskID;

				error(ConfirmID);
			}
			else if(userID == ownerID && IsAssigned == 0)
			{
				var result = ToDoPanel.ChangeTaskStatusToAllComplited(taskID);
				
				if (result.error)
				{
					alert(result.error);
				}
			}
		}
	}
}

function ChangeTaskStatus_NewDesign(taskID, userID, ownerID, ConfirmID, status)
{
	if (typeof(ToDoList) != "undefined")
	{
		var control = findObject("tdlc" + taskID);

		if (control)
		{
			control.className = status ? "fade" : "";

			var result = ToDoList.ChangeTaskStatus(taskID, userID, status);

			if (result.error)
			{
				alert(result.error);
			}
			else if (userID == ownerID)
			{
				taskIdForWinPopup = taskID;

				WindowPopupShow(ConfirmID);
			}
		}
	}
}

function ChangeTaskStatusToAllComplited(taskID)
{
	if (typeof(ToDoPanel) != "undefined")
	{
		var result = ToDoPanel.ChangeTaskStatusToAllComplited(taskIdForWinPopup)
		
		if (result.error)
		{
			alert(result.error);
		}
	}
}

function ChangeTaskStatusToAllComplited_NewDesign(taskID)
{
	if (typeof(ToDoList) != "undefined")
	{
		var result = ToDoList.ChangeTaskStatusToAllComplited(taskIdForWinPopup)
		
		if (result.error)
		{
			alert(result.error);
		}
	}
}

function OpenTask(e, taskID)
{
	var popupWindow;
	var url = 'forms/task.aspx';

	if (taskID != null)
	{
		url += "?code=" + taskID;
	}

	popupWindow = window.open(url, null, 'width=700, height=500, toolbar=no, location=no, menubar=no, status=no');
	popupWindow.focus();

	var e = (e) ? e : window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();

	return false
}

function EncodeImageURI(template)
{
	var imgRegExp = new RegExp("<img [^>]*src=\"photo.ashx\\?id=[^&]*&amp;", "g");

	var img = template.match(imgRegExp);

	if (img != null)
	{
		for (i = 0; i < img.length; i++)
		{
			var uriRegExp = new RegExp("<img [^>]*src=\"photo.ashx\\?id=([^&]*)&amp;", "g");

			var uri = uriRegExp.exec(img[i]);

			template = template.replace(uri[1], encodeURIComponent(uri[1]));
		}
	}

	return template;
}

function changePercentCommissions(feesID, comissionsID, comissionsPercentID, ddlFeesCommissionableContractID, txtAdditionalFee1ContractID, ddlFeesCommissionable1ContractID, txtAdditionalFee2ContractID, ddlFeesCommissionable2ContractID, txtFee3ContractID, ddlFeesCommissionable3ContractID, txtFee4ContractID, ddlFeesCommissionable4ContractID, txtFee5ContractID, ddlFeesCommissionable5ContractID, vatPercent, vatID)
{
	var fees = findObject(feesID);
	var ddlFeesCommissionableContract = findObject(ddlFeesCommissionableContractID);

	var comissions = findObject(comissionsID);
	var comissionsPercent = findObject(comissionsPercentID);
	var vat = findObject(vatID);

	var AdditionalFee1Contract = findObject(txtAdditionalFee1ContractID);
	var AdditionalFee2Contract = findObject(txtAdditionalFee2ContractID);
	var AdditionalFee3Contract = findObject(txtFee3ContractID);
	var AdditionalFee4Contract = findObject(txtFee4ContractID);
	var AdditionalFee5Contract = findObject(txtFee5ContractID);

	var ddlFeesCommossionable1Contract = findObject(ddlFeesCommissionable1ContractID);
	var ddlFeesCommossionable2Contract = findObject(ddlFeesCommissionable2ContractID);
	var ddlFeesCommossionable3Contract = findObject(ddlFeesCommissionable3ContractID);
	var ddlFeesCommossionable4Contract = findObject(ddlFeesCommissionable4ContractID);
	var ddlFeesCommossionable5Contract = findObject(ddlFeesCommissionable5ContractID);

	var summ = 0;

	if (ddlFeesCommissionableContract.value != 0)
	{
		summ = summ + Math.ceil(validNumber(fees.value));
	}

	if (ddlFeesCommossionable1Contract != null)
	{
		if (ddlFeesCommossionable1Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee1Contract.value));
		}
	}

	if (ddlFeesCommossionable2Contract != null)
	{
		if (ddlFeesCommossionable2Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee2Contract.value));
		}
	}

	if (ddlFeesCommossionable3Contract != null)
	{
		if (ddlFeesCommossionable3Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee3Contract.value));
		}
	}

	if (ddlFeesCommossionable4Contract != null)
	{
		if (ddlFeesCommossionable4Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee4Contract.value));
		}
	}

	if (ddlFeesCommossionable5Contract != null)
	{
		if (ddlFeesCommossionable5Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee5Contract.value));
		}
	}

	if(fees != null && comissions != null && comissionsPercent != null)
	{
		if(fees.value != '' && comissionsPercent.value != '')
		{
			comissions.value = Math.ceil(summ * validNumber(comissionsPercent.value) * 100) / 10000;
			comissions.onkeyup();
		}

		if (vat != null && comissions.value != '') {
			vat.value = Math.ceil(validNumber(comissions.value) * vatPercent * 100) / 10000;
			vat.onkeyup();
		}
	}
}

function changeCommissions(feesID, comissionsID, comissionsPercentID, ddlFeesCommissionableContractID, txtAdditionalFee1ContractID, ddlFeesCommissionable1ContractID, txtAdditionalFee2ContractID, ddlFeesCommissionable2ContractID, txtFee3ContractID, ddlFeesCommissionable3ContractID, txtFee4ContractID, ddlFeesCommissionable4ContractID, txtFee5ContractID, ddlFeesCommissionable5ContractID, vatPercent, vatID)
{
	var fees = findObject(feesID);
	var ddlFeesCommissionableContract = findObject(ddlFeesCommissionableContractID);
	
	var comissions = findObject(comissionsID);
	var comissionsPercent = findObject(comissionsPercentID);
	var vat = findObject(vatID);

	var AdditionalFee1Contract = findObject(txtAdditionalFee1ContractID);
	var AdditionalFee2Contract = findObject(txtAdditionalFee2ContractID);
	var AdditionalFee3Contract = findObject(txtFee3ContractID);
	var AdditionalFee4Contract = findObject(txtFee4ContractID);
	var AdditionalFee5Contract = findObject(txtFee5ContractID);

	var ddlFeesCommossionable1Contract = findObject(ddlFeesCommissionable1ContractID);
	var ddlFeesCommossionable2Contract = findObject(ddlFeesCommissionable2ContractID);
	var ddlFeesCommossionable3Contract = findObject(ddlFeesCommissionable3ContractID);
	var ddlFeesCommossionable4Contract = findObject(ddlFeesCommissionable4ContractID);
	var ddlFeesCommossionable5Contract = findObject(ddlFeesCommissionable5ContractID);

	var summ = 0;

	if (ddlFeesCommissionableContract.value != 0)
	{
		summ = summ + Math.ceil(validNumber(fees.value));
	}

	if (ddlFeesCommossionable1Contract != null)
	{
		if (ddlFeesCommossionable1Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee1Contract.value));
		}
	}

	if (ddlFeesCommossionable2Contract != null)
	{
		if (ddlFeesCommossionable2Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee2Contract.value));
		}
	}

	if (ddlFeesCommossionable3Contract != null)
	{
		if (ddlFeesCommossionable3Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee3Contract.value));
		}
	}

	if (ddlFeesCommossionable4Contract != null)
	{
		if (ddlFeesCommossionable4Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee4Contract.value));
		}
	}

	if (ddlFeesCommossionable5Contract != null)
	{
		if (ddlFeesCommossionable5Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee5Contract.value));
		}
	}

	if(fees != null && comissions != null && comissionsPercent != null)
	{
		if (fees.value != '' && comissions.value != '')
		{
			if (summ != 0)
			{
				comissionsPercent.value = Math.ceil(validNumber(comissions.value) / summ * 10000) / 100;
				comissionsPercent.onkeyup();
			}
			else
			{
				comissionsPercent.value = 0;
			}
		}
	}

	if (vat != null) {
		vat.value = Math.ceil(validNumber(comissions.value) * vatPercent * 100) / 10000;
		vat.onkeyup();
	}
}

//function changeFees(feesID, comissionsID, comissionsPercentID, managementCommissionsID, managementCommissionsPercentID, ddlFeesCommissionableContractID, AdditionalFee1ContractID, ddlFeesCommossionable1ContractID, AdditionalFee2ContractID, ddlFeesCommossionable2ContractID, AdditionalFee3ContractID, ddlFeesCommossionable3ContractID, AdditionalFee4ContractID, ddlFeesCommossionable4ContractID, AdditionalFee5ContractID, ddlFeesCommossionable5ContractID, txtCommissionsEvent1ContractID, txtPercentCommissionsEvent1ContractID, txtManagementCommissionsEvent1ContractID, txtPercentManagementCommissionsEvent1ContractID, txtCommissionsEvent2ContractID, txtPercentCommissionsEvent2ContractID, txtManagementCommissionsEvent2ContractID, txtPercentManagementCommissionsEvent2ContractID, txtCommissionsEvent3ContractID, txtPercentCommissionsEvent3ContractID, txtManagementCommissionsEvent3ContractID, txtPercentManagementCommissionsEvent3ContractID)
function changeFees(feesID, comissionsID, comissionsPercentID, managementCommissionsID, managementCommissionsPercentID, ddlFeesCommissionableContractID, AdditionalFee1ContractID, ddlFeesCommossionable1ContractID, AdditionalFee2ContractID, ddlFeesCommossionable2ContractID, AdditionalFee3ContractID, ddlFeesCommossionable3ContractID, AdditionalFee4ContractID, ddlFeesCommossionable4ContractID, AdditionalFee5ContractID, ddlFeesCommossionable5ContractID, txtCommissionsEvent1ContractID, txtPercentCommissionsEvent1ContractID, txtManagementCommissionsEvent1ContractID, txtPercentManagementCommissionsEvent1ContractID, txtCommissionsEvent2ContractID, txtPercentCommissionsEvent2ContractID, txtManagementCommissionsEvent2ContractID, txtPercentManagementCommissionsEvent2ContractID, txtCommissionsEvent3ContractID, txtPercentCommissionsEvent3ContractID, txtManagementCommissionsEvent3ContractID, txtPercentManagementCommissionsEvent3ContractID, bookingVATPercent, managementVATPercent, bookingVAT, managingVAT, bookingVAT1, managingVAT1, bookingVAT2, managingVAT2, bookingVAT3, managingVAT3)
{
	var fees = findObject(feesID);
	var ddlFeesCommissionableContract = findObject(ddlFeesCommissionableContractID);

	var comissions = findObject(comissionsID);
	var comissionsPercent = findObject(comissionsPercentID);

	var AdditionalFee1Contract = findObject(AdditionalFee1ContractID);
	var AdditionalFee2Contract = findObject(AdditionalFee2ContractID);
	var AdditionalFee3Contract = findObject(AdditionalFee3ContractID);
	var AdditionalFee4Contract = findObject(AdditionalFee4ContractID);
	var AdditionalFee5Contract = findObject(AdditionalFee5ContractID);

	var ddlFeesCommossionable1Contract = findObject(ddlFeesCommossionable1ContractID);
	var ddlFeesCommossionable2Contract = findObject(ddlFeesCommossionable2ContractID);
	var ddlFeesCommossionable3Contract = findObject(ddlFeesCommossionable3ContractID);
	var ddlFeesCommossionable4Contract = findObject(ddlFeesCommossionable4ContractID);
	var ddlFeesCommossionable5Contract = findObject(ddlFeesCommossionable5ContractID);

	var txtCommissionsEvent1Contract = findObject(txtCommissionsEvent1ContractID);
	var txtCommissionsEvent2Contract = findObject(txtCommissionsEvent2ContractID);
	var txtCommissionsEvent3Contract = findObject(txtCommissionsEvent3ContractID);

	var txtPercentCommissionsEvent1Contract = findObject(txtPercentCommissionsEvent1ContractID);
	var txtPercentCommissionsEvent2Contract = findObject(txtPercentCommissionsEvent2ContractID);
	var txtPercentCommissionsEvent3Contract = findObject(txtPercentCommissionsEvent3ContractID);

	var txtManagementCommissionsEvent1Contract = findObject(txtManagementCommissionsEvent1ContractID);
	var txtManagementCommissionsEvent2Contract = findObject(txtManagementCommissionsEvent2ContractID);
	var txtManagementCommissionsEvent3Contract = findObject(txtManagementCommissionsEvent3ContractID);

	var txtPercentManagementCommissionsEvent1Contract = findObject(txtPercentManagementCommissionsEvent1ContractID);
	var txtPercentManagementCommissionsEvent2Contract = findObject(txtPercentManagementCommissionsEvent2ContractID);
	var txtPercentManagementCommissionsEvent3Contract = findObject(txtPercentManagementCommissionsEvent3ContractID);

	var summ = 0;

	if (ddlFeesCommissionableContract.value != 0)
	{
		summ = summ + Math.ceil(validNumber(fees.value));
	}

	if (ddlFeesCommossionable1Contract != null)
	{
		if (ddlFeesCommossionable1Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee1Contract.value));
		}
	}

	if (ddlFeesCommossionable2Contract != null)
	{
		if (ddlFeesCommossionable2Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee2Contract.value));
		}
	}

	if (ddlFeesCommossionable3Contract != null)
	{
		if (ddlFeesCommossionable3Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee3Contract.value));
		}
	}

	if (ddlFeesCommossionable4Contract != null)
	{
		if (ddlFeesCommossionable4Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee4Contract.value));
		}
	}

	if (ddlFeesCommossionable5Contract != null)
	{
		if (ddlFeesCommossionable5Contract.value != 0)
		{
			summ = summ + Math.ceil(validNumber(AdditionalFee5Contract.value));
		}
	}
	
	//main
	if(fees != null && comissions != null && comissionsPercent != null)
	{
		if (comissionsPercent.value != '') {
			comissions.value = Math.ceil(summ * validNumber(comissionsPercent.value) * 100) / 10000;
			comissions.onkeyup();
		}
		else if (comissions.value != '') {
			changeCommissions(feesID, comissionsID, comissionsPercentID);
		}
	}

	var managementCommissions = findObject(managementCommissionsID);
	var managementCommissionsPercent = findObject(managementCommissionsPercentID);

	if(fees != null && managementCommissions != null && managementCommissionsPercent != null)
	{
		if (managementCommissionsPercent.value != '')
		{
			managementCommissions.value = Math.ceil(summ * validNumber(managementCommissionsPercent.value) * 100) / 10000;
			managementCommissions.onkeyup();
		}
		else if (managementCommissions.value != '')
		{
			changeCommissions(feesID, managementCommissionsID, managementCommissionsPercentID);
		}
	}

	//first
	if (fees != null && txtCommissionsEvent1Contract != null && txtPercentCommissionsEvent1Contract != null)
	{
		if (txtPercentCommissionsEvent1Contract.value != '')
		{
			txtCommissionsEvent1Contract.value = Math.ceil(summ * validNumber(txtPercentCommissionsEvent1Contract.value) * 100) / 10000;
			txtCommissionsEvent1Contract.onkeyup();
		}
		else if (txtCommissionsEvent1Contract.value != '')
		{
			changeCommissions(feesID, txtCommissionsEvent1ContractID, txtPercentCommissionsEvent1ContractID);
		}
	}

	if (fees != null && txtManagementCommissionsEvent1Contract != null && txtPercentManagementCommissionsEvent1Contract != null)
	{
		if (txtPercentManagementCommissionsEvent1Contract.value != '')
		{
			txtManagementCommissionsEvent1Contract.value = Math.ceil(summ * validNumber(txtPercentManagementCommissionsEvent1Contract.value) * 100) / 10000;
			txtManagementCommissionsEvent1Contract.onkeyup();
		}
		else if (txtManagementCommissionsEvent1Contract.value != '')
		{
			changeCommissions(feesID, txtManagementCommissionsEvent1ContractID, txtPercentManagementCommissionsEvent1ContractID);
		}
	}

	//second
	if (fees != null && txtCommissionsEvent2Contract != null && txtPercentCommissionsEvent2Contract != null) {
		if (txtPercentCommissionsEvent2Contract.value != '') {
			txtCommissionsEvent2Contract.value = Math.ceil(summ * validNumber(txtPercentCommissionsEvent2Contract.value) * 100) / 10000;
			txtCommissionsEvent2Contract.onkeyup();
		}
		else if (txtCommissionsEvent2Contract.value != '') {
			changeCommissions(feesID, txtCommissionsEvent2ContractID, txtPercentCommissionsEvent2ContractID);
		}
	}

	if (fees != null && txtManagementCommissionsEvent2Contract != null && txtPercentManagementCommissionsEvent2Contract != null) {
		if (txtPercentManagementCommissionsEvent2Contract.value != '') {
			txtManagementCommissionsEvent2Contract.value = Math.ceil(summ * validNumber(txtPercentManagementCommissionsEvent2Contract.value) * 100) / 10000;
			txtManagementCommissionsEvent2Contract.onkeyup();
		}
		else if (txtManagementCommissionsEvent2Contract.value != '') {
			changeCommissions(feesID, txtManagementCommissionsEvent2ContractID, txtPercentManagementCommissionsEvent2ContractID);
		}
	}

	//third
	if (fees != null && txtCommissionsEvent3Contract != null && txtPercentCommissionsEvent3Contract != null) {
		if (txtPercentCommissionsEvent3Contract.value != '') {
			txtCommissionsEvent3Contract.value = Math.ceil(summ * validNumber(txtPercentCommissionsEvent3Contract.value) * 100) / 10000;
			txtCommissionsEvent3Contract.onkeyup();
		}
		else if (txtCommissionsEvent3Contract.value != '') {
			changeCommissions(feesID, txtCommissionsEvent3ContractID, txtPercentCommissionsEvent3ContractID);
		}
	}

	if (fees != null && txtManagementCommissionsEvent3Contract != null && txtPercentManagementCommissionsEvent3Contract != null) {
		if (txtPercentManagementCommissionsEvent3Contract.value != '') {
			txtManagementCommissionsEvent3Contract.value = Math.ceil(summ * validNumber(txtPercentManagementCommissionsEvent3Contract.value) * 100) / 10000;
			txtManagementCommissionsEvent3Contract.onkeyup();
		}
		else if (txtManagementCommissionsEvent3Contract.value != '') {
			changeCommissions(feesID, txtManagementCommissionsEvent3ContractID, txtPercentManagementCommissionsEvent3ContractID);
		}
	}
}

//---------------------- Reminder -------------------------------

function OpenReminder(userID, controlID, windowID, refreshTime) {
	var locker = null;

	if (isIE) {
		locker = top.document.getElementById('formLocker')
	} else {
		locker = window.document.getElementById('formLocker')
	}

	if (locker == null) {
		var response = ToDoPanel.RequestReminder(userID);

		if (response.value != null && response.value.length != 0) {
			control = findObject(controlID);

			if (control != null) {
				control.innerHTML = response.value;

				error(windowID);
			}
		}
		else {
			window.setTimeout("OpenReminder(" + userID + ", '" + controlID + "', '" + windowID + "', " + refreshTime + ");", refreshTime);
		}
	} else {
		window.setTimeout("OpenReminder(" + userID + ", '" + controlID + "', '" + windowID + "', " + refreshTime + ");", refreshTime);
	}
}

function GetRowSelectorCheckedItems(tableID)
{
	var checkedIDList = [], listCount = 0;

	var tableObj = findObject(tableID);

	for (i = 1; i < tableObj.rows.length; i++)
	{
		var cbControl = findRowSelector_recursive("RowSelectorColumnSelector", tableObj.rows[i]);

		if (cbControl != null)
		{
			if (cbControl.checked)
			{
				checkedIDList[listCount] = i;

				listCount++;
			}
		}
	}

	return checkedIDList;
}

function UncheckRowSelectorCheckedItems(tableID) {
	var tableObj = findObject(tableID);

	var cbAllSelector = findRowSelector_recursive("RowSelectorColumnAllSelector", tableObj.rows[0]);
	if (cbAllSelector != null) {
		if (cbAllSelector.checked) {
			cbAllSelector.checked = false;
		}
	}

	for (i = 1; i < tableObj.rows.length; i++) {
		var cbSelector = findRowSelector_recursive("RowSelectorColumnSelector", tableObj.rows[i]);

		if (cbSelector != null) {
			if (cbSelector.checked) {
				cbSelector.checked = false;
			}
		}
	}
}

function ReminderPopupRequest(tableID, reminderWindowID, warningWindowID, userID, controlID, isDismiss, ddlSnoozeID, refreshTime)
{
	if (GetCountCheckedItem(tableID) == 0)
	{
		hideAjaxWindow();

		return error(warningWindowID, this);
	}
	else
	{
		var response;

		hideAjaxWindow();

		showLoadingPanel(reminderWindowID, "img/popup-loading.gif")

		if (isDismiss)
		{
			response = ToDoPanel.DismissReminderRequest(userID, GetRowSelectorCheckedItems(tableID));
		}
		else
		{

			var ddlSnoozeControl = findObject(ddlSnoozeID);

			if (ddlSnoozeControl != null)
			{
				response = ToDoPanel.SnoozeReminderRequest(userID, GetRowSelectorCheckedItems(tableID), ddlSnoozeControl.value);
			}
		}

		if (response.value != null && response.value.length != 0)
		{
			control = findObject(controlID);

			if (control != null)
			{
				control.innerHTML = response.value;

				hideLoadingPanel(reminderWindowID);

				error(reminderWindowID, null);
			}
		}
		else
		{
			hideLoadingPanel(reminderWindowID);

			cancel();

			window.setTimeout("OpenReminder(" + userID + ", '" + controlID + "', '" + reminderWindowID + "', " + refreshTime + ");", refreshTime);
		}
	}
}

function CloseReminderPopup(userID, controlID, reminderWindowID, refreshTime)
{
	hideAjaxWindow();

	ToDoPanel.CloseReminderRequest(userID);

	window.setTimeout("OpenReminder(" + userID + ", '" + controlID + "', '" + reminderWindowID + "', " + refreshTime + ");", refreshTime);

	return false;
}

function ResizeUploader(UploaderID, sizeWin, sizeMac)
{
	if (navigator.platform.indexOf("Win") != -1)
	{
		document.getElementById(UploaderID).setAttribute("size",sizeWin);
	}
	if (navigator.platform.indexOf("Mac") != -1) {
		document.getElementById(UploaderID).setAttribute("size", sizeMac);
	}
}

function redirectKeyDownToControlClick( keyDownCode, controlName )
{
	var control = document.getElementById( controlName );
	
	if( control )
	{	
		if( event.keyCode == keyDownCode )
		{
			event.returnValue = false;
			event.cancelBubble = true;
			control.click();
		}
	}
}

function findAspControlClientId( aspControlId )
{   
	var count = document.getElementsByTagName('*').length;
	var i = 0;
	var elementName;
	for( i = 0; i < count; i++ )
	{
		elementName = document.getElementsByTagName('*')[i].id;
		pos = elementName.indexOf( aspControlId );
		if( pos >= 0 )  break;
	}
	return elementName;
}

function getDropDownValue(controlId) {
	var control = document.getElementById(controlId);
	if (control != null)
		return control.options[control.selectedIndex].value;
	else
		return "";
}

// ---------------- Collapsing Panel -------------- //

function CP_CollapseExpand(itemId, fieldId, headerId) {
	var panel = document.getElementById(itemId.toString());
	var field = document.getElementById(fieldId.toString());
	var header = document.getElementById(headerId.toString());

	if (panel.style.display == "none") {
		panel.style.display = "inline";
		field.value = "inline";
		header.className = "rpLink rpExpanded";
	}
	else {
		panel.style.display = "none";
		field.value = "none";
		header.className = "rpLink rpExpandable";
	}

	return true;
}

function CP_CollapseExpand_VEC(item, buttonId) {
	var panel = document.getElementById(item.toString());
	var button = document.getElementById(buttonId.toString());

	if (panel.style.display == "none") {
		panel.style.display = "inline";
		button.innerHTML = "hide details";
	}
	else {
		panel.style.display = "none";
		button.innerHTML = "show details";
	}

	return true;
}

// --------------- New fees and commissions --------------- //

// this function should be applied to numeric edit fields
// (but may be applied to the others)
function forceOnChange(ctrlId) {
	var ctrl = document.getElementById(ctrlId);
	if (ctrl != null) {
		if (typeof(ctrl.onchange) == 'function') {
			ctrl.onchange();
		} else if (typeof(ctrl.onblur) == 'function') {
			ctrl.onblur();
		}
	}
}

function validNumber(text) {
	return text.toString().replace(/,/g,'');
}

function setZeroValue(objectId) {
	var control = document.getElementById(objectId);
	if (control != null) {
		if (control.value != null && control.value != '') {
			control.value = '';
		}
	}
}

function applyDefaultNumberFormat(ctrlId) {
	var ctrl = document.getElementById(ctrlId);
	if (ctrl != null) {
		if (ctrl.value != '') {
			ctrl.value = Number(validNumber(ctrl.value)).toFixed(2);
			if (typeof (ctrl.onkeyup) == 'function') {
				ctrl.onkeyup();
			}
		}
	}
}

function recalcAllFeesCommissions(feesID, isCommissionableID, bookingVATPercent, managingVATPercent, vatRateCtrlId,
	bookingCommissionsID, managingCommissionsID, bookingPercentID, managingPercentID, bookingVATID, managingVATID
) {
	forceOnChange(vatRateCtrlId);

	if (isCommissionable = document.getElementById(isCommissionableID).value != '1') {
		setZeroValue(bookingCommissionsID);
		setZeroValue(managingCommissionsID);
		setZeroValue(bookingVATID);
		setZeroValue(managingVATID);
		return;
	}

	applyFeesToCommissions(feesID, bookingCommissionsID, managingCommissionsID, bookingPercentID, managingPercentID, bookingVATID, managingVATID, bookingVATPercent, managingVATPercent);

	applyDefaultNumberFormat(feesID);
}

function applyFeesToCommissions(feesID, bookingCommissionsID,
	managingCommissionsID, bookingPercentID, managingPercentID, bookingCommissionsVATID,
	managingCommissionsVATID, bookingVATPercent, managingVATPercent) {

	/*if (document.getElementById(feesID).value == '') {
		return;
	}*/

	var feesAmount = validNumber(document.getElementById(feesID).value);

	var bookingCommissionsField = document.getElementById(bookingCommissionsID);
	var managingCommissionsField = document.getElementById(managingCommissionsID);
	var bookingPercentField = document.getElementById(bookingPercentID);
	var managingPercentField = document.getElementById(managingPercentID);

	if (bookingCommissionsField != null) {
		var bookingPercent = validNumber(bookingPercentField.value);
		var bookingValue = '';

		if (bookingPercent == '' && bookingCommissionsField.value != '') {
			bookingPercent = Math.ceil((validNumber(bookingCommissionsField.value) / feesAmount) * 100).toFixed(2);
			bookingPercentField.value = bookingPercent.toFixed(2);
			bookingValue = validNumber(bookingCommissionsField.value);
		} else if (document.getElementById(bookingPercentID).value != '') {
			bookingValue = Math.ceil(feesAmount * bookingPercent) / 100;
			bookingCommissionsField.value = bookingValue.toFixed(2);
		}

		//bookingCommissionsField.onchange();
		forceOnChange(bookingCommissionsID);

		bookingCommissionsField.onkeyup();
		bookingPercentField.onkeyup();
	}

	if (managingCommissionsField != null) {
		var managingPercent = validNumber(managingPercentField.value);
		var managingValue = '';

		if (managingPercent == '' && managingCommissionsField.value != '') {
			managingPercent = Math.ceil((validNumber(managingCommissionsField.value) / feesAmount) * 100).toFixed(2);
			managingPercentField.value = managingPercent;
			managingValue = validNumber(managingCommissionsField.value);
		} else if (document.getElementById(managingPercentID).value != '') {
			managingValue = Math.ceil(feesAmount * managingPercent) / 100;
			managingCommissionsField.value = managingValue.toFixed(2);
		}

		//managingCommissionsField.onchange();
		forceOnChange(managingCommissionsID);
		
		managingCommissionsField.onkeyup();
		managingPercentField.onkeyup();
	}
}

function applyCommissionsToPercent(feesID, isCommissionableID, commissionFieldID, percentFieldID,
	commissionVATID, commissionPercentID) {
	try {
		var commissionPercentCtrl = document.getElementById(commissionPercentID);
		var commissionPercent;

		if (commissionPercentCtrl == null) {
			commissionPercent = null;
		} else {
			commissionPercent = validNumber(commissionPercentCtrl.value);
		}

		applyDefaultNumberFormat(commissionFieldID);

		var feeField = document.getElementById(feesID);

		if (feeField.value == '') {
			return;
		}
		
		if (isCommissionable = validNumber(document.getElementById(isCommissionableID).value) != '1') {
			return;
		}

		var commissionsField = document.getElementById(commissionFieldID);

		if (commissionsField == null) {
			return;
		}

		if (commissionsField.value == '') {
			return;
		}

		var commissionsVATField = document.getElementById(commissionVATID);
		if (commissionPercent != null && commissionPercent != '') {
			var value = Math.ceil(validNumber(commissionsField.value) * commissionPercent) / 100;
			if (value <= 0) {
				commissionsVATField.value = '';
			} else {
				commissionsVATField.value = value.toFixed(2);
			}

			commissionsVATField.onkeyup();
		}

		var percentField = document.getElementById(percentFieldID);

		if (validNumber(feeField.value) > 0) {
			percentField.value = Math.ceil(validNumber(commissionsField.value) / validNumber(feeField.value) * 10000) / 100;
		}

		percentField.onkeyup();
	}
	catch (e) {
		alert(e.message);
	}
}

function applyPercentToCommissions(feesID, isCommissionableID, commissionFieldID, percentFieldID) {
	var feeField = document.getElementById(feesID);

	if (feeField.value == '') {
		return;
	}

	if (isCommissionable = validNumber(document.getElementById(isCommissionableID).value) != '1') {
		return;
	}

	var percentField = document.getElementById(percentFieldID);
	var commissionsField = document.getElementById(commissionFieldID);

	if (percentField == null) {
		return;
	}

	if (percentField.value == '') {
		return;
	}

	commissionsField.value = (validNumber(feeField.value) * validNumber(percentField.value) / 100).toFixed(2);
	commissionsField.onkeyup();
	forceOnChange(commissionFieldID);
}

function applyCurrencies(
		mainCurrencyControlID,
		feeCurrencyControls,
		feeExchangeRateControls,
		bookingCommissionCurrencyControls,
		bookingCommissionExchangeRateControls,
		managingCommissionCurrencyControls,
		managingCommissionExchangeRateControls,
		expenseCurrencyControls,
		expenseExchangeRateControls,
		depositCurrencyControls,
		ticketingCurrencyControls
) {
	try {
		applyCurrency(mainCurrencyControlID, feeCurrencyControls, feeExchangeRateControls);
		applyCurrency(mainCurrencyControlID, bookingCommissionCurrencyControls, bookingCommissionExchangeRateControls);
		applyCurrency(mainCurrencyControlID, managingCommissionCurrencyControls, managingCommissionExchangeRateControls);
		applyCurrency(mainCurrencyControlID, expenseCurrencyControls, expenseExchangeRateControls);
		applyCurrency(mainCurrencyControlID, depositCurrencyControls, null);
		applyCurrency(mainCurrencyControlID, ticketingCurrencyControls, null);
	}
	catch (e) {
		alert(e.message);
	}
}

function applyCurrency(mainCurrencyControlID, currencyControls, exchangeRateControls) {
	var mainCurrencyControl = document.getElementById(mainCurrencyControlID);
	var selection = mainCurrencyControl.selectedIndex;
	var newRate = mainCurrencyControl.options[mainCurrencyControl.selectedIndex].getAttribute('rate');

	for (var i = 0; i < currencyControls.length; i++) {
		var currencyControl = document.getElementById(currencyControls[i]);
		if (currencyControl != null) {
			currencyControl.selectedIndex = selection;
		}
		if (exchangeRateControls != null) {
			var exchangeRateControl = document.getElementById(exchangeRateControls[i]);
			if (exchangeRateControl != null) {
				exchangeRateControl.value = newRate != null ? newRate : '';
			}
		}
	}
}

function applyVATRate(rateDropDownID, percentFieldID, vatFieldID, srcFieldID) {
	var rateDropDown = document.getElementById(rateDropDownID);
	var percentField = document.getElementById(percentFieldID);
	var vatField = document.getElementById(vatFieldID);
	var srcField = document.getElementById(srcFieldID);

	if (rateDropDown.selectedIndex < 0) {
		return;
	}

	var selectedPercent = Number(rateDropDown.options[rateDropDown.selectedIndex].getAttribute('percent'));

	if (selectedPercent >= 0 && rateDropDown.options.length > 0) {
		if (rateDropDown.value != '' && rateDropDown.selectedIndex > 0 /* && selectedPercent != 0*/) {
			percentField.value = selectedPercent;

			if (srcField.value != '') {
				vatField.value = (selectedPercent * validNumber(srcField.value) / 100).toFixed(2);
				vatField.onkeyup();
			}
		}
		percentField.onkeyup();
	} else {
		forceOnChange(percentFieldID);
	}
}

function applyVATPercent(percentCtrlId, feesCtrlId, VATCtrlId, VATRateCtrlId) {
	var percent = document.getElementById(percentCtrlId).value;
	var fees = document.getElementById(feesCtrlId).value;
	var VATCtrl = document.getElementById(VATCtrlId);
	var VATRateCtrl = document.getElementById(VATRateCtrlId);

	if (VATRateCtrl.options.length > 0) {
		document.getElementById(VATRateCtrlId).options[0].selected = true;
	}

	if (fees != '' && percent != '') {
		VATCtrl.value = validNumber(fees) * validNumber(percent) / 100;
		applyDefaultNumberFormat(VATCtrlId);
		forceOnChange(VATCtrlId);
	}
}

function applyVATAmount(percentCtrlId, feesCtrlId, VATCtrlId, VATRateCtrlId) {
	var percentCtrl = document.getElementById(percentCtrlId);
	var fees = document.getElementById(feesCtrlId).value;
	var VAT = document.getElementById(VATCtrlId).value;
	var VATRateCtrl = document.getElementById(VATRateCtrlId);

	if (VATRateCtrl.options.length > 0) {
		document.getElementById(VATRateCtrlId).options[0].selected = true;
	}

	if (VAT != '' && fees != '' && validNumber(fees) > 0) {
		percentCtrl.value = validNumber(VAT) / validNumber(fees) * 100;
		applyDefaultNumberFormat(percentCtrlId);
	}

	applyDefaultNumberFormat(VATCtrlId);
}

// --------------- VAT Rates functionality --------------- //

function checkDateSpan(dateMinCtrlID, dateMaxCtrlID, tgtDateCtrlID, formatNum) {
	var dateMinCtrl = document.getElementById(dateMinCtrlID);
	var dateMaxCtrl = document.getElementById(dateMaxCtrlID);
	var tgtDateCtrl = document.getElementById(tgtDateCtrlID);

	if (dateMinCtrl.value != '' && tgtDateCtrl.value != '') {
		var startDate = CalendarPopup_Up_GetDate(dateMinCtrlID, formatNum);
		var tgtDate = CalendarPopup_Up_GetDate(tgtDateCtrlID, formatNum);
		
		if (startDate > tgtDate) {
			return false;
		}
	}

	if (dateMaxCtrl.value != '' && tgtDateCtrl.value != '') {
		var endDate = CalendarPopup_Up_GetDate(dateMaxCtrlID, formatNum);
		var tgtDate = CalendarPopup_Up_GetDate(tgtDateCtrlID, formatNum);

		if (endDate < tgtDate) {
			return false;
		}
	}

	return true;
}

// --------------- Exchange Rates functionality --------------- //

function recalculateTotals(
		currencies,
		feeControls,
		feeCurrencyControls,
		commissionableControls,
		bookingCommissionControls,
		bookingCommissionCurrencyControls,
		managingCommissionsControls,
		managingCommissionCurrencyControls,
		commissionCommissionableControls,
		expenseControls,
		expenseCurrencyControls,
		destinationTextBoxControls,
		destinationLabelControls
) {
	try {
		recalculateTotal(currencies, feeControls, feeCurrencyControls, destinationTextBoxControls[0], destinationLabelControls[0]);
		recalculateFeeTotal(currencies, feeControls, feeCurrencyControls, commissionableControls, destinationTextBoxControls[1], destinationLabelControls[1], 1);
		recalculateFeeTotal(currencies, feeControls, feeCurrencyControls, commissionableControls, destinationTextBoxControls[2], destinationLabelControls[2], 0);
		recalculateCommissionableTotal(currencies, bookingCommissionControls, bookingCommissionCurrencyControls, commissionCommissionableControls, destinationTextBoxControls[3], destinationLabelControls[3]);
		recalculateCommissionableTotal(currencies, managingCommissionsControls, managingCommissionCurrencyControls, commissionCommissionableControls, destinationTextBoxControls[4], destinationLabelControls[4]);
		recalculateTotal(currencies, expenseControls, expenseCurrencyControls, destinationTextBoxControls[5], destinationLabelControls[5]);
	}
	catch (e) {
		alert(e.message);
	}
}

function recalculateConvertedTotals(
		currencies,
		targetCurrencyID,
		feeControls,
		feeCurrencyControls,
		feeExchangeRateControls,
		commissionableControls,
		bookingCommissionControls,
		bookingCommissionCurrencyControls,
		bookingCommissionExchangeRateControls,
		managingCommissionsControls,
		managingCommissionCurrencyControls,
		managingCommissionExchangeRateControls,
		commissionCommissionableControls,
		expenseControls,
		expenseCurrencyControls,
		expenseExchangeRateControls,
		destinationTextBoxControls,
		destinationLabelControls
) {
	try {
		recalculateConvertedTotal(currencies, feeControls, feeCurrencyControls, feeExchangeRateControls, targetCurrencyID, destinationTextBoxControls[0], destinationLabelControls[0]);
		recalculateConvertedFeeTotal(currencies, feeControls, feeCurrencyControls, feeExchangeRateControls, commissionableControls, targetCurrencyID, destinationTextBoxControls[1], destinationLabelControls[1], 1);
		recalculateConvertedFeeTotal(currencies, feeControls, feeCurrencyControls, feeExchangeRateControls, commissionableControls, targetCurrencyID, destinationTextBoxControls[2], destinationLabelControls[2], 0);
		recalculateConvertedCommissionableTotal(currencies, bookingCommissionControls, bookingCommissionCurrencyControls, bookingCommissionExchangeRateControls, commissionCommissionableControls, targetCurrencyID, destinationTextBoxControls[3], destinationLabelControls[3]);
		recalculateConvertedCommissionableTotal(currencies, managingCommissionsControls, managingCommissionCurrencyControls, managingCommissionExchangeRateControls, commissionCommissionableControls, targetCurrencyID, destinationTextBoxControls[4], destinationLabelControls[4]);
		recalculateConvertedTotal(currencies, expenseControls, expenseCurrencyControls, expenseExchangeRateControls, targetCurrencyID, destinationTextBoxControls[5], destinationLabelControls[5]);
	}
	catch (e) {
		alert(e.massage);
	}
}

function recalculateConvertedTotal(currencies, amountControls, currencyControls, exchangeRateControls, targetCurrencyID, destinationTextBoxControlID, destinationLabelControlID) {
	var destinationTextBoxControl = document.getElementById(destinationTextBoxControlID);
	var destinationLabelControl = document.getElementById(destinationLabelControlID);

	destinationTextBoxControl.value = '';
	destinationLabelControl.innerHTML = '';

	var amount = 0;

	if (amountControls.length > 0 && targetCurrencyID > 0) {
		for (var index = 0; index < amountControls.length; index++) {
			var currencyControl = document.getElementById(currencyControls[index]);
			var amountControl = document.getElementById(amountControls[index]);
			var exchangeRateControl = document.getElementById(exchangeRateControls[index]);

//			var currencyID = currencyControl[currencyControl.selectedIndex].value;
//			var rate = getCurrencyRate(currencies, currencyID);
			var rate = exchangeRateControl.value == '' ? 0 : Number(validNumber(exchangeRateControl.value));

			amount += rate * (amountControl.value == '' ? 0 : Number(validNumber(amountControl.value)));
		}

		destinationTextBoxControl.value = amount > 0 ? amount.toFixed(2) : '' ;
		destinationLabelControl.innerHTML = amount > 0 ? getCurrencyAbbreviation(currencies, targetCurrencyID) : '';
	}
}

function recalculateConvertedCommissionableTotal(currencies, amountControls, currencyControls, exchangeRateControls, commissionableControls, targetCurrencyID, destinationTextBoxControlID, destinationLabelControlID) {
	var destinationTextBoxControl = document.getElementById(destinationTextBoxControlID);
	var destinationLabelControl = document.getElementById(destinationLabelControlID);

	destinationTextBoxControl.value = '';
	destinationLabelControl.innerHTML = '';

	var amount = 0;
	var comissionable = 1;

	if (amountControls.length > 0 && targetCurrencyID > 0) {
		for (var index = 0; index < amountControls.length; index++) {
			var commissionableControl = document.getElementById(commissionableControls[index]);

			if (commissionableControl.value == comissionable) {
				var currencyControl = document.getElementById(currencyControls[index]);
				var amountControl = document.getElementById(amountControls[index]);
				var exchangeRateControl = document.getElementById(exchangeRateControls[index]);

//				var currencyID = currencyControl[currencyControl.selectedIndex].value;
//				var rate = getCurrencyRate(currencies, currencyID);
				var rate = exchangeRateControl.value == '' ? 0 : Number(validNumber(exchangeRateControl.value));

				amount += rate * (amountControl.value == '' ? 0 : Number(validNumber(amountControl.value)));
			}
		}

		destinationTextBoxControl.value = amount > 0 ? amount.toFixed(2) : '' ;
		destinationLabelControl.innerHTML = amount > 0 ? getCurrencyAbbreviation(currencies, targetCurrencyID) : '';
	}
}

function recalculateConvertedFeeTotal(currencies, feeAmountControls, feeCurrencyControls, feeExchangeRateControls, feeCommissionableControls, targetCurrencyID, destinationTextBoxControlID, destinationLabelControlID, commissionable) {
	var destinationTextBoxControl = document.getElementById(destinationTextBoxControlID);
	var destinationLabelControl = document.getElementById(destinationLabelControlID);

	destinationTextBoxControl.value = '';
	destinationLabelControl.innerHTML = '';

	var amount = 0;

	if (feeAmountControls.length > 0 && targetCurrencyID > 0) {
		for (var index = 0; index < feeAmountControls.length; index++) {
			var commissionableControl = document.getElementById(feeCommissionableControls[index]);

			if (commissionableControl[commissionableControl.selectedIndex].value == commissionable)
			{
				var currencyControl = document.getElementById(feeCurrencyControls[index]);
				var amountControl = document.getElementById(feeAmountControls[index]);
				var exchangeRateControl = document.getElementById(feeExchangeRateControls[index]);

//				var currencyID = currencyControl[currencyControl.selectedIndex].value;
//				var rate = getCurrencyRate(currencies, currencyID);
				var rate = exchangeRateControl.value == '' ? 0 : Number(validNumber(exchangeRateControl.value));

				amount += rate * (amountControl.value == '' ? 0 : Number(validNumber(amountControl.value)));
			}
		}

		destinationTextBoxControl.value = amount > 0 ? amount.toFixed(2) : '';
		destinationLabelControl.innerHTML = amount > 0 ? getCurrencyAbbreviation(currencies, targetCurrencyID) : '';
	}
}

function recalculateTotal(currencies, amountControls, currencyControls, destinationTextBoxControlID, destinationLabelControlID) {
	var destinationTextBoxControl = document.getElementById(destinationTextBoxControlID);
	var destinationLabelControl = document.getElementById(destinationLabelControlID);

	destinationTextBoxControl.value = '';
	destinationLabelControl.innerHTML = '';

	if (amountControls.length > 0) {
		var currencyID = 0;

		for (var index = 0; index < currencyControls.length; index++) {
			if (document.getElementById(amountControls[index]).value > 0) {
				if (currencyID > 0) {
					var currencyControl = document.getElementById(currencyControls[index]);

					if (currencyID != currencyControl[currencyControl.selectedIndex].value) {
						currencyID = 0;

						break;
					}
				}
				else {
					var compareCurrencyControl = document.getElementById(currencyControls[index]);
					currencyID = compareCurrencyControl[compareCurrencyControl.selectedIndex].value;
				}
			}
		}

		var amount = 0;

		if(currencyID > 0) {
			for (var index = 0; index < amountControls.length; index++) {
				var amountControl = document.getElementById(amountControls[index]);

				amount += (amountControl.value == '' ? 0 : Number(validNumber(amountControl.value)));
			}

			destinationTextBoxControl.value = amount > 0 ? amount.toFixed(2) : '';
			destinationLabelControl.innerHTML = amount > 0 ? getCurrencyAbbreviation(currencies, currencyID) : '';
		}
	}
}

function recalculateCommissionableTotal(currencies, amountControls, currencyControls, commissionableControls, destinationTextBoxControlID, destinationLabelControlID) {
	var destinationTextBoxControl = document.getElementById(destinationTextBoxControlID);
	var destinationLabelControl = document.getElementById(destinationLabelControlID);

	destinationTextBoxControl.value = '';
	destinationLabelControl.innerHTML = '';

	if (amountControls.length > 0) {
		var comissionable = 1;
		var currencyID = 0;

		for (var index = 0; index < currencyControls.length; index++) {
			if (document.getElementById(amountControls[index]).value > 0) {
				var commissionableControl = document.getElementById(commissionableControls[index]);

				if (commissionableControl.value == comissionable) {
					if (currencyID > 0) {
						var currencyControl = document.getElementById(currencyControls[index]);

						if (currencyID != currencyControl[currencyControl.selectedIndex].value) {
							currencyID = 0;

							break;
						}
					}
					else {
						var compareCurrencyControl = document.getElementById(currencyControls[0]);
						currencyID = compareCurrencyControl[compareCurrencyControl.selectedIndex].value;
					}
				}
			}
		}

		if (currencyID > 0) {
			var amount = 0;

			for (var index = 0; index < amountControls.length; index++) {
				var commissionableControl = document.getElementById(commissionableControls[index]);

				if (commissionableControl.value == comissionable) {
					var amountControl = document.getElementById(amountControls[index]);

					amount += (amountControl.value == '' ? 0 : Number(validNumber(amountControl.value)));
				}
			}

			destinationTextBoxControl.value = amount > 0 ? amount.toFixed(2) : '';
			destinationLabelControl.innerHTML = amount > 0 ? getCurrencyAbbreviation(currencies, currencyID) : '';
		}
	}
}

function recalculateFeeTotal(currencies, feeControls, feeCurrencyControls, feeCommissionableControls, destinationTextBoxControlID, destinationLabelControlID, comissionable) {
	var destinationTextBoxControl = document.getElementById(destinationTextBoxControlID);
	var destinationLabelControl = document.getElementById(destinationLabelControlID);

	destinationTextBoxControl.value = '';
	destinationLabelControl.innerHTML = '';

	if (feeControls.length > 0) {
		var currencyID = 0;

		for (var index = 0; index < feeCurrencyControls.length; index++) {
			if (document.getElementById(feeControls[index]).value > 0) {
				var feeCommissionableControl = document.getElementById(feeCommissionableControls[index]);

				if (feeCommissionableControl[feeCommissionableControl.selectedIndex].value == comissionable) {
					var feeCurrencyControl = document.getElementById(feeCurrencyControls[index]);
					currencyID = feeCurrencyControl[feeCurrencyControl.selectedIndex].value;

					break;
				}
			}
		}

		for (var index = 0; index < feeCurrencyControls.length; index++) {
			if (document.getElementById(feeControls[index]).value > 0) {
				var feeCommissionableControl = document.getElementById(feeCommissionableControls[index]);

				if (feeCommissionableControl[feeCommissionableControl.selectedIndex].value == comissionable) {
					var currencyControl = document.getElementById(feeCurrencyControls[index]);

					if (currencyID != currencyControl[currencyControl.selectedIndex].value) {
						currencyID = 0;

						break;
					}
				}
			}
		}

		if (currencyID > 0) {
			var amount = 0;

			for (var index = 0; index < feeControls.length; index++) {
				var feeCommissionableControl = document.getElementById(feeCommissionableControls[index]);

				if (feeCommissionableControl[feeCommissionableControl.selectedIndex].value == comissionable) {
					var amountControl = document.getElementById(feeControls[index]);

					amount += (amountControl.value == '' ? 0 : Number(validNumber(amountControl.value)));
				}
			}

			destinationTextBoxControl.value = amount > 0 ? amount.toFixed(2) : '';
			destinationLabelControl.innerHTML = amount > 0 ? getCurrencyAbbreviation(currencies, currencyID) : '';
		}
	}
}

function getCurrencyRate(currencies, currencyID) {
	var rate = 0;

	for (var index = 0; index < currencies.length; index++) {
		if (currencies[index][0] == currencyID) {

			rate = currencies[index][2];

			break;
		}
	}

	return validNumber(rate);
}

function getCurrencyAbbreviation(currencies, currencyID) {
	var abbreviation = '';

	for (var index = 0; index < currencies.length; index++) {
		if (currencies[index][0] == currencyID) {
			abbreviation = currencies[index][1];

			break;
		}
	}

	return abbreviation;
}


// val - text representation of number
// d - decimals count
function isValidNumber(val, d) {
	var c, i, dot = d == 0, res = true;
	for (i = 0; i < val.length; ++i) {
		c = val.charAt(i);
		if (c == '.') {
			if (dot == true) {
				res = false;
				break;
			}

			dot = true;
		}
		else if ((c < '0' || c > '9') && c != ',') {
			res = false;
			break;
		}
	}

	return res;
}

function doRecurringPing(url, time, init) {
	try {
		if (init != true) {
			var http = new XMLHttpRequest();
			http.open("HEAD", url, true);
			http.send();
		}
	}
	finally {
		setTimeout("doRecurringPing('" + url + "'," + time.toString() + ")", time);
	}
}

function addEventHandler(obj, name, func) {
	if (obj.addEventListener) obj.addEventListener(name, func);
	else obj.attachEvent("on" + name, func);
}

function jsEventHandler(f) {
	this.func = f;
	this.next = null;
}

function jsEvent() {
	this.handlers = null;

	this.add = function(f) {
		var h = this.handlers;
		if (h == null)
			this.handlers = new jsEventHandler(f);
		else {
			while (h.next != null)
				h = h.next;
			h.next = new jsEventHandler(f);
		}
	}

	this.invoke = function() {
		var h = this.handlers;
		while (h != null) {
			h.func();
			h = h.next;
		}
	}
}

