var editingRowsCount = 0;

//
// Some Regular Expressions for checking form data
// Use them in this way:
// if (expression.exec(value) == null) {
//   value is bad, process error here
// }
// else {
//   value is good, continue
// }
//

var reNumeric = /^[-0-9]+$/;
var reMoney = /^\d+(\.\d{1,2}){0,1}$/;
var reAlphaNumeric = /^[-a-zA-Z0-9\u0410-\u044f\u00c0-\u00ff]+$/;
var rePhone = /^[-\[\]\.\(\) a-zA-Z0-9]+$/;
var reCleanText = /^[-_\.a-zA-Z0-9\u0410-\u044f\u00c0-\u00ff]+([\s]*?[-_\.a-zA-Z0-9\u0410-\u044f\u00c0-\u00ff]+)*$/;
var reText = /^[-_\+=\.\,\/!@#\$%&*\(\)a-zA-Z0-9\u0410-\u044f\u00c0-\u00ff]+([\s]*?[-_\+=\.\,\/!@#\$%&*\(\)a-zA-Z0-9\u0410-\u044f\u00c0-\u00ff]+)*$/;
var reAnyText = /^\S+(\s*?\S+)*$/;
var reEmail = /^\w+[\w\-\.]*@\w+[\w\-\.]*\.\w{2,4}(,\w+[\w\-\.]*@\w+[\w\-\.]*\.\w{2,4})*$/;
var reStrict = /^[a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9]+)$/;
var reTime = /^([0-9]{1,2}):([0-9]{1,2}):?([0-9]{1,2})?$/;
var reDate = /^(\d+)-(\d+)-(\d+)$/;

// Creates new window from link
// Parameters:
// LinkURL - link to show in window
// options - object with params for window.open @see window.open docs
// Effect:
// Opens a window with name "Additional" and shows needed link in it.
function LinkWindow(linkURL, options)
{
	if (window.event)
	{
		event.cancelBubble = true;
		event.returnValue = false;
	}

	if (!options)
		options = {};

	var width = options.width || null;
	var height = options.height || null;

	if (!width)
	{
		width = Math.ceil(screen.width/2);
		if (width < 650) width = 650;
	}

	if (!height)
	{
		var height = Math.ceil(screen.height*0.6);
		if (height < 400) height = 400;
	}

	var toolbar = options.toolbar || 0;
	var location = options.location || 0;
	var directories = options.directories || 0;
	var menubar = options.menubar || 0;
	var scrollbars = options.scrollbars || 1;
	var resizable = options.resizable || 0;
	var status = options.status || 0;
	var fullscreen = options.fullscreen || 0;
	var name = options.name || "Additional";

	var left = options.left || Math.ceil(screen.width/4);
	var top = options.top || Math.ceil(screen.height*0.1);
	var oTarget = window.open(linkURL, name, "height="+height+",width="+width+",scrollbars="+scrollbars+",left="+left+",top="+top+",toolbar="+toolbar+",location"+location+",directories"+directories+",menubar"+menubar+",resizable"+resizable+",status"+status+",fullscreen"+fullscreen);
	oTarget.focus();
	return false;
}

// Gets a element by its Id. Used for shorter coding
function GetE(elementId)
{
	return document.getElementById(elementId);
}

function ShowLeftMenuSubs(menuID)
{
	menuObj = document.getElementById(menuID);
	if ("none" == menuObj.style.display)
		menuObj.style.display = "block";
	else
		menuObj.style.display = "none";
}

// Function to check all checkboxes of the form with predefined name
function CheckAll(elm, name)
{
	$(elm.form).getInputs('checkbox', name).each( function(el)
	{
		el.checked = elm.checked;
	});
}

function CorrectMain(mainCheckID, elm)
{
	if ($(elm.form).getInputs('checkbox', name).any(function(el){ return !el.checked }))
		$(mainCheckID).checked = false;
	else
		$(mainCheckID).checked = true;
}

function CheckListSelected(elm, name)
{
	var haveSelected = false;

	if (!$(elm.form).getInputs('checkbox', name).any(function(el){ return el.checked }))
	{
		alert("There are no selected elements!");
		return false;
	}

	return true;
}

function CheckListDelete(elm, name, canEditRows)
{
	if (!CheckListSelected(elm, name))
	{
		return false;
	}

	if (confirm("Are you sure?")) return true;
	return false;
}

function CheckDelete(canEditRows)
{
	if (confirm("Are you sure?")) return true;
	return false;
}

function CheckEditRows()
{
	if (editingRowsCount > 0)
	{
		if (confirm("Discard all unsaved changes?")) return true;
		return false;
	}
	return -1;
}

// Functions to highlight rows on mouseover
function HighlightTR(elm)
{
	// if it is event -> must bind in context of needed TR
	if (!elm.tagName)
		elm = this;

	$(elm).addClassName('tselected');
}

function UnhighlightTR(elm)
{
	// if it is event -> must bind in context of needed TR
	if (!elm.tagName)
		elm = this;

	$(elm).removeClassName('tselected');
}

function HighlightDiv(elm)
{
	elm.style.background = "#E5E5E5";
}

function UnhighlightDiv(elm)
{
	elm.style.background = "#FFFFFF";
}

// debug function for object
function pr(obj)
{
	var res = '';
	if (Object.isString(obj))
	{
		res += obj;
	}
	else
	{
		$H(obj).each(function(el)
		{
			res += el.key + ' = ' + el.value + '<br />';
		});
	}

	var debug = $('debug');
	if (!debug)
	{
		debug = new Element('div', {id:'debug'});
		$(document.body).insert(debug);
	}

	debug.insert(res);
}

// for writing in debug area (alerts is realy bad)
function wr(str, divID)
{
	$(divID || 'debug').insert(str.escapeHTML() +'<br />');
}

function nl2br(str)
{
	var p = /\n/;
	str = str.replace(p, '<br />');
	p = /\r/;
	return str.replace(p, '<br />');
}

//
// removes left and right spaces from string
// Parameters:
// str - some string
// Returns:
// string without left and right spaces
//
function trim(str)
{
	return str.strip(); // see prototype :)
	//str = str.replace(/^(\s)*/, "");
	//str = str.replace(/(\s)*$/, "");
	//return str;
}

/*
// sets classnames to table's TRs for list
// Parameters:
// tlbID - id of a Table Element
*/
function SetRowsClassNames(tlbID)
{
	var trs = $$('#'+tlbID+' tr');
	trs.each(function(row, i)
		{
			row.className = 0 == i%2 ? "teven" : "todd";
		});
}

/*
// disabled first and last sorting arrows (can be used after deleting element)
// Parameters:
// tlbID - id of a Table Element
// rowPrefix - prefix of the TR id (for example, id is "ItemID_123", there prefix is "ItemID_" and "123" will be item id; td with arrows in this case will have ids "TdUp_123" and "TdDown_123")
// url - url prefix for files
// topRowsNum, bottomRowsNum - number of rows on top and bottom of table, which are not in the list (include titles, buttons, etc.)
*/
function UpdateArrows(tlbID, rowPrefix, url, topRowsNum, bottomRowsNum)
{
	var trs = $$('#'+tlbID+' tr');
	// top arrow
	if (trs[topRowsNum].id)
	{
		var idTop = trs[topRowsNum].id.substring(rowPrefix.length, trs[topRowsNum].id.length);
		if (parseInt(idTop, 10) > 0)
		{
			var elmTopUp = $('TdUp_'+idTop).firstDescendant();
			if (elmTopUp.tagName.toLowerCase() == "a")
			{
				elmTopUp.remove();
				var img = '<img src="'+url+'images/icons/icon_up_off.gif" />';
				$('TdUp_'+idTop).innerHTML = img;
			}
		}
	}

	// bottom arrow
	if (trs[trs.length - bottomRowsNum - 1].id)
	{
		var idBottom = trs[trs.length - bottomRowsNum - 1].id.substring(rowPrefix.length, trs[trs.length - bottomRowsNum - 1].id.length);
		if (parseInt(idBottom, 10) > 0)
		{
			var elmBottomDown = $('TdDown_'+idBottom).firstDescendant();
			if (elmBottomDown.tagName.toLowerCase() == "a")
			{
				elmBottomDown.remove();
				var img = '<img src="'+url+'images/icons/icon_down_off.gif" />';
				$('TdDown_'+idBottom).innerHTML = img;
			}
		}
	}
}

/*
// changes places of the rows when sort elements
// Parameters:
// elmTop - TR element which is on top and will be moved 1 line down
// elmBottom - TR element which is under elmTop and will be moved 1 line up
// rowPrefix - prefix of the TR id (for example, id is "ItemID_123", there prefix is "ItemID_" and "123" will be item id; td with arrows in this case will have ids "TdUp_123" and "TdDown_123")
// url - url prefix for files
*/
function ChangeRows(elmTop, elmBottom, rowPrefix, url)
{
	// change positions of elements
	elmTop.insert({before: elmBottom});

	// get IDs
	var idTop = elmTop.id.substring(rowPrefix.length, elmTop.id.length);
	var idBottom = elmBottom.id.substring(rowPrefix.length, elmBottom.id.length);

	// get sort arrows of the moved element
	var elmBottomUp = $('TdUp_'+idBottom).firstDescendant();
	var elmBottomDown = $('TdDown_'+idBottom).firstDescendant();

	// get sort arrows of the previous element
	var elmTopUp = $('TdUp_'+idTop).firstDescendant();
	var elmTopDown = $('TdDown_'+idTop).firstDescendant();

	// change active/not active arrows
	if (elmBottomUp.tagName != elmTopUp.tagName) // up arrows
	{
		elmBottomUp.remove();
		var img = '<img src="'+url+'images/icons/icon_up_off.gif" />';
		$('TdUp_'+idBottom).innerHTML = img;

		elmTopUp.remove();
		var img = "<img src=\""+url+"images/icons/icon_up_on.gif\" title=\"Move Up\" />";
		var linkimg = "<a href=\"#\" onclick=\"return MoveRow('"+idTop+"', 'MoveUp');\">"+img+"</a>";
		$('TdUp_'+idTop).innerHTML = linkimg;
	}
	if (elmBottomDown.tagName != elmTopDown.tagName) // down arrows
	{
		elmBottomDown.remove();
		var img = "<img src=\""+url+"images/icons/icon_down_on.gif\" title=\"Move Down\" />";
		var linkimg = "<a href=\"#\" onclick=\"return MoveRow('"+idBottom+"', 'MoveDown');\">"+img+"</a>";
		$('TdDown_'+idBottom).innerHTML = linkimg;

		elmTopDown.remove();
		var img = '<img src="'+url+'images/icons/icon_down_off.gif" />';
		$('TdDown_'+idTop).innerHTML = img;
	}
}

function CorrectTableLinesStyle(id)
{
	var search = id ? '#'+id+' > tr' : 'table.border_table tbody > tr';

	if (id && $(id))
	{
		$$(search).each(function(el, ind)
		{
			if (ind % 2 == 1)
			{
				el.addClassName('todd');
				wr(el.innerHTML);
			}
		});
	}
	else
	{
		document.observe("dom:loaded", function()
		{
			$$(search).each(function(el, ind)
			{
				if (ind % 2 == 1)
					el.addClassName('todd');

			});
		});
	}
}