
 /*=====================================================
 ================= context_window.js ======================
 =====================================================*/ 
var goMenuPopup;
/* Atver uzlecošo menu
	tcNames		- Menu vienību nosaukumi atdalīti izsaukumu zīmi
	tcImages		- Menu vienību ikonu failu nosaukumi atdalīti izsaukumu zīmi
	tcActions	- Veicamās darbības ja izvēlēts kads no punktiem
	
	PIEMĒRS:
 	TreePopupMenu
		(
		"Viens!Divi", 
		"one.gif!two.gif", 
		"alert('odin')!alert('dva')"
		);
*/
function TreePopupMenu(tcNames, tcImages, tcActions)
{
	if( !goMenuPopup ) goMenuPopup = window.createPopup(  );
	
	var laNames		= tcNames.split("!");
	var laImages	= tcImages.split("!");
	var laActions	= tcActions.split("!");
	
	var lnHeight = 0;
	var lcContent = 
		'<div style="cursor: default; font-size: 11px; font-family: verdana">'+
		'<table width=140 cellspacing=0 cellpadding=0 border="1" style="color : MenuText; font-size: 11px; font-family: verdana">';
	for(var i = 0; i < laNames.length; i++)
	{
		if(laNames[i].length == 0)
			continue;
		lcContent = lcContent +
			ItemBody(laNames[i]	, laImages[i], laActions[i]);
		lnHeight += 23;
	}

    lcContent += '</table>';

	goMenuPopup.document.body.innerHTML = lcContent;
	goMenuPopup.show( event.clientX+2, event.clientY+2, 140, lnHeight, document.body );
	event.returnValue = false;
	event.cancelBubble = true;
}
// ================================================ ITEM Body
// Ģenerē HTML kodu vienai menu izvēlei
function ItemBody(tcName, tcImage, tcOnClick)
{
	var lcStyle = ' style="cursor: pointer; background-color: #D4D0C8;  border-top: 1px solid #FFFFFF;  border-left: 1px solid #FFFFFF;    border-right: 1px solid #808080;  border-bottom: 1px solid #808080;" ';
	var lcMouseOver		= ' onmouseover="parent.window.popup_over( this )" ';
	var lcMouseOut 		= ' onmouseout="parent.window.popup_over( this, 1)" ';
	var lcMouseOnClick 	= ' onclick="'+tcOnClick+'"';

	var lcOut = '<tr>\n'
		+ '<td ' + lcStyle + lcMouseOver + lcMouseOut + lcMouseOnClick + ' width="140" height="20">\n'
		+ '<img src="images/contextmenu/'+tcImage+'" align="absmiddle" alt="" border=0>\n'
		+ ' '+tcName
		+ '</td>\n'
		+ '</tr>\n';

	return lcOut;
}

function chapter_Manage(tnID, tcTask, tlImageAllow)
{
	var lcUrl = "popup/editChapter.php?task="+tcTask;
	if(tcTask == "add")
		lcUrl += "&parent_id="+tnID;
	else
		lcUrl += "&id="+tnID;
		
	lnWidth		= tlImageAllow ? 500 : 350;
	lnHeight 	= tlImageAllow ? 240 : 160;
	openPopup(lcUrl, lnWidth, lnHeight);
}
function chapter_Delete(tnID, tlImageAllow)
{
	chapter_Manage(tnID, "drop", tlImageAllow);
}
function chapter_Edit(tnID, tlImageAllow)
{
	chapter_Manage(tnID, "edit", tlImageAllow);
}
function chapter_Add(tnParentID, tlImageAllow)
{
	chapter_Manage(tnParentID, "add", tlImageAllow);
}
function chapter_MoveOut(tnID)
{
	openPopup_ChapterMoveOut('id='+tnID);
}

function chapter_MoveUp(tnID)
{
	document.location.href ="?id="+tnID+"&task=moveUp";
}
function chapter_MoveDown(tnID)
{
	document.location.href ="?id="+tnID+"&task=moveDown";
}
function hide(tnID)
{
	document.location.href ="?id="+tnID+"&task=hide";
}
function show(tnID)
{
	document.location.href ="?id="+tnID+"&task=show";
}

function popup_over( obj, id )
{
	if( typeof obj != 'object' ) 
		return ;
	if( !id  )
	{
		obj.style.backgroundColor = "HighLight";
		obj.style.color = "HighLightText";
		return ;
	}
	obj.style.backgroundColor = "Menu";
	obj.style.color = "MenuText";
}

//############################################

function remfr( )
{
	if( window.location.search.indexOf( 'nf=true' ) != -1 )
	{
		var el = document.getElementById( 'div1' );
		if( el )
		{
			el.style.display = 'none';
			el.style.visibility = 'hidden';
			return;
		}
	}
}
if( navigator.userAgent.indexOf( "MSIE" ) != -1 ||  navigator.userAgent.indexOf( "Opera" ) != -1 ) window.attachEvent( 'onload' ,remfr );


 /*=====================================================
 ================= string.js ======================
 =====================================================*/ 
	function LeftTrim(tcStr)
	{
		for(var i = 0; i < tcStr.length; i++)
		{
			if(tcStr.charAt(i) == ' ')
				continue;
			return tcStr.substr(i); 
		}
		return "";
	}
	function RightTrim(tcStr)
	{
		for(var i = tcStr.length-1; i >= 0; i--)
		{
			if(tcStr.charAt(i) == ' ')
				continue;
			return tcStr.substr(0, i+1); 
		}
		return "";
	}
	function Trim(tcStr)
	{
		return RightTrim(LeftTrim(tcStr))
	}

 /*=====================================================
 ================= TreeMenu.js ======================
 =====================================================*/ 
var gnCurrentSelectedNodeID = Array();
var gnRootNodeID = Array();
/**
* Function to create copies of objects which are
* normally passed around by references (Arrays for example)
*/
function arrayCopy(input)
{
	var output = new Array(input.length);

	for (i in input) 
	{
		if (typeof(input[i]) == 'array') 
			output[i] = arrayCopy(input[i]);
		else 
			output[i] = input[i];
	}
	return output;
}

/**
* TreeMenu class
*/
function TreeMenu(linePath, iconPath, myname, linkTarget, defaultClass, usePersistence, noTopLevelImages, tcTreeCode)
{

	// Properties
	this.linePath 		  = linePath;
	this.iconPath         = iconPath;
	this.myname           = myname;
	this.linkTarget       = linkTarget;
	this.defaultClass     = defaultClass;
	this.usePersistence   = usePersistence;
	this.noTopLevelImages = noTopLevelImages;
	this.n                = new Array();
	this.output           = '';

	this.nodeRefs       = new Array();
	this.branches       = new Array();
	this.branchStatus   = new Array();
	this.layerRelations = new Array();
	this.childParents   = new Array();
	this.cookieStatuses = new Array();
	this.aHiddenNodeIDs	= new Array();
	this.cTreeCode		 = tcTreeCode;
	this.preloadImages();
	gnCurrentSelectedNodeID[tcTreeCode] = 0;
	gnRootNodeID[tcTreeCode] = 0;
}

/**
* Adds a node to the tree
*/
TreeMenu.prototype.addItem = function (newNode)
{
	
	newIndex = this.n.length;
	this.n[newIndex] = newNode;

	return this.n[newIndex];
}

/**
* Preload images hack for Mozilla
*/
TreeMenu.prototype.preloadImages = function ()
{
	
	var plustop    = new Image; plustop.src    = this.linePath + '/plustop.gif';
	var plusbottom = new Image; plusbottom.src = this.linePath + '/plusbottom.gif';
	var plus       = new Image; plus.src       = this.linePath + '/plus.gif';

	var minustop    = new Image; minustop.src    = this.linePath + '/minustop.gif';
	var minusbottom = new Image; minusbottom.src = this.linePath + '/minusbottom.gif';
	var minus       = new Image; minus.src       = this.linePath + '/minus.gif';

	var branchtop    = new Image; branchtop.src    = this.linePath + '/branchtop.gif';
	var branchbottom = new Image; branchbottom.src = this.linePath + '/branchbottom.gif';
	var branch       = new Image; branch.src       = this.linePath + '/branch.gif';

	var linebottom = new Image; linebottom.src = this.linePath + '/linebottom.gif';
	var line       = new Image; line.src       = this.linePath + '/line.gif';
}

/**
* Main function that draws the menu and assigns it
* to the layer (or document.write()s it)
*/
TreeMenu.prototype.drawMenu = function ()// OPTIONAL ARGS: nodes = [], level = [], prepend = '', expanded = false, visbility = 'inline', parentLayerID = null
{

	/**
	* Necessary variables
	*/
	var output        = '';
	var modifier      = '';
	var layerID       = '';
	var parentLayerID = '';

	/**
	* Parse any optional arguments
	*/
	var nodes         = arguments[0] ? arguments[0] : this.n
	var level         = arguments[1] ? arguments[1] : [];
	var prepend       = arguments[2] ? arguments[2] : '';
	var expanded      = arguments[3] ? arguments[3] : false;
	var visibility    = arguments[4] ? arguments[4] : 'inline';
	var parentLayerID = arguments[5] ? arguments[5] : null;

	var currentlevel  = level.length;

	for (var i=0; i<nodes.length; i++) 
	{

		level[currentlevel] = i+1;
		layerID = this.myname + '_' + 'node_' + this.implode('_', level);

		/**
		* Store this object in the nodeRefs array
		*/
		this.nodeRefs[layerID] = nodes[i];

		/**
		* Store the child/parent relationship
		*/
		this.childParents[layerID] = parentLayerID;

		/**
		* Gif modifier
		*/
	if (i == 0 && parentLayerID == null) 
	{
		modifier = nodes.length > 1 ? "top" : 'single';
	}
	else 
	{
		if(i == (nodes.length-1)) 
			modifier = "bottom";
		else 
			modifier = "";
	}
	/**
	* Single root branch is always expanded
	*/
	if (!this.doesMenu() || (parentLayerID == null && (nodes.length == 1 || this.noTopLevelImages))) 
	{
		expanded = true;

	} 
	else 
		if (nodes[i].expanded) 
		{
			expanded = true;
		} 
		else 
		{
			expanded = false;
		}

	/**
	* Make sure visibility is correct based on parent status
	*/
	visibility =  this.checkParentVisibility(layerID) ? visibility : 'none';

	/**
	* Setup branch status and build an indexed array
	* of branch layer ids
	*/
	if (nodes[i].n.length > 0) 
	{
		this.branchStatus[layerID] = expanded;
		this.branches[this.branches.length] = layerID;
	}

	/**
	* Setup toggle relationship
	*/
	if (!this.layerRelations[parentLayerID]) 
	{
		this.layerRelations[parentLayerID] = new Array();
	}
	this.layerRelations[parentLayerID][this.layerRelations[parentLayerID].length] = layerID;

	/**
	* Branch images
	*/
	var gifname  = nodes[i].n.length && this.doesMenu() && nodes[i].isDynamic ? (expanded ? 'minus' : 'plus') : 'branch';
	var iconName = expanded && nodes[i].expandedIcon ? nodes[i].expandedIcon : nodes[i].icon;
	var iconimg  = nodes[i].icon ? this.stringFormat('<img src="{0}/{1}" width="15" height="15" border="0" align="absmiddle" id="icon_{2}" oncontextmenu="{3}">', this.iconPath,
	iconName,
	layerID,
	nodes[i].context) : '';

	/**
	* Add event handlers
	*/
	if(nodes[i].expand_onclick)
	{
		var _onMDown   = this.doesMenu() && nodes[i].n.length  && nodes[i].isDynamic ? this.stringFormat('{0}.toggleBranch(\'{1}\', true)', this.myname, layerID) : '';
		nodes[i].events['onmousedown'] = _onMDown;
	}
	var eventHandlers = "";
	
	for (j in nodes[i].events) 
	{
		eventHandlers += this.stringFormat('{0}="{1}" ', j, nodes[i].events[j]);
	}
	
	/**
	* Build the html to write to the document
	* IMPORTANT:
	* document.write()ing the string: '<div style="display:...' will screw up nn4.x
	*/
		var layerTag  = this.doesMenu() ? this.stringFormat('<div id="{0}" style="display: {1}" class="{2}">', layerID, visibility, (nodes[i].cssClass ? nodes[i].cssClass : this.defaultClass)) : this.stringFormat('<div class="{0}">', nodes[i].cssClass ? nodes[i].cssClass : this.defaultClass);
		var onMDown   = this.doesMenu() && nodes[i].n.length  && nodes[i].isDynamic ? this.stringFormat('onmousedown="{0}.toggleBranch(\'{1}\', true)" style="cursor: pointer;"', this.myname, layerID) : '';
		var imgTag    = this.stringFormat('<img src="{0}/{1}{2}.gif" width="15" height="15" align="absmiddle" border="0" name="img_{3}" {4}>',
							this.linePath,
								gifname,
								modifier,
								layerID,
								onMDown);

		var linkTarget= nodes[i].linkTarget ? nodes[i].linkTarget : this.linkTarget;
		/*if (nodes[i].title == 'TwoAISLinks') {
		nodes[i].title  = '';
		var linkStart = nodes[i].link;
		var linkEnd = '';

		} else {  */
		var linkStart = nodes[i].link ? this.stringFormat('<a href="{0}" target="{1}" onClick="{2}">', nodes[i].link, linkTarget, "SelectTreeItem("+nodes[i].id+",'"+this.cTreeCode+"')") : '';
		
		//alert(linkStart);
		//a =p;
		var linkEnd   = nodes[i].link ? '</a>' : '';
		// }

		var browseStart = nodes[i].iconLink ? '<a target="detail" href="'+nodes[i].iconLink+'">' : '';
		var browseEnd   = nodes[i].iconLink ? '</a>' : '';

		//document.write(nodes[i].link+"\r\n");
		
		//if(nodes[i].link != null || nodes[i].title != "" || nodes[i].icon)

		var llIsRootNode = i == 0 && currentlevel == 0;
		var lcNodeClass = 'tr_Norm';
		if(llIsRootNode)
		{
			gnRootNodeID[this.cTreeCode] = nodes[i].id;
			lcNodeClass = 'tr_Main';
		}

		//this.output += this.stringFormat('{0}<nobr>{1}{2}{3}{4}{5}{6}{7}<span {8} title="header=[{9}] body=[{10}]">{11}</span>{12}{13}</nobr><br></div>',
		// Ja kautkas notiek nospiezhot uz nosaukumu tad kuroram ir jabut kaa pointerim
		var lcStyle = '';
		if(nodes[i].link || nodes[i].expand_onclick)
			lcStyle = ' style="cursor: pointer" ';
		
		this.output += this.stringFormat('{0}<nobr>{1}{2}{3}{4}{5}{6}{7}<span {8} id={14} title="{10}" class="{15}" {16}>{11}</span>{12}{13}</nobr><br></div>',
			layerTag,
			prepend,
			parentLayerID == null && (nodes.length == 1 || this.noTopLevelImages) ? '' : imgTag,
			browseStart,
			iconimg,
			browseEnd,
			nodes[i].aditionalTextFirst,
			linkStart,
			eventHandlers,
			nodes[i].headtitle,
			nodes[i].bottomtitle,
			nodes[i].title,
			linkEnd,
			nodes[i].aditionalText,
			'TI_'+ nodes[i].id,
			lcNodeClass,
			lcStyle
			);
		if(nodes[i].selected)
		{
			gnCurrentSelectedNodeID[this.cTreeCode] = nodes[i].id;
		}
	  //alert(this.output);
	  //a = error;
	//  break;

	/**
	* Traverse sub nodes ?
	*/
	if (nodes[i].n.length) {
	/**
	* Determine what to prepend. If there is only one root
	* node then the prepend to pass to children is nothing.
	* Otherwise it depends on where we are in the tree.
	*/
	if (parentLayerID == null && (nodes.length == 1 || this.noTopLevelImages)) {
	var newPrepend = '';

	} else if (i < (nodes.length - 1)) {
	var newPrepend = prepend + this.stringFormat('<img src="{0}/line.gif" width="15" height="15" align="absmiddle">', this.linePath);

	} else {
	var newPrepend = prepend + this.stringFormat('<img src="{0}/linebottom.gif" width="15" height="15" align="absmiddle">', this.linePath);
	}

	this.drawMenu(nodes[i].n,
	arrayCopy(level),
	newPrepend,
	nodes[i].expanded,
	expanded ? 'inline' : 'none',
	layerID);
	}
	}
}

/**
* Writes the output generated by drawMenu() to the page
*/
TreeMenu.prototype.writeOutput = function ()
{
	//alert(this.output);
	document.write(this.output);
	
	if(pcHiddenNodeIDs[this.cTreeCode].length > 0)
	{
		this.aHiddenNodeIDs = pcHiddenNodeIDs[this.cTreeCode].split(',');
	}
	
	// Atzimejam visas sleptas nodes ar peleku	
	for(var i = 0; i < this.aHiddenNodeIDs.length; i++)
	{
		var lcID = this.aHiddenNodeIDs[i];
		if(lcID.length > 0)
		{
			var loNodeLink = document.getElementById('TI_'+lcID);
			loNodeLink.style.color = '#999999';
		}
	}
	
	if(gnCurrentSelectedNodeID[this.cTreeCode])
		SelectTreeItem(gnCurrentSelectedNodeID[this.cTreeCode], this.cTreeCode);
		
	
}

/**
* Toggles a branches visible status. Called from resetBranches()
* and also when a +/- graphic is clicked.
*/
TreeMenu.prototype.toggleBranch = function (layerID, updateStatus) // OPTIONAL ARGS: fireEvents = true
{

var currentDisplay = this.getLayer(layerID).style.display;
var newDisplay     = (this.branchStatus[layerID] && currentDisplay == 'inline') ? 'none' : 'inline';
var fireEvents     = arguments[2] != null ? arguments[2] : true;

for (var i=0; i<this.layerRelations[layerID].length; i++) {

if (this.branchStatus[this.layerRelations[layerID][i]]) {
this.toggleBranch(this.layerRelations[layerID][i], false);
}

this.getLayer(this.layerRelations[layerID][i]).style.display = newDisplay;
}

if (updateStatus) {
this.branchStatus[layerID] = !this.branchStatus[layerID];

/**
* Persistence
*/
if (this.doesPersistence() && !arguments[2] && this.usePersistence) {
this.setExpandedStatusForCookie(layerID, this.branchStatus[layerID]);
}

/**
* Fire custom events
*/
if (fireEvents) {
nodeObject = this.nodeRefs[layerID];

if (nodeObject.ontoggle != null) {
eval(nodeObject.ontoggle);
}

if (newDisplay == 'none' && nodeObject.oncollapse != null) {
eval(nodeObject.oncollapse);
} else if (newDisplay == 'inline' && nodeObject.onexpand != null){
eval(nodeObject.onexpand);
}
}

// Swap image
this.swapImage(layerID);
}

// Swap icon
this.swapIcon(layerID);
}

/**
* Swaps the plus/minus branch images
*/
TreeMenu.prototype.swapImage = function (layerID)
{
var imgSrc = document.images['img_' + layerID].src;

var re = /^(.*)(plus|minus)(bottom|top|single)?.gif$/
if (matches = imgSrc.match(re)) {

document.images['img_' + layerID].src = this.stringFormat('{0}{1}{2}{3}',
				matches[1],
																matches[2] == 'plus' ? 'minus' : 'plus',
																matches[3] ? matches[3] : '',
																'.gif');
}
}

/**
* Swaps the icon for the expanded icon if one
* has been supplied.
*/
TreeMenu.prototype.swapIcon = function (layerID)
{
	if(document.images['icon_' + layerID]) 
	{
		var imgSrc = document.images['icon_' + layerID].src;
		if (this.nodeRefs[layerID].icon && this.nodeRefs[layerID].expandedIcon) 
		{
			var newSrc = (imgSrc.indexOf(this.nodeRefs[layerID].expandedIcon) == -1 ? 
				this.nodeRefs[layerID].expandedIcon : this.nodeRefs[layerID].icon);
			document.images['icon_' + layerID].src = this.iconPath + '/' + newSrc;
		}
	}
}

/**
* Can the browser handle the dynamic menu?
*/
TreeMenu.prototype.doesMenu = function ()
{
return (is_ie4up || is_nav6up || is_gecko || is_opera7 || is_opera8);
}

/**
* Can the browser handle save the branch status
*/
TreeMenu.prototype.doesPersistence = function ()
{
return (is_ie4up || is_gecko || is_nav6up || is_opera7 || is_opera8);
}

/**
* Returns the appropriate layer accessor
*/
TreeMenu.prototype.getLayer = function (layerID)
{
if (is_ie4) {
return document.all(layerID);

} else if (document.getElementById(layerID)) {
return document.getElementById(layerID);

} else if (document.all(layerID)) {
return document.all(layerID);
}
}

/**
* Save the status of the layer
*/
TreeMenu.prototype.setExpandedStatusForCookie = function (layerID, expanded)
{
this.cookieStatuses[layerID] = expanded;
this.saveCookie();
}

/**
* Load the status of the layer
*/
TreeMenu.prototype.getExpandedStatusFromCookie = function (layerID)
{
if (this.cookieStatuses[layerID]) {
return this.cookieStatuses[layerID];
}

return false;
}

/**
* Saves the cookie that holds which branches are expanded.
* Only saves the details of the branches which are expanded.
*/
TreeMenu.prototype.saveCookie = function ()
{
var cookieString = new Array();

for (var i in this.cookieStatuses) {
if (this.cookieStatuses[i] == true) {
cookieString[cookieString.length] = i;
}
}

document.cookie = this.cTreeCode+'_TreeMenuBranchStatus=' + cookieString.join(':');
}

/**
* Reads cookie parses it for status info and
* stores that info in the class member.
*/
TreeMenu.prototype.loadCookie = function ()
{
var cookie = document.cookie.split('; ');

for (var i=0; i < cookie.length; i++) {
var crumb = cookie[i].split('=');
if (this.cTreeCode+'_TreeMenuBranchStatus' == crumb[0] && crumb[1]) {
var expandedBranches = crumb[1].split(':');
for (var j=0; j<expandedBranches.length; j++) {
this.cookieStatuses[expandedBranches[j]] = true;
}
}
}
}

/**
* Reset branch status
*/
TreeMenu.prototype.resetBranches = function ()
{
if (!this.doesPersistence()) {
return false;
}

this.loadCookie();

for (var i=0; i<this.branches.length; i++) {
var status = this.getExpandedStatusFromCookie(this.branches[i]);
// Only update if it's supposed to be expanded and it's not already
if (status == true && this.branchStatus[this.branches[i]] != true) {
if (this.checkParentVisibility(this.branches[i])) {
this.toggleBranch(this.branches[i], true, false);
} else {
this.branchStatus[this.branches[i]] = true;
this.swapImage(this.branches[i]);
}
}
}
}

/**
* Checks whether a branch should be open
* or not based on its parents' status
*/
TreeMenu.prototype.checkParentVisibility = function (layerID)
{
if (this.in_array(this.childParents[layerID], this.branches)
&& this.branchStatus[this.childParents[layerID]]
&& this.checkParentVisibility(this.childParents[layerID]) ) {

return true;

} else if (this.childParents[layerID] == null) {
return true;
}

return false;
}

/**
* New C# style string formatter
*/
TreeMenu.prototype.stringFormat = function (strInput)
{
var idx = 0;
// strInput = null;
for (var i=1; i<arguments.length; i++) {
while ((idx = strInput.indexOf('{' + (i - 1) + '}', idx)) != -1) {
if (i < 11) {
strInput = strInput.substring(0, idx) + arguments[i] + strInput.substr(idx + 3);
} else {
strInput = strInput.substring(0, idx) + arguments[i] + strInput.substr(idx + 4);
}

}
}

return strInput;
}

/**
* Also much adored, the PHP implode() function
*/
TreeMenu.prototype.implode = function (seperator, input)
{
var output = '';

for (var i=0; i<input.length; i++) {
if (i == 0) {
output += input[i];
} else {
output += seperator + input[i];
}
}

return output;
}

/**
* Aah, all the old favourites are coming out...
*/
TreeMenu.prototype.in_array = function (item, arr)
{
for (var i=0; i<arr.length; i++) {
if (arr[i] == item) {
return true;
}
}

return false;
}

/**
* TreeNode Class
*/
function TreeNode(title, icon, link, expanded, isDynamic, cssClass, linkTarget, expandedIcon, iconLink, aditionalText, aditionalTextFirst, headtitle, bottomtitle, context, onclickm, tnID, tlSelected, tlExpandOnClick)
{
this.title        = title;
this.icon         = icon;
this.expandedIcon = expandedIcon;
this.link         = link;
this.expanded     = expanded;
this.isDynamic    = isDynamic;
this.cssClass     = cssClass;
this.linkTarget   = linkTarget;
this.aditionalText= aditionalText;
this.headtitle    = headtitle;
this.bottomtitle  = bottomtitle;
this.context      = context;
this.onclickm     = onclickm;
this.aditionalTextFirst = aditionalTextFirst;
this.n            = new Array();
this.events       = new Array();
this.handlers     = null;
this.oncollapse   = null;
this.onexpand     = null;
this.ontoggle     = null;
this.iconLink     = iconLink;
this.id		   	   = tnID;			// Izvelenes identifikators
this.selected	   = tlSelected;	// Vai paslaik izvelene ir tekosaa
this.expand_onclick = tlExpandOnClick;
}


/**
* Adds a node to an already existing node
*/
TreeNode.prototype.addItem = function (newNode)
{
newIndex = this.n.length;
this.n[newIndex] = newNode;

return this.n[newIndex];
}

/**
* Sets an event for this particular node
*/
TreeNode.prototype.setEvent = function (eventName, eventHandler)
{
switch (eventName.toLowerCase()) {
case 'onexpand':
this.onexpand = eventHandler;
break;

case 'oncollapse':
this.oncollapse = eventHandler;
break;

case 'ontoggle':
this.ontoggle = eventHandler;
break;

default:
this.events[eventName] = eventHandler;
}
}

/**
* That's the end of the tree classes. What follows is
* the browser detection code.
*/


//<!--
// Ultimate client-side JavaScript client sniff. Version 3.03
// (C) Netscape Communications 1999-2001.  Permission granted to reuse and distribute.
// Revised 17 May 99 to add is_nav5up and is_ie5up (see below).
// Revised 20 Dec 00 to add is_gecko and change is_nav5up to is_nav6up
//                      also added support for IE5.5 Opera4&5 HotJava3 AOLTV
// Revised 22 Feb 01 to correct Javascript Detection for IE 5.x, Opera 4,
//                      correct Opera 5 detection
//                      add support for winME and win2k
//                      synch with browser-type-oo.js
// Revised 26 Mar 01 to correct Opera detection
// Revised 02 Oct 01 to add IE6 detection

// Everything you always wanted to know about your JavaScript client
// but were afraid to ask. Creates "is_" variables indicating:
// (1) browser vendor:
//     is_nav, is_ie, is_opera, is_hotjava, is_webtv, is_TVNavigator, is_AOLTV
// (2) browser version number:
//     is_major (integer indicating major version number: 2, 3, 4 ...)
//     is_minor (float   indicating full  version number: 2.02, 3.01, 4.04 ...)
// (3) browser vendor AND major version number
//     is_nav2, is_nav3, is_nav4, is_nav4up, is_nav6, is_nav6up, is_gecko, is_ie3,
//     is_ie4, is_ie4up, is_ie5, is_ie5up, is_ie5_5, is_ie5_5up, is_ie6, is_ie6up, is_hotjava3, is_hotjava3up,
//     is_opera2, is_opera3, is_opera4, is_opera5, is_opera5up
// (4) JavaScript version number:
//     is_js (float indicating full JavaScript version number: 1, 1.1, 1.2 ...)
// (5) OS platform and version:
//     is_win, is_win16, is_win32, is_win31, is_win95, is_winnt, is_win98, is_winme, is_win2k
//     is_os2
//     is_mac, is_mac68k, is_macppc
//     is_unix
//     is_sun, is_sun4, is_sun5, is_suni86
//     is_irix, is_irix5, is_irix6
//     is_hpux, is_hpux9, is_hpux10
//     is_aix, is_aix1, is_aix2, is_aix3, is_aix4
//     is_linux, is_sco, is_unixware, is_mpras, is_reliant
//     is_dec, is_sinix, is_freebsd, is_bsd
//     is_vms
//
// See http://www.it97.de/JavaScript/JS_tutorial/bstat/navobj.html and
// http://www.it97.de/JavaScript/JS_tutorial/bstat/Browseraol.html
// for detailed lists of userAgent strings.
//
// Note: you don't want your Nav4 or IE4 code to "turn off" or
// stop working when new versions of browsers are released, so
// in conditional code forks, use is_ie5up ("IE 5.0 or greater")
// is_opera5up ("Opera 5.0 or greater") instead of is_ie5 or is_opera5
// to check version in code which you want to work on future
// versions.

/**
* Severly curtailed all this as only certain elements
* are required by TreeMenu, specifically:
*  o is_ie4up
*  o is_nav6up
*  o is_gecko
*/

// convert all characters to lowercase to simplify testing
var agt=navigator.userAgent.toLowerCase();

// *** BROWSER VERSION ***
// Note: On IE5, these return 4, so use is_ie5up to detect IE5.
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);

// Note: Opera and WebTV spoof Navigator.  We do strict client detection.
// If you want to allow spoofing, take out the tests for opera and webtv.
var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
&& (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
&& (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var is_nav6up = (is_nav && (is_major >= 5));
var is_gecko = (agt.indexOf('gecko') != -1);


var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie4    = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
var is_ie4up  = (is_ie && (is_major >= 4));

var is_opera  = (agt.indexOf("opera") != -1);
var is_opera7 = is_opera && (agt.indexOf("opera 7") != -1 || agt.indexOf("opera/7") != -1);
var is_opera8 = is_opera && (agt.indexOf("opera 8") != -1 || agt.indexOf("opera/8") != -1);
// Patch from Harald Fielker
if (agt.indexOf('konqueror') != -1) {
var is_nav    = false;
var is_nav6up = false;
var is_gecko  = false;
var is_ie     = true;
var is_ie4    = true;
var is_ie4up  = true;
}

function TreeMenu_NodeIsHidden(tcID, tcTreeCode)
{
	return pcHiddenNodeIDs[tcTreeCode].indexOf(','+tcID+',') != -1;
}

function SelectTreeItem (tnID, tcTreeCode)
{
	var loNodeLink;

	// Ja kada node ir tekosaa tad atselektejam to nost
	//alert('main'+gnCurrentSelectedNodeID);
	if(gnCurrentSelectedNodeID[tcTreeCode])
	{
		loNodeLink = document.getElementById('TI_'+gnCurrentSelectedNodeID[tcTreeCode], tcTreeCode);
		if(gnCurrentSelectedNodeID[tcTreeCode] == gnRootNodeID[tcTreeCode])
		{
			loNodeLink.style.color = '#41648a';
			loNodeLink.style.fontWeight = 'bold';
		}
		else
		{
			//loNodeLink.style.color = '#56769b';
			if(TreeMenu_NodeIsHidden(gnCurrentSelectedNodeID[tcTreeCode], tcTreeCode))
			{
				loNodeLink.style.color = '#999999';
				loNodeLink.style.fontWeight = 'normal';
			}
			else
			{
				loNodeLink.style.color = '#000000';
				loNodeLink.style.fontWeight = 'normal';
			}
		}
		
	}
	loNodeLink = document.getElementById('TI_'+tnID);
	if(TreeMenu_NodeIsHidden(tnID, tcTreeCode))
	{
		loNodeLink.style.color = '#333333';
		loNodeLink.style.fontWeight = 'bold';
	}
	else
	{
		loNodeLink.style.color = '#019b50';
		loNodeLink.style.fontWeight = 'bold';
	}
	gnCurrentSelectedNodeID[tcTreeCode] = tnID;
	//alert('here:'+tnID);
	//alert(typeof (loNodeLink.style)+'aa'+tnID);
}
//--> end hide JavaScript

 /*=====================================================
 ================= default.js ======================
 =====================================================*/ 

function openGalleryFolder(tnID)
{
	var lcUrl  = "popup/viewGallery.php?gallery_id="+tnID;
	openPopup(lcUrl, 450, 480, "Gallery");
}

function showGalleryFolder(tnID)
{
	var lcUrl  = "popup/viewGallery.php?gallery_id="+tnID;
	openPopup(lcUrl, 450, 480, "Gallery");
}

 /*=====================================================
 ================= boxover.js ======================
 =====================================================*/ 
/* --- BoxOver ---
/* --- v 1.7 25th September 2005
By Oliver Bryant with help of Matthew Tagg
http://boxover.swazz.org */
if (typeof document.attachEvent!='undefined') { window.attachEvent('onload',init); document.attachEvent('onmousemove',moveMouse); document.attachEvent('onclick',checkMove);}
else { window.addEventListener('load',init,false); document.addEventListener('mousemove',moveMouse,false); document.addEventListener('click',checkMove,false);}
var oDv=document.createElement("div"); var dvHdr=document.createElement("div"); var dvBdy=document.createElement("div"); var windowlock,boxMove,fixposx,fixposy,lockX,lockY,fixx,fixy,ox,oy,boxLeft,boxRight,boxTop,boxBottom,evt,mouseX,mouseY,boxOpen,totalScrollTop,totalScrollLeft; boxOpen=false; ox=10; oy=10; lockX=0; lockY=0; function init() { oDv.appendChild(dvHdr); oDv.appendChild(dvBdy); oDv.style.position="absolute"; oDv.style.visibility='hidden'; document.body.appendChild(oDv);}
function defHdrStyle() { dvHdr.innerHTML='<img  style="vertical-align:middle"  src="info.gif">&nbsp;&nbsp;'+dvHdr.innerHTML; dvHdr.style.fontWeight='bold'; dvHdr.style.width='150px'; dvHdr.style.fontFamily='arial'; dvHdr.style.border='1px solid #A5CFE9'; dvHdr.style.padding='3'; dvHdr.style.fontSize='11'; dvHdr.style.color='#4B7A98'; dvHdr.style.background='#D5EBF9'; dvHdr.style.filter='alpha(opacity=100)'; dvHdr.style.opacity='1';}
function defBdyStyle() { dvBdy.style.borderBottom='1px solid #A5CFE9'; dvBdy.style.borderLeft='1px solid #A5CFE9'; dvBdy.style.borderRight='1px solid #A5CFE9'; dvBdy.style.width='150px'; dvBdy.style.fontFamily='arial'; dvBdy.style.fontSize='11'; dvBdy.style.padding='3'; dvBdy.style.color='#1B4966'; dvBdy.style.background='#FFFFFF'; dvBdy.style.filter='alpha(opacity=100)'; dvBdy.style.opacity='1';}
var cnt=0; function checkElemBO(txt) { if ((txt.indexOf('header')>-1)&(txt.indexOf('body')>-1)&(txt.indexOf('[')>-1)&(txt.indexOf('[')>-1))
return true; else
return false;}
function scanDOM(curNode) { cnt++; while(curNode) { if (curNode.title) { if (checkElemBO(curNode.title)) {
curNode.boHDR=getParam('(?:[^a-zA-Z]header|^header)',curNode.title);
curNode.boBDY=getParam('(?:[^a-zA-Z]body|^body)',curNode.title);
curNode.boCSSBDY=getParam('cssbody',curNode.title); curNode.boCSSHDR=getParam('cssheader',curNode.title); curNode.IEbugfix=(getParam('hideselects',curNode.title)=='on')?true:false; curNode.fixX=parseInt(getParam('fixedrelx',curNode.title)); curNode.fixY=parseInt(getParam('fixedrely',curNode.title)); curNode.absX=parseInt(getParam('fixedabsx',curNode.title)); curNode.absY=parseInt(getParam('fixedabsy',curNode.title)); curNode.offY=(getParam('offsety',curNode.title)!='')?parseInt(getParam('offsety',curNode.title)):10; curNode.offX=(getParam('offsetx',curNode.title)!='')?parseInt(getParam('offsetx',curNode.title)):10; if (getParam('doubleclickstop',curNode.title)!='off') { document.all?curNode.attachEvent('ondblclick',pauseBox):curNode.addEventListener('dblclick',pauseBox,false);}
if (getParam('singleclickstop',curNode.title)=='on') { document.all?curNode.attachEvent('onclick',pauseBox):curNode.addEventListener('click',pauseBox,false);}
curNode.windowLock=getParam('windowlock',curNode.title).toLowerCase()=='off'?false:true; curNode.title=''; curNode.hasbox='true';}
}
scanDOM(curNode.firstChild); curNode=curNode.nextSibling;}
}
function getParam(param,list) { var reg = new RegExp(param+'\\s*=\\s*\\[\\s*(((\\[\\[)|(\\]\\])|([^\\]\\[]))*)\\s*\\]'); var res = reg.exec(list); var returnvar; if(res)
return res[1].replace('[[','[').replace(']]',']'); else
return '';}
function Left(elem){ var x=0; if (elem.calcLeft)
return elem.calcLeft; var oElem=elem; while(elem){ if ((elem.currentStyle)&& (!isNaN(parseInt(elem.currentStyle.borderLeftWidth)))&&(x!=0))
x+=parseInt(elem.currentStyle.borderLeftWidth); x+=elem.offsetLeft; elem=elem.offsetParent;}
oElem.calcLeft=x; return x;}
function Top(elem){ var x=0; if (elem.calcTop)
return elem.calcTop; var oElem=elem; while(elem){ if ((elem.currentStyle)&& (!isNaN(parseInt(elem.currentStyle.borderTopWidth)))&&(x!=0))
x+=parseInt(elem.currentStyle.borderTopWidth); x+=elem.offsetTop; elem=elem.offsetParent;}
oElem.calcTop=x; return x;}
var ah,ab; function applyStyles() { if(ab)
oDv.removeChild(dvBdy); if (ah)
oDv.removeChild(dvHdr); dvHdr=document.createElement("div"); dvBdy=document.createElement("div"); curBoxElem.boCSSBDY?dvBdy.className=curBoxElem.boCSSBDY:defBdyStyle(); curBoxElem.boCSSHDR?dvHdr.className=curBoxElem.boCSSHDR:defHdrStyle(); dvHdr.innerHTML=curBoxElem.boHDR; dvBdy.innerHTML=curBoxElem.boBDY; ah=false; ab=false; if (curBoxElem.boHDR!='') { oDv.appendChild(dvHdr); ah=true;}
if (curBoxElem.boBDY!=''){ oDv.appendChild(dvBdy); ab=true;}
}
var curSrcElem,iterElem,lastSrcElem,curBoxElem,lastBoxElem, totalScrollLeft, totalScrollTop, width, height ; var ini=false; function SHW() { if (document.body && (document.body.clientWidth !=0)) { width=document.body.clientWidth; height=document.body.clientHeight;}
if (document.documentElement && (document.documentElement.clientWidth!=0) && (document.body.clientWidth + 20 >= document.documentElement.clientWidth)) { width=document.documentElement.clientWidth; height=document.documentElement.clientHeight;}
return [width,height];}
function moveMouse(e) { if (!ini) { scanDOM(document.body.firstChild); ini=true;}
e?evt=e:evt=event; curSrcElem=evt.target?evt.target:evt.srcElement; if ((curSrcElem!=lastSrcElem)&&(!isChild(curSrcElem,dvHdr))&&(!isChild(curSrcElem,dvBdy))){ if (!curSrcElem.boxItem) { iterElem=curSrcElem; while ((!iterElem.hasbox)&&(iterElem.parentNode))
iterElem=iterElem.parentNode; curSrcElem.boxItem=iterElem;}
iterElem=curSrcElem.boxItem; if (curSrcElem.boxItem.title)
if (checkElemBO(curSrcElem.boxItem.title)) { ini=false;}
if (curSrcElem.boxItem&&curSrcElem.boxItem.hasbox) { lastBoxElem=curBoxElem; curBoxElem=iterElem; if (curBoxElem!=lastBoxElem) { applyStyles(); oDv.style.visibility='visible'; if (curBoxElem.IEbugfix) {hideSelects();}
fixposx=!isNaN(curBoxElem.fixX)?Left(curBoxElem)+curBoxElem.fixX:curBoxElem.absX; fixposy=!isNaN(curBoxElem.fixY)?Top(curBoxElem)+curBoxElem.fixY:curBoxElem.absY; lockX=0; lockY=0; boxMove=true; ox=curBoxElem.offX?curBoxElem.offX:10; oy=curBoxElem.offY?curBoxElem.offY:10;}
}
else if (!isChild(curSrcElem,dvHdr) && !isChild(curSrcElem,dvBdy) && (boxMove)) { if ((!isChild(curBoxElem,curSrcElem)) || (curSrcElem.tagName!='TABLE')) { curBoxElem=null; oDv.style.visibility='hidden'; /*showSelects();*/}
}
lastSrcElem=curSrcElem;}
else if (((isChild(curSrcElem,dvHdr) || isChild(curSrcElem,dvBdy))&&(boxMove))) { totalScrollLeft=0; totalScrollTop=0; iterElem=curSrcElem; while(iterElem) { if(!isNaN(parseInt(iterElem.scrollTop)))
totalScrollTop+=parseInt(iterElem.scrollTop); if(!isNaN(parseInt(iterElem.scrollLeft)))
totalScrollLeft+=parseInt(iterElem.scrollLeft); iterElem=iterElem.parentNode;}
boxLeft=Left(curBoxElem)-totalScrollLeft; boxRight=parseInt(Left(curBoxElem)+curBoxElem.offsetWidth)-totalScrollLeft; boxTop=Top(curBoxElem)-totalScrollTop; boxBottom=parseInt(Top(curBoxElem)+curBoxElem.offsetHeight)-totalScrollTop; doCheck();}
if (boxMove&&curBoxElem) { bodyScrollTop=document.documentElement&&document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop; bodyScrollLet=document.documentElement&&document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft; mouseX=evt.pageX?evt.pageX-bodyScrollLet:evt.clientX-document.body.clientLeft; mouseY=evt.pageY?evt.pageY-bodyScrollTop:evt.clientY-document.body.clientTop; if ((curBoxElem)&&(curBoxElem.windowLock)) { mouseY < -oy?lockY=-mouseY-oy:lockY=0; mouseX < -ox?lockX=-mouseX-ox:lockX=0; mouseY > (SHW()[1]-oDv.offsetHeight-oy)?lockY=-mouseY+SHW()[1]-oDv.offsetHeight-oy:lockY=lockY; mouseX > (SHW()[0]-dvBdy.offsetWidth-ox)?lockX=-mouseX-ox+SHW()[0]-dvBdy.offsetWidth:lockX=lockX;}
oDv.style.left=((fixposx)||(fixposx==0))?fixposx:bodyScrollLet+mouseX+ox+lockX+"px"; oDv.style.top=((fixposy)||(fixposy==0))?fixposy:bodyScrollTop+mouseY+oy+lockY+"px";}
}
function doCheck() { if ( (mouseX < boxLeft) || (mouseX >boxRight) || (mouseY < boxTop) || (mouseY > boxBottom)) { oDv.style.visibility='hidden'; if (curBoxElem.IEbugfix) {/*showSelects();*/}
curBoxElem=null;}
}
function pauseBox(e) { e?evt=e:evt=event; boxMove=false; evt.cancelBubble=true;}
function isChild(s,d) { while(s) { if (s==d)
return true; s=s.parentNode;}
return false;}
var cSrc; function checkMove(e) { e?evt=e:evt=event; cSrc=evt.target?evt.target:evt.srcElement; if ((!boxMove)&&(!isChild(cSrc,oDv))) { oDv.style.visibility='hidden'; if (curBoxElem&&curBoxElem.IEbugfix) {/*showSelects();*/}
boxMove=true; curBoxElem=null;}
}
function showSelects(){ var elements = document.getElementsByTagName("select"); for (i=0;i< elements.length;i++){ elements[i].style.visibility='visible';}
}
function hideSelects(){ var elements = document.getElementsByTagName("select"); for (i=0;i< elements.length;i++){ elements[i].style.visibility='hidden';}
}
 /*=====================================================
 ================= emailValidate.js ======================
 =====================================================*/ 
/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function emailValidate(str) {

		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		if (str.indexOf(at)==-1){
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){

		    return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false;
		 }
 		 return true;					
	}

 /*=====================================================
 ================= list.js ======================
 =====================================================*/ 
 	var gaTaskNames = Array();
	var gcLangID = 'lv';
	var pnCurrentRowID = 0;
	gaTaskNames['lv'] 	= Array();
	
	gaTaskNames['lv']['name'] = Array();
	gaTaskNames['lv']['name']['view'] 		= 'Skatīt';
	gaTaskNames['lv']['name']['edit'] 		= 'Labot';
	gaTaskNames['lv']['name']['drop'] 		= 'Dzēst';
	gaTaskNames['lv']['name']['comment'] 	= 'Komentēt';
	gaTaskNames['lv']['name']['perform'] 	= 'Izpildīt';
	gaTaskNames['lv']['name']['confirm'] 	= 'Vērtēt';
	gaTaskNames['lv']['name']['subtask']	= 'Apakšuzdevums';
	gaTaskNames['lv']['name']['open'] 		= 'Atvērt';
	gaTaskNames['lv']['name']['history'] 	= 'Vēsture';
	gaTaskNames['lv']['name']['changepsw']	= 'Nomainīt paroli';
	gaTaskNames['lv']['name']['unlink'] 	= 'Atvienot';
	gaTaskNames['lv']['name']['add_task'] 	= 'Jauns uzdevums';
	gaTaskNames['lv']['name']['mode_calendar_day'] = 'Dienas skats';
	gaTaskNames['lv']['name']['mode_calendar_week'] = 'Nedēļas skats';

	
	gaTaskNames['lv']['name']['task_edit'] 		= 'Labot uzdevuma datus';
	gaTaskNames['lv']['name']['task_drop'] 		= 'Dzēst uzdevuma ierakstu';
	gaTaskNames['lv']['name']['task_saveClose']	= 'Saglabāt izmaiņas un aizvērt logu';
	gaTaskNames['lv']['name']['task_comment'] 		= 'Komentēt';
	gaTaskNames['lv']['name']['task_perform'] 		= 'Reģistrēt izpildi';
	gaTaskNames['lv']['name']['task_confirm'] 		= 'Vērtēt izpildi';
	gaTaskNames['lv']['name']['task_subtask']		= 'Izveidot apakšuzdevumu';

	
	gaTaskNames['lv']['name']['client_drop'] 		= 'Dzēst klienta ierakstu';
	gaTaskNames['lv']['name']['client_edit'] 		= 'Labot klienta datus';
	gaTaskNames['lv']['name']['client_saveClose'] 	= 'Saglabāt izmaiņas un aizvērt logu';
	

	gaTaskNames['lv']['name']['document_drop'] 			= 'Dzēst dokumenta ierakstu';
	gaTaskNames['lv']['name']['document_edit'] 			= 'Labot dokumenta datus';
	gaTaskNames['lv']['name']['document_saveClose'] 		= 'Saglabāt izmaiņas un aizvērt logu';
	gaTaskNames['lv']['name']['document_open'] 			= 'Atvērt dokumentu';
	gaTaskNames['lv']['name']['document_add_to_client']	= 'Pievienot dokumentu klientam';
	gaTaskNames['lv']['name']['document_add_to_task']		= 'Pievienot dokumentu darbam';

	gaTaskNames['lv']['name']['theme_drop'] 		= 'Dzēst tēmas ierakstu';
	gaTaskNames['lv']['name']['theme_edit'] 		= 'Labot tēmas datus';
	gaTaskNames['lv']['name']['theme_saveClose'] 	= 'Saglabāt izmaiņas un aizvērt logu';

	gaTaskNames['lv']['name']['infoCenter_drop'] 		= 'Dzēst infocentra ierakstu';
	gaTaskNames['lv']['name']['infoCenter_edit'] 		= 'Labot datus';
	gaTaskNames['lv']['name']['infoCenter_saveClose'] 	= 'Saglabāt izmaiņas un aizvērt logu';

	gaTaskNames['lv']['name']['helpUser_drop'] 		= 'Dzēst infocentra ierakstu';
	gaTaskNames['lv']['name']['helpUser_edit'] 		= 'Labot datus';
	gaTaskNames['lv']['name']['helpUser_saveClose'] 	= 'Saglabāt izmaiņas un aizvērt logu';
	
	gaTaskNames['lv']['name']['user_drop'] 		= 'Dzēst darbinieka ierakstu';
	gaTaskNames['lv']['name']['user_edit'] 		= 'Labot darbinieka datus';
	gaTaskNames['lv']['name']['user_changepsw'] 	= 'Nomainīt paroli';
	gaTaskNames['lv']['name']['user_saveClose'] 	= 'Saglabāt izmaiņas un aizvērt logu';

	gaTaskNames['lv']['image'] = Array();
	gaTaskNames['lv']['image']['view'] 		= 'hidd.gif';
	gaTaskNames['lv']['image']['edit'] 		= 'edit.gif';
	gaTaskNames['lv']['image']['drop'] 		= 'del.gif';
	gaTaskNames['lv']['image']['open'] 		= 'open.png';
	gaTaskNames['lv']['image']['comment'] 		= 'hidd.gif';
	gaTaskNames['lv']['image']['perform'] 		= 'hidd.gif';
	gaTaskNames['lv']['image']['confirm'] 		= 'hidd.gif';
	gaTaskNames['lv']['image']['subtask'] 		= 'subtask.gif';
	gaTaskNames['lv']['image']['history'] 		= 'hidd.gif';
	gaTaskNames['lv']['image']['changepsw']	= 'hidd.gif';
	gaTaskNames['lv']['image']['unlink']		= 'hidd.gif';

	gaTaskNames['lv']['image']['task_edit'] 		= 'edit.gif';
	gaTaskNames['lv']['image']['task_drop'] 		= 'del.gif';
	gaTaskNames['lv']['image']['task_saveClose'] 	= 'hidd.gif';
	gaTaskNames['lv']['image']['task_comment']		= 'hidd.gif';
	gaTaskNames['lv']['image']['task_perform']		= 'hidd.gif';
	gaTaskNames['lv']['image']['task_confirm']		= 'hidd.gif';
	gaTaskNames['lv']['image']['task_subtask']		= 'hidd.gif';
	
	gaTaskNames['lv']['image']['client_drop'] 		= 'del.gif';
	gaTaskNames['lv']['image']['client_edit'] 		= 'edit.gif';
	gaTaskNames['lv']['image']['client_saveClose']	= 'hidd.gif';

	gaTaskNames['lv']['image']['document_drop'] 			= 'del.gif';
	gaTaskNames['lv']['image']['document_edit'] 			= 'edit.gif';
	gaTaskNames['lv']['image']['document_saveClose']		= 'hidd.gif';
	gaTaskNames['lv']['image']['document_open']			= 'open.png';
	gaTaskNames['lv']['image']['document_add_to_client']	= 'hidd.gif';
	gaTaskNames['lv']['image']['document_add_to_task']		= 'hidd.gif';

	gaTaskNames['lv']['image']['theme_drop'] 		= 'del.gif';
	gaTaskNames['lv']['image']['theme_edit'] 		= 'edit.gif';
	gaTaskNames['lv']['image']['theme_saveClose']	= 'hidd.gif';
	
	gaTaskNames['lv']['image']['infoCenter_drop'] 		= 'del.gif';
	gaTaskNames['lv']['image']['infoCenter_edit'] 		= 'edit.gif';
	gaTaskNames['lv']['image']['infoCenter_saveClose']	= 'hidd.gif';

	gaTaskNames['lv']['image']['helpUser_drop'] 		= 'del.gif';
	gaTaskNames['lv']['image']['helpUser_edit'] 		= 'edit.gif';
	gaTaskNames['lv']['image']['helpUser_saveClose']	= 'hidd.gif';
	
	gaTaskNames['lv']['image']['user_drop'] 		= 'del.gif';
	gaTaskNames['lv']['image']['user_edit'] 		= 'edit.gif';
	
	gaTaskNames['lv']['image']['user_saveClose'] 	= 'hidd.gif';
	
	gaTaskNames['lv']['image']['add_task'] 		= 'hidd.gif';
	gaTaskNames['lv']['image']['mode_calendar_day']= 'hidd.gif';
	gaTaskNames['lv']['image']['mode_calendar_week']= 'hidd.gif';

	function OpenPopupMenu(tnID, tcMenuID)
	{
		var lcNames		= '';
		var lcActions	= '';
		var lcImages	= '';
		var lcEnables	= '';
		var laTasks, laRights;
		
		if(tcMenuID)
		{
			laTasks = paAllTasks[tcMenuID];
			laRights = typeof(paRights[tcMenuID]) != 'undefined' ? paRights[tcMenuID] : null;
		}
		else
		{
			laTasks = paAllTasks;
			laRights = paRights;
		}
		
		for(var i = 0; i < laTasks.length; i++)
		{
			lcTask = laTasks[i];
			
			lcNames 	+= '!' 	+ gaTaskNames[gcLangID]['name'][laTasks[i]];
			lcImages 	+= '!'	+ gaTaskNames[gcLangID]['image'][laTasks[i]];
			if(glIs_MSIE)
				lcActions 	+= '!'	+ "parent.window.Manage('"+tnID+"', '"+lcTask+"');";
			else
				lcActions 	+= '!'	+ "Manage('"+tnID+"', '"+lcTask+"');";
			
			if(laRights != null)
				lcEnables 	+= '!'	+ (laRights[tnID].indexOf(lcTask) != -1 ? 'E' : 'D');
			else
				lcEnables	+= '!E';
		}
		
		ListPopupMenu_Open(lcNames, lcImages, lcActions, lcEnables, 'TR_'+tnID);
		return false;
	}

	function OpenFormPopupMenu()
	{
		
		var lcNames		= '';
		var lcActions	= '';
		var lcImages	= '';
		var lcEnables	= '';
		
		for(var i = 0; i < paAllTasks.length; i++)
		{
				
			var lcTask = paAllTasks[i];
			lcNames 	+= '!' 	+ gaTaskNames[gcLangID]['name'][lcTask];
			lcImages 	+= '!'	+ gaTaskNames[gcLangID]['image'][lcTask];
			
			if(glIs_MSIE)
				lcActions 	+= '!'	+ "parent.window.Manage('"+lcTask+"');";
			else
				lcActions 	+= '!'	+ "Manage('"+lcTask+"');";
				
			if(typeof(paRights) != 'undefined')
				lcEnables 	+= '!'	+ (paRights.indexOf(lcTask) != -1 ? 'E' : 'D');
			else
				lcEnables += '!E';
		}
		ListPopupMenu_Open(lcNames, lcImages, lcActions, lcEnables, 'popup_functions');
		
		return false;
	}
	
	function onRowClick(tnID, tcTask)
	{
		if(!tcTask)
			tcTask = 'edit';
			
		Manage(tnID, tcTask);
		
		/*
		if(GetMouseButton() == 2)
		{
			OpenPopupMenu(tnID);
		}
		else
		{
			Manage(tnID, 'edit');
		}
		*/
		return false;
	}

	function GetCurrentRowID()
	{
		return GetCookie('ListCurrentRowID_'+pcListName);
	}
	
	var gaTableList = Array();
	
	function List_Init()
	{
		var loTable = GetElem('TABLE_List');
		var loRow, lcID;
		if(loTable == null)
			return null;
			
		for(var i = 0; i < loTable.rows.length; i++)
		{
			loRow = loTable.rows[i];
			lcID = loRow.id.substr(3);
			if(lcID.indexOf('_d') != -1)
			{
				lcID = lcID.substr(0, lcID.length-2);
				gaTableList[lcID]['haveText'] = true;
				gaTableList[lcID]['textRow'] = loRow;
			}
			else
			{
				gaTableList[lcID] = Array();
				gaTableList[lcID]['id'] = lcID;
				gaTableList[lcID]['no'] = i;
				gaTableList[lcID]['haveText'] = false;
				gaTableList[lcID]['mainRow'] = loRow;
				gaTableList[lcID]['textRow'] = null;
				gaTableList[lcID]['hidden'] = false;
				gaTableList[lcID]['showNo'] = i;
				gaTableList[lcID]['highLight'] = (i % 2) == 0 && glHighLighList;
			}
		}
		List_Refresh();
		return true;
	}
	function List_Refresh()
	{
		var lnID, i = 0, lnPrevRowID = null;
		for(lnID in gaTableList)
		{
			if(gaTableList[lnID]['mainRow'].style.visibility == 'hidden')
			{
				gaTableList[lnID]['hidden'] = true;
				continue;
			}
			gaTableList[lnID]['hidden'] = false;
			gaTableList[lnID]['showNo']		= i;
			gaTableList[lnID]['highLight']	= (i % 2) == 0  && glHighLighList;
			gaTableList[lnID]['prevRowID'] = lnPrevRowID;
			lnPrevRowID = lnID;
			i++;
		}
	}
	
	
	function List_Refresh_HighLight()
	{
		var laRow, lnID, lcBGColor;
		List_Refresh();
		for(lnID in gaTableList)
		{
			laRow = gaTableList[lnID];
			if(!laRow['hidden'])
			{
				lcBGColor = laRow['highLight'] ? 
					gaColors['ListRow']['BackGround']['highlight'] : 
					gaColors['ListRow']['BackGround']['normal'];
				SetRowCellBackGround(lnID, lcBGColor);
			}
		}
	}
	function List_GetRow(tnID)
	{
		if(typeof(gaTableList[tnID]) == 'undefined')
			return 0;
		return gaTableList[tnID];
	}
	// Noskaidro iepriekjs rindas ID
	function GetPrevRowID(tnID)
	{
		var loTable = GetElem('TABLE_List');
		var lnPrevRowID = 0;
		if(loTable == null)
			return null;
		for(var i = 0; i < loTable.rows.length; i++)
		{
			var loRow = loTable.rows[i];
			if(loRow.id == 'TR_'+tnID && loRow.style.visibility != 'hidden')
				return lnPrevRowID;
			lnPrevRowID = loRow.id.substr(3);
			if(lnPrevRowID.indexOf('_d') != -1)
				lnPrevRowID = lnPrevRowID.substr(0, lnPrevRowID.length - 2);
		}
		return 0;
	}
	
	function SetDefaultRow(tnDefaultRowID)
	{
		SetCurrentRow(tnDefaultRowID == '' ? GetCurrentRowID() : tnDefaultRowID);
	}
	function SetCurrentRow(tnID)
	{
		UnSetCurrentRow();
		pnCurrentRowID = tnID;
		if(tnID != 0)
		{
			SetRowCellBackGround(tnID, gaColors['ListRow']['BackGround']['current']);
			SaveCurrentRowID(tnID, pcListName)
		}
	}
	
	
	function SaveCurrentRowID(tnID, tcListName)
	{
		SetCookie('ListCurrentRowID_'+tcListName, tnID);
	}
	function UnSetCurrentRow()
	{
		var laRow = List_GetRow(pnCurrentRowID);
		if(!laRow)
			return false;
		var lcBGColor = laRow['highLight'] ? 
			gaColors['ListRow']['BackGround']['highlight'] : 
			gaColors['ListRow']['BackGround']['normal'];
		
		SetRowCellBackGround(pnCurrentRowID, lcBGColor);	
	}
	function UnSelectRow(tnID)
	{
		var laRow = List_GetRow(tnID), lcBGColor;
		if(!laRow)	return false;
			
		SetRowCellBorderStyle(tnID, '1px solid #ffcc00');
		if(pnCurrentRowID == tnID)
		{
			lcBGColor = gaColors['ListRow']['BackGround']['current'];
		}
		else 
		{
			lcBGColor = laRow['highLight'] ? 
				gaColors['ListRow']['BackGround']['highlight'] : 
				gaColors['ListRow']['BackGround']['normal'];
		}
		SetRowCellBackGround(tnID, lcBGColor);
	}
	function SelectRow(tnID)
	{
		SetRowCellBorderStyle(tnID, '1px solid #000000');
		SetRowCellBackGround(tnID, gaColors['ListRow']['BackGround']['selected']);
	}

	function SetRowCellBackGround(tnID, tcBGColor)
	{
		var laRow = List_GetRow(tnID);
		if(!laRow)	return false;
	
		laRow['mainRow'].style.backgroundColor = tcBGColor;
		if(laRow['haveText'])
			laRow['textRow'].style.backgroundColor = tcBGColor;
	}
	
	function SetRowCellBorderStyle(tnID, tcStyle)
	{
		var laRow = List_GetRow(tnID);
		var lnPrevID = laRow['prevRowID'];
		SetRowCellBorderStyle_One(lnPrevID	, tcStyle);
		SetRowCellBorderStyle_One(tnID		, tcStyle);
	}
	
	function SetRowCellBorderStyle_One(tnID, tcStyle)
	{
		
		var laRow = List_GetRow(tnID);
		
		if(!laRow)	return false;
		var loCell;
			
		var loRow 		= laRow['mainRow'];
		var loRowText 	= laRow['textRow'];
		var llHaveText 	= laRow['haveText'];
		
		for(i = 0; i < loRow.cells.length; i++)
		{
			loCell = loRow.cells[i];
			if(!llHaveText || loCell.rowSpan > 1)
			{
				loCell.style.borderBottom = tcStyle;
			}
		}
		if(loRowText)
		{
			for(i = 0; i < loRowText.cells.length; i++)
			{
				loCell = loRowText.cells[i];
				loCell.style.borderBottom = tcStyle;
			}
		}
	}

	function List_SetParam(tcParams, tcCat, tcWindow)
	{
		document.location.href = '/list.php?'
			+ 'cat=' 		+ document.main.cat.value
			+ '&window=' 	+ document.main.window.value
			+ (tcCat ? '&cat=' + tcCat : '')
			+ (tcWindow ? '&window=' + tcWindow : '')
			+ '&' + tcParams;
	}
	
var goMenuPopup;
/* Atver uzleco?o menu
	tcNames		- Menu vien?bu nosaukumi atdal?ti izsaukumu z?mi
	tcImages		- Menu vien?bu ikonu failu nosaukumi atdal?ti izsaukumu z?mi
	tcActions	- Veicam?s darb?bas ja izv?l?ts kads no punktiem
	
	PIEM?RS:
 	TreePopupMenu
		(
		"Viens!Divi", 
		"one.gif!two.gif", 
		"alert('odin')!alert('dva')"
		);
*/
function ListPopupMenu_Open(tcNames, tcImages, tcActions, tcEnables, tcTargetID)
{
	//if( !goMenuPopup ) goMenuPopup = window.createPopup(  );
	 
	var laNames		= tcNames.split("!");
	var laImages	= tcImages.split("!");
	var laActions	= tcActions.split("!");
	var laEnables 	= tcEnables ? tcEnables.split("!") : null;
	var llEnable	= false;
	var lnHeight = 0;
	var lcContent = 
		'<div style="cursor: default; font-size: 11px; font-family: verdana">'+
		'<table cellspacing=0 cellpadding=0 border="1" style="color : MenuText; font-size: 11px; font-family: verdana">';
	for(var i = 0; i < laNames.length; i++)
	{
		
		if(laNames[i].length == 0)
			continue;
		
		llEnable = laEnables ? laEnables[i] == 'E': true;
		lcContent = lcContent +
			ListPopupMenu_ItemBody(laNames[i]	, laImages[i], laActions[i], llEnable);
		lnHeight += 23;
		
	}

    lcContent += '</table>';
	goPopupWindow.Open(lcContent, tcTargetID);
}
// ================================================ ITEM Body
// ?ener? HTML kodu vienai menu izv?lei
function ListPopupMenu_ItemBody(tcName, tcImage, tcOnClick, tlEnable)
{
	var lcMouseOver = lcMouseOut = lcMouseOnClick = '';
	if(tlEnable)
	{
		var lcStyle = ' style="cursor: pointer; background-color: Menu;  border-top: 1px solid #FFFFFF;  border-left: 1px solid #FFFFFF; border-right: 1px solid #808080;  border-bottom: 1px solid #808080; padding-right: 10px" ';
		if(glIs_MSIE)
		{
			var lcMouseOver		= ' onmouseover="parent.window.ListPopupMenu_Over( this )" ';
			var lcMouseOut 		= ' onmouseout="parent.window.ListPopupMenu_Over( this, 1)" ';
		}
		else
		{
			var lcMouseOver		= ' onmouseover="ListPopupMenu_Over( this )" ';
			var lcMouseOut 		= ' onmouseout="ListPopupMenu_Over( this, 1)" ';
		}
		var lcMouseOnClick 	= ' onclick="'+tcOnClick+'"';
	}
	else
	{
		var lcStyle = ' style="cursor: default; background-color: Menu;  border-top: 1px solid #FFFFFF;  border-left: 1px solid #FFFFFF;    border-right: 1px solid #808080;  border-bottom: 1px solid #808080; color: GrayText; padding-right: 10px"; ';	
	}
	var lcOut = '<tr>\n'
		+ '<td ' + lcStyle + lcMouseOver + lcMouseOut + lcMouseOnClick + ' nowrap height="20">\n'
		+ '<img src="/images/functions/'+tcImage+'" align="absmiddle" alt="" border=0 width=20 height=20>\n'
		+ ' '+tcName
		+ '</td>\n'
		+ '</tr>\n';
	
	return lcOut;
}


function ListPopupMenu_Over( obj, id )
{
	if( typeof obj != 'object' ) 
		return ;
	if( !id  )
	{
		obj.style.backgroundColor	= "HighLight";
		obj.style.color 			= "HighLightText";
		return ;
	}
	obj.style.backgroundColor	= "Menu";
	obj.style.color 			= "MenuText";
}

//############################################

function remfr( )
{
	if( window.location.search.indexOf( 'nf=true' ) != -1 )
	{
		var el = document.getElementById( 'div1' );
		if( el )
		{
			el.style.display = 'none';
			el.style.visibility = 'hidden';
			return;
		}
	}
}
	if
	( 
		navigator.userAgent.indexOf( "MSIE" ) != -1 ||  
		navigator.userAgent.indexOf( "Opera" ) != -1 
	) 
	window.attachEvent( 'onload' ,remfr );

	
 /*=====================================================
 ================= datePopup.js ======================
 =====================================================*/ 
	var gaWeekDayNames = Array();
		gaWeekDayNames['lv'] = Array('P', 'O', 'T', 'C', 'P', 'S', 'Sv');
	
	var gaMonthNames = Array();
		gaMonthNames['lv'] = Array('Janv&#257;ris', 'Febru&#257;ris', 'Marts', 'Apr&#299;lis', 'Maijs', 'J&#363;nijs', 'J&#363;lijs', 'Augusts', 'Septembris', 'Oktobris', 'Novembris', 'Decembris');
	
	var gaLabels	= Array();
		gaLabels['lv'] = Array();
			gaLabels['lv']['emptyDate'] = 'Nav datuma';
			
	var gcLanguage = '';
	var goDateCur = null;
	var goDateToday = new Date();
	var goInput = null;

	var gcCustomFreeDates = ',1:0,11:10,18:10,';

	/* =========================================================================== OPEN 
		Atver kalendru
	*/
	function GetDate(toInput)
	{
		goInput = toInput;
		gcLanguage = gcLangID;
		
		if(goInput.value)
		{
			
			var lcValue = goInput.value.substr(0,10);
			var laDateParts = lcValue.split('.');
			goDateCur = new Date(laDateParts[2], laDateParts[1]-1, laDateParts[0]);
			Calendar_SetDate(goDateCur.getMonth(), goDateCur.getFullYear());
			
		}
		else
		{

			var loDate = new Date();
			Calendar_SetDate(loDate.getMonth(), loDate.getFullYear());
		}
	}
	/* ============================================================== MONTH DAY COUNT
		Noskaidro cik dienu ir mnes
		tnMonth	- Mnea numurs. Janvris - 0; Decembris - 11
		tnYear	- Pilnais gada numurs
	*/
	function MonthDayCount(tnMonth, tnYear) 
	{
		var laDayCount = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
		// Garaj gad februr ir 29 dienas
		if((tnYear % 4) == 0)
			laDayCount[1] = 29;
		return laDayCount[tnMonth];
	}

	/* ============================================================== MONTH ROW COUNT
		Noskaidro cik nedas rindu bs nepiecieams lai attlotu mnesi
		tnMonth	- Mnea numurs. Janvris - 0; Decembris - 11
		tnYear	- Pilnais gada numurs
	*/
	function MonthRowCount(tnMonth, tnYear)
	{
		var lnDayCount 			= MonthDayCount(tnMonth, tnYear);						// Cik dienu menesii
		var loDate 				= new Date(tnYear, tnMonth, 1);
		var lnFirstDayOfWeek	= loDate.getDay();										// Pirm datuma nedls diena
		var lnOffset 			= lnFirstDayOfWeek == 0 ? 6 : lnFirstDayOfWeek - 1;	// Nobde no skuma. Ja pirmdiena tad 0
		var lnCellCount 		= lnDayCount + lnOffset;								// Cik lauciu kop lai attlotu visas dienas
		return Math.ceil(lnCellCount / 7);												// Cik pilnu rindu vajadzs
	}
	function IsDayFree(tnDay, tnMonth, tnYear)
	{
		var loDate 		= new Date(tnYear, tnMonth, tnDay);
		var lnDayOfWeek	= loDate.getDay();
		if(lnDayOfWeek == 0 || lnDayOfWeek == 6)
			return true;
		if(gcCustomFreeDates.indexOf(","+tnDay+":"+tnMonth+",") != -1)
			return true;
		return false;
	}
	function Calendar_CellMouseEvent(tnDay, tcEvent)
	{
		
		var loCell = GetElem("TD_"+tnDay);
		
		if(tcEvent == 'enter')
			loCell.style.background = '#EEEEEE';
		else
			loCell.style.background = '#FFFFFF';
	}
	function HTMLOfDay(tnDay, tnMonth, tnYear)
	{
		
		if(tnDay < 1 || tnDay > MonthDayCount(tnMonth, tnYear))
		{
			return "";
		}
		
		var llIsFree = IsDayFree(tnDay, tnMonth, tnYear);
		var llIsCurrent = false;
		var llIsToday = 
				goDateToday.getDate()		== tnDay 	&&
				goDateToday.getMonth()		== tnMonth	&&
				goDateToday.getFullYear()	== tnYear;
		
		
		if(goDateCur != null)
		{
			llIsCurrent = 
				goDateCur.getDate()		== tnDay 	&&
				goDateCur.getMonth()	== tnMonth	&&
				goDateCur.getFullYear()	== tnYear;
		}
		
		var lcTDClass	= llIsCurrent	? 'calCurCell'	: 'calNormCell';
		var lcDateClass	= llIsFree		? 'calFreeDate'	: 'calNormDate';
		var lcEvents = '';
		var lcPrefix = gaSupported['CreatePopup'] ? 'parent.window.' : '';
		if(!llIsCurrent)
		{
			lcEvents = 
				"onMouseOver='Calendar_CellMouseEvent("+tnDay+", \"enter\")' " + 
				"onMouseOut='Calendar_CellMouseEvent("+tnDay+", \"out\")' ";
			
		}
		var lcTemplate = 
			"<TD width=25 #Events# id='#ID#' class='#TDClass#' onClick='"+lcPrefix+"Calendar_SelectDay(#Day#, #Month# ,#Year#)'>" + 
			"<SPAN class='#DateClass#'>#Date#</span>" +
			"</td>\r\n";
		
		var lcDate = llIsToday ? '<B>'+tnDay+'</b>' : tnDay;
		
		lcTemplate = lcTemplate.replace('#TDClass#'		, lcTDClass);
		lcTemplate = lcTemplate.replace('#DateClass#'	, lcDateClass);
		lcTemplate = lcTemplate.replace('#Day#'			, tnDay);
		lcTemplate = lcTemplate.replace('#Date#'		, lcDate);
		lcTemplate = lcTemplate.replace('#Month#'		, tnMonth);
		lcTemplate = lcTemplate.replace('#Year#'		, tnYear);
		lcTemplate = lcTemplate.replace('#ID#'			, "TD_"+tnDay);
		lcTemplate = lcTemplate.replace('#Events#'		, lcEvents);
		return lcTemplate;
			
	}

	function Calendar_SelectDay(tnDay, tnMonth ,tnYear)
	{
		var lcDate = '';
		if(tnDay != 0)
		{
			lcDate = 
				addZero(tnDay) 		+ '.' +
				addZero(tnMonth+1)	+ '.' +
				tnYear;
		}
		goInput.value = lcDate
		if(goInput.onchange)
			goInput.onchange();
		Calendar_Close();
	}

	function Calendar_SetDate(tnMonth, tnYear)
	{
		 
		var lcContent = HTMLOfMonth(tnMonth, tnYear);
		Calendar_WriteContent(lcContent, goInput.id);
		
	}
	
	function Calendar_WriteContent(tcContent)
	{
		goPopupWindow.cAlign = 'Object';
		goPopupWindow.cStyleLink = '/css/datePopup.css';
		goPopupWindow.Open(tcContent, goInput.id);
	}
	
	function HTMLOfMonth(tnMonth, tnYear)
	{
	
		var lcHTML = '';
		
		var lnRowCount 			= MonthRowCount(tnMonth, tnYear);
		var lnDayCount 			= MonthDayCount(tnMonth, tnYear);
		var loDate 				= new Date(tnYear, tnMonth, 1);
		var lnFirstDayOfWeek	= loDate.getDay();										// Pirm datuma nedls diena
		var lnOffset 			= lnFirstDayOfWeek == 0 ? 6 : lnFirstDayOfWeek - 1;	// Nobde no skuma. Ja pirmdiena tad 0		
		
		var lnDate = 0;
		var lnDay;
		
		
		// Mneu skrollings -----------------------
		var lnMonth, lnYear;
		var lcPrefix = gaSupported['CreatePopup'] ? 'parent.' : '';
		lcHTML += '<TR>';
		
		lnMonth = tnMonth == 0 ? 11 : tnMonth - 1;
		lnYear 	= tnMonth == 0 ? tnYear - 1: tnYear;
		lcHTML += "<TD class='calMonthScrollButton' onClick='"+lcPrefix+"Calendar_SetDate("+lnMonth+", "+lnYear+")'><IMG src='/images/calendar/left.gif'></td>\r\n";
		
		lcHTML += "<TD colspan=5 class='calMonthScroll'>" 
			+ gaMonthNames[gcLanguage][tnMonth] 
			+ " " + tnYear + "</td>\r\n";

		lnMonth = tnMonth == 11 ? 0 : tnMonth + 1 ;
		lnYear 	= tnMonth == 11 ? tnYear + 1: tnYear;
		lcHTML += "<TD class='calMonthScrollButton' onClick='"+lcPrefix+"Calendar_SetDate("+lnMonth+", "+lnYear+")'><IMG src='/images/calendar/right.gif'></td>\r\n";
			
		lcHTML += '</tr>';

		// Dienu nosaukumi ------------------------
		lcHTML += '<TR>';
		for(lnDay = 0; lnDay < 7; lnDay++)
		{
			var lcWeekClass = lnDay < 5 ? 'calWeekNorm' : 'calWeekFree';
			lcHTML += "<TD class='"+lcWeekClass+"'>"+gaWeekDayNames[gcLanguage][lnDay]+"</td>";
		}
		lcHTML += '</tr>\r\n';
		
		// Dienas ---------------------------------
		for(var lnRow = 0; lnRow < lnRowCount; lnRow++)
		{
			lcHTML += '<TR>';
			if(lnRow == 0 && lnOffset)
				lcHTML += "<TD class='calEmptyCell' colspan="+lnOffset+">&nbsp;</td>";
				
			for(lnDay = 0; lnDay < 7; lnDay++)
			{
				if(lnDate == 0)
				{
					if(lnDay == lnOffset) lnDate = 1;
				}
				else
				{
					lnDate++;
				}
				lcHTML += HTMLOfDay(lnDate, tnMonth, tnYear);
			}
			if(lnRow  == lnRowCount - 1)
			{
				lnOffestEnd = lnRowCount * 7 - (lnDayCount + lnOffset);
				if(lnOffestEnd > 0)
					lcHTML += "<TD class='calEmptyCell' colspan="+lnOffestEnd+">&nbsp;</td>";
			}
			lcHTML += '</tr>';
		}
		lcHTML += "<TR><TD onClick='"+lcPrefix+"Calendar_SelectDay(0,0,0)' colspan=7 class='calEmptyDate'>"+ gaLabels[gcLanguage]['emptyDate']+"</td></tr>";
		lcHTML = '<TABLE id="popup_TABLE" width=175 class="cal" border=0 cellpadding=1 cellspacing=1>' + lcHTML + '</table>';
		return lcHTML;
	}
	
	function Calendar_Close()
	{
		goPopupWindow.Close();
	}

 /*=====================================================
 ================= utility.js ======================
 =====================================================*/ 

var gaFormElementCache = Array();
var gaFormElementCacheList = '';
var goObj = null;

function GetElem(tcID, tcContainerID)
{
	var loCont = typeof(tcContainerID) == 'undefined' ? document : GetElem(tcContainerID);
		
	// it vispr nevar bt. Bet gads kad IE kautk 'greizi' iekeo javaskriptus
	if(typeof(gaFormElementCacheList) == 'undefined')
		return loCont.getElementById(tcID);
		
	if(gaFormElementCacheList.indexOf('^'+tcID+'^') != -1)
	{
		return gaFormElementCache[tcID];
	}
	gaFormElementCache[tcID] = loCont.getElementById(tcID);
		//document.all ? document.all[tcID] : document.getElementById(tcID);
	gaFormElementCacheList += '^'+tcID+'^';
	
	return gaFormElementCache[tcID];
}
function GetWidth(toObj) 
{
	return (document.layers) ? toObj.clip.width : toObj.offsetWidth;
}
function GetHeight(toObj) 
{
	return (document.layers) ? toObj.clip.height : toObj.offsetHeight;
}
function GetLeft(toObj) 
{
	var laPos = findPos(toObj);
	return laPos['left'];
}
function GetTop(toObj) 
{
	var laPos = findPos(toObj);
	return laPos['top'];
}

function findPos(toObj) 
{
	var lnCurLeft = lnCurTop = 0;
	if (toObj.offsetParent) 
	{
		lnCurLeft = toObj.offsetLeft;
		lnCurTop = toObj.offsetTop;
		while (toObj = toObj.offsetParent) 
		{
			lnCurLeft += toObj.offsetLeft;
			lnCurTop += toObj.offsetTop;
		}
	}
	
	var laPos = Array();
	laPos['left']	= lnCurLeft;
	laPos['top']	= lnCurTop;
	
	return laPos;
}	

function addZero(tnValue)
{
	var lcValue = '' + tnValue;
	if(lcValue.length != 2)
		return '0' + tnValue;
	return tnValue;
}
function GetMouseX()
{
	return document.body.scrollLeft + event.clientX;
}
function GetMouseY()
{
	return document.body.scrollTop + event.clientY;
}
function Error(tcMessage)
{
	alert('Manual script error [ '+tcMessage+' ]');
	return false;
}
function GetMouseButton(toEvent)
{
	switch(gcBrowser)
	{
		case 'MSIE':
			if(event.button != null)
				return event.button;
			return event.witch;
		case 'FireFox':
			return alert(toEvent);
			
	}
	
	return Error('Unsuported browser:'+gcBrowser);
}
function OpenHint(tcText)
{
	loHint = GetElem('hint');
	loHint.innerHTML = tcText;
	loHint.style.visibility = 'visible';
	loHint.style.left = GetMouseX() + 'px';
	loHint.style.top = (GetMouseY() + 20) + 'px';
}
function CloseHint()
{
	loHint = GetElem('hint');
	loHint.style.visibility = 'hidden';
}

// Aktiviz Kabatu
var pcCurrentTabStyle = '';

function OpenTab(tcTabID)
{
	
	// Braucam cauri vism defintajm Kabatm
	for(var i = 0; i < pcTabList.length; i++)
	{
		var lcTabID  	= pcTabList[i];
		var loTabLink 	= GetElem('TabLink_'+lcTabID);
		var loTab;
		var laTabStyles = Array('', '_view', '_edit');
		for(var t = 0; t < 3; t++)
		{
			var lcTabID_ByStyle = lcTabID + laTabStyles[t];
	 		loTab = GetElem(lcTabID_ByStyle);
			
			if(loTab != null)
			{
				if(lcTabID == tcTabID)
				{
					if(laTabStyles[t].length == 0 || laTabStyles[t] == '_'+pcCurrentTabStyle)
					{
						Form_FocusTab_Set(lcTabID);
						SetTabStatus(loTab, loTabLink, 'show');
					}
					else
					{
						SetTabStatus(loTab, null, 'hide');
					}
				}
				else
				{
					SetTabStatus(loTab, loTabLink, 'hide');
				}
				continue;
			}
		}
	}
}

function SetTabStatus(toTab, toTabLink, tcStatus)
{
	if(tcStatus == 'show')
	{
		var loTabRow = GetElem('TabRow');
		toTab.style.top = (GetTop(loTabRow) + GetHeight(loTabRow) + 5) + 'px';
		toTab.style.visibility = 'visible';
		if(toTabLink.href)
			toTabLink.style.color = '#fcff00';
	}
	else
	{
		toTab.style.visibility = 'hidden';
		if(toTabLink && toTabLink.href)
			toTabLink.style.color = '#FFFFFF';
	}
}

function DateTimeToString(tcName)
{
	var lcValue = 
		GetElem('input_'+tcName+'_date').value + '|' +
		GetElem('input_'+tcName+'_hour').value + '|' +
		GetElem('input_'+tcName+'_min').value;
	return lcValue;
}

function SelectDropdown(tcObjectID, tcValue)
{
	var loObj = document.getElementById(tcObjectID);
	if(!loObj)
		return Error("SelectDropdown(). Object not found: "+tcObjectID);
	for(var i = 0; i < loObj.options.length; i++)
	{
		if(loObj.options[i].value == tcValue)
			loObj.selectedIndex = i;
	}
}

function FormOnLoadClose()
{
	var lcTask = document.main.task.value;
	if(lcTask == 'close')
	{
		opener.location.reload();
		self.close();
		return true;
	}
	return false;
}
 /*=====================================================
 ================= cookie.js ======================
 =====================================================*/ 
var gcLangID = 'lv';
if(GetCookie('Language'))
	gcLangID = GetCookie('Language');
//---------------------------------------------------------------------
// Function to return the value of the cookie specified by "name".

// Parameter:
//     name     String object containing the cookie name.

// Return:      String object containing the cookie value, or null if
//              the cookie does not exist.
//---------------------------------------------------------------------
function GetCookie (name)
{
    var arg  = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i    = 0;

    while (i < clen)
    {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
          return getCookieVal (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}
//---------------------------------------------------------------------
// Function to get a cookie.
//---------------------------------------------------------------------
function getCookieVal( offset )
{
    var endstr = document.cookie.indexOf (";", offset);

    if (endstr == -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}
//---------------------------------------------------------------------
// Function to set a cookie.
//---------------------------------------------------------------------
function SetCookie( name, value, tcExpireCode )
{
    var argv    = SetCookie.arguments;
    var argc    = SetCookie.arguments.length;
    var expires	= null;
    
    switch(tcExpireCode)
    {
    	case 'session'  : expires =null;break;
    	case 'forever' : expires =null;
    		var d = new Date();
    		d.setYear(d.getYear()+1);
    		expires = d.toGMTString();
    	break;
    }

    var path    = '/';
    var domain  = null;
    var secure  = false;

    document.cookie =
        name + "=" + escape (value) +
        ((expires 	== null) ? "" 			: ("; expires=" + expires)) +
        ((path 		== null) ? "" 			: ("; path=" 	+ path)) +
        ((domain 	== null) ? "" 			: ("; domain=" 	+ domain)) +
        ((secure 	== true) ? "; secure" 	: "");
}
//---------------------------------------------------------------------
// Function to delete a cookie. (Sets expiration date)
//    name - String object containing the cookie name
//---------------------------------------------------------------------
function DeleteCookie (name)
{
    var exp  = new Date();
    var cval = GetCookie (name);

    exp.setTime (exp.getTime() - 1);  // This cookie is history
    document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
 /*=====================================================
 ================= realPopus.js ======================
 =====================================================*/ 
//openPopup(tcUrl, tnWidth, tnHeight, tcWindowName, tlScrolled, tnPosX, tnPosY, tnPosOffsetX, tnPosOffsetY)

// Sagalaba loga izmeru pie resaiza
function winSaveSize()
{
	var lcName = window.name;
	var lnWidth = GetWindow_Width();
	var lnHeight = GetWindow_Height();
	SetCookie('WinSize_' + lcName, lnWidth + 'x' + lnHeight, 'forever');
} 

function openPopup_EditText(tnID, tcField, tcTable, tnWidth)
{
	var lcUrl = '/admin/visio/popups/textEdit.php?tran_id='+tnID+'&task=Edit&table='+tcTable+'&field='+tcField+'&width='+tnWidth;
	openPopup(lcUrl, 800, 600);
}
function openPopup_ChapterMoveOut(tcUrl)				
{
	openPopup('/admin/popup/selectChapterParent.php?'+tcUrl, 400, 500, 'ChapterMoveOut', true);
}

function OpenPopup_EditChapter(tcUrl)
{
	openPopup('/admin/popup/editChapter.php?'+tcUrl, 400, 215, 'EditChaptet');
}
function OpenPopup_EditCatalog(tcUrl)
{
	openPopup('/admin/popup/editCatalog.php?'+tcUrl, 500, 205, 'EditCatalog');
}
function OpenPopup_MoveHere(tcUrl, tnObjectCount)
{
	if(typeof(tnObjectCount) != 'undefined')
	{
		if(tnObjectCount > 25)
			tnObjectCount = 25;
	}
	else
	{
		tnObjectCount = 25;
	}

	var lnHeight = (tnObjectCount+1) * 19 + 150;
	openPopup('/admin/popup/listMoveHere.php?'+tcUrl, 400, lnHeight, 'MoveHere', true);
}
function OpenPopup_MoveChapter(tcUrl)
{
	openPopup('/admin/popup/moveChapter.php?'+tcUrl, 400, 500, 'MoveChapter', true);
}
function OpenPopup_EditFile(tcUrl)
{
	openPopup('/admin/popup/editFile.php?'+tcUrl, 400, 220, 'EditChapter');
}
function OpenPopup_EditPriceText(tcUrl)
{
	openPopup('/admin/popup/editPriceText.php?'+tcUrl, 400, 230, 'EditPriceText');
}

function OpenPopup_EditSimpleTextTitle(tcUrl)
{
	openPopup('/admin/popup/editSimpleTextTitle.php?'+tcUrl, 400, 190, 'EditSimpleTextTitle');
}


function OpenPopup_EditTeacherPhoto(tcUrl)
{
	openPopup('/admin/popup/editTeacherPhoto.php?'+tcUrl, 400, 190, 'EditTeacherPhoto');	
}
function OpenPopup_EditBanner(tcUrl)
{
	openPopup('/admin/popup/editBanner.php?'+tcUrl, 400, 265, 'EditBanner');
}
function OpenPopup_EditGalleryPicture(tcUrl)
{
	openPopup('/admin/popup/editGalleryPicture.php?'+tcUrl, 480, 240, 'EditGalleryPicture');
}
function OpenPopup_EditCourse(tcUrl)
{
	openPopup('/admin/popup/editCourse.php?'+tcUrl, 400, 220, 'EditCourse');
}

function OpenPopup_SubscribeCourse(tcUrl)
{
	openPopup('/user/popup/subscribeCourse.php?'+tcUrl, 400, 240, 'SubscribeCourse');
}

function OpenPopup_EditSimpleTextString(tcUrl)
{
	openPopup('/admin/popup/editSimpleTextString.php?'+tcUrl, 400, 190, 'EditSimpleTextString');
}

function OpenPopup_EditSimpleTextArea(tcUrl)
{
	openPopup('/admin/popup/editSimpleTextArea.php?'+tcUrl, 400, 260, 'EditSimpleTextString');
}


function OpenPopup_GalleryPopup(tcUrl)
{
	openPopup('/user/popup/galleryPopup.php?'+tcUrl, 760, 640, 'GalleyPopup');
}

function OpenPopup_MoveCatalog(tcUrl)
{
	openPopup('/admin/popup/moveCatalog.php?'+tcUrl, 760, 640, 'MoveCatalog', true);
}
function OpenPopup_SetProductCatalog(tcUrl)
{
	openPopup('/admin/popup/setProductCatalog.php?'+tcUrl, 760, 640, 'SetProductCatalog', true);
}

function OpenPopup_QualityFilter(tcUrl)
{
	openPopup('/admin/popup/editQualityFilter.php?'+tcUrl, 400, 300, 'QualityFilter');
}
function OpenPopup_EditAttribute(tcUrl)
{
	openPopup('/admin/popup/editAttribute.php?'+tcUrl, 400, 240, 'EditBanner');
}
function OpenPopup_ViewImage(tcUrl, tnWidth, tnHeight)
{
	openPopup(''+tcUrl, tnWidth, tnHeight, 'ViewImage');
}

function OpenPopup_MoveHereProduct(tcUrl, tnObjectCount)
{
	if(typeof(tnObjectCount) != 'undefined')
	{
		if(tnObjectCount > 25)
			tnObjectCount = 25;
	}
	else
	{
		tnObjectCount = 25;
	}

	var lnHeight = (tnObjectCount+1) * 19 + 150;
	openPopup('/admin/popup/listMoveHereProduct.php?'+tcUrl, 400, lnHeight, 'MoveHereProduct', true);
}
function OpenPopup_SetLinkedProductsCatalog(tcUrl)
{
	openPopup('/admin/popup/setLinkedProducts.php?'+tcUrl, 760, 640, 'SetLinkedProducts', true);
}
function OpenPopup_SetBannerCatalog(tcUrl)
{
	openPopup('/admin/popup/setBannerCatalog.php?'+tcUrl, 760, 640, 'SetBannerCatalog', true);
}

function OpenPopup_SetBannerChapter(tcUrl)
{
	openPopup('/admin/popup/setBannerChapter.php?'+tcUrl, 760, 640, 'SetBannerCatalog', true);
}

function OpenPopup_EditClientFiz(tcUrl)
{
	openPopup('/admin/popup/editClient.php?'+tcUrl, 450, 440, 'EditClientFiz', false, false);
}

function OpenPopup_EditClientJure(tcUrl)
{
	openPopup('/admin/popup/editClient.php?'+tcUrl, 450, 480, 'EditClientJure', false, false);
}

function OpenPopup_EditOrder(tcUrl)
{
	openPopup('/admin/popup/editOrder.php?'+tcUrl, 450, 450, 'EditOrderJure', true, true);
}
function OpenPopup_AddOrderProduct(tcUrl)
{
	openPopup('/admin/popup/addOrderProduct.php?'+tcUrl, 450, 450, 'AddOrderProduct', true, true);
}

function OpenPopup_SaveDicItem(tcUrl)
{
	openPopup('/admin/popup/saveDicItem.php?'+tcUrl, 10, 10, 'SaveDicItem', false, false);
}
function OpenPopup_EditDictItem(tcUrl)
{
	openPopup('/admin/popup/editDictItem.php?'+tcUrl, 400, 300, 'EditDictItem', false, false);
}
function OpenPopup_DictFullText(tcUrl)
{
	openPopup('/admin/popup/DictFullText.php?'+tcUrl, 400, 300, 'EditDictItem', false, false);
}
function OpenPopup_EditProduct(tcUrl)
{
	openPopup('/admin/popup/editProduct.php?'+tcUrl, 400, 300, 'EditDictItem', false, false);
}

function OpenPopup_EditSpeedIndex(tcUrl)
{
	openPopup('/admin/popup/editSpeedIndex.php?'+tcUrl, 400, 300, 'EditSpeedIndex', false, false);
}
function OpenPopup_EditProtector(tcUrl)
{
	openPopup('/admin/popup/editProtector.php?'+tcUrl, 400, 300, 'EditDictItem', false, false);
}
function OpenPopup_EditDiameter(tcUrl)
{
	openPopup('/admin/popup/editDiameter.php?'+tcUrl, 400, 150, 'EditDictItem', false, false);
}

function OpenPopup_ChoiseAlternative(tcUrl)
{
	openPopup('/user/popup/choiceAlternative.php?'+tcUrl, 400, 250, 'ChoiceAlternative', false, false);
}

function OpenPopup_EditAccessory(tcUrl)
{
	openPopup('/admin/popup/editAccessory.php?'+tcUrl, 400, 300, 'EditAccessory', false, false);
}


 /*=====================================================
 ================= base64.js ======================
 =====================================================*/ 
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}
 /*=====================================================
 ================= calup.js ======================
 =====================================================*/ 
var mouseeY;
var mouseeX;
var iii = 5;
var xxd;
var abbbc=0;
var yyd;
moz_lay='idnumer';
var mas = new Array();
calcz=null;
var valentins=1;
laukums=null;
datums=new Date();





function movein3(which,html){
which.style.background='#E2E3E7'
}
function moveout3(which, html){
which.style.background='#F2F3ED'
}


function movein4(which,html){
which.style.background='#C6CBCF'
}
function moveout4(which, html){
which.style.background='#F2F3ED'
}

function widd(o) {
    if (document.layers) return o.clip.width;
    return o.offsetWidth;
}

function heighh(o) {
    if (document.layers) return o.clip.height;
    return o.offsetHeight;
}

function OT_inside(o,x,y,dx1,dy1,dx2,dy2) {
   var l=xxd;
   var t=yyd;
   if (valentins==1 && abbbc!=1) {
            return ((x-(dx1?dx1:0)>=l)&&(y-(dy1?dy1:0)>=t)&&(x-(dx2?dx2:0)<l+widd(o))&&(y-(dy2?dy2:0)<t+heighh(o)));
   }

   else {
        return true;
   }

}


function getel(a,b,c) {
    mas[0]=document.getElementById(a);
}

function OT_move(o,x,y) {
//x=100; y=100;
    if (document.layers)
        o.moveToAbsolute(x,y);
    else if (o.style.left&&(!o.style.pixelLeft)) {
        o.style.left=x+'px';
        o.style.top=y+'px';
    } else {
        o.style.pixelLeft=x;
        o.style.pixelTop=y;
    }
}

function get_date(a,b,c,d,e,f) {

    xxd=e;
    yyd=f;
        getel(b,c,d);
    var o=(document.getElementById?document.getElementById(moz_lay):(document.all?document.all[moz_lay]:document[moz_lay]));
    var n=(calcz==null);
    if (laukums&&(a==laukums)) return false;
    if (!n) {
        if (document.layers)
            calcz.visibility='hide';
        else
            calcz.style.visibility='hidden';
    }
    calcz=o;
    laukums=a;
    var d;
    if (a.name=='inDate') {
        datums=new Date();
        d=new Date();
        d.setDate(d.getDate()+14);
    } else if (a.name=='departureDate') {
        datums=new Date();
        d=new Date();
        d.setDate(d.getDate()+14);
    } else {
        d=new Date(datums.getFullYear(),datums.getMonth(),datums.getDate());
        d.setDate(d.getDate()+2);
    }
    OT_render(d.getMonth()+1,d.getFullYear());
    OT_move(o,e,f);
    if (document.layers)
        o.visibility='show';
    else
        o.style.visibility='visible';
    if (n) {
        if (document.layers)
            document.captureEvents(Event.MOUSEDOWN);
        else
            document.onmousedown=cfff;
    }
}

function cfff(e) {
    if (calcz==null) return;
    var x=(document.all?event.clientX+document.body.scrollLeft:e.pageX);
    var y=(document.all?event.clientY+document.body.scrollTop:e.pageY);
    if (!(OT_inside(laukums,x,y,0,0,4,0)||OT_inside(calcz,x,y))) {OT_close(); }//
}

function cal_settings(y,m,d) {

    if (calcz==null) return;
   // alert(document.all["T1"]);
    if (m < 10) m = '0' + m;
    if (d < 10) d = '0' + d;
    mas[0].value=y+'-'+m+'-'+d;
    OT_close();
}

function OT_close2() {

    if (parent.document.layers)
        parent.calcz.visibility='hide';
    else {
        if (parent.calcz)
        parent.calcz.style.visibility='hidden';
    }
    if (parent.calcz) {
        if (parent.document.layers)
            parent.document.releaseEvents(Event.MOUSEDOWN);
        else
            parent.document.onmousedown=null;
    }
    parent.calcz=null;
    parent.laukums=null;
    parent.abbbc=1;
}

function setHeader(_head) {
     document.getElementById('head_id').innerHTML = _head;

}


function setBold(_head) {
     i = 0;
     while (document.getElementById('curentmenu' + i)) {
         document.getElementById('curentmenu' + i).style.fontWeight = 'normal';
         i++;
     }

     _head.style.fontWeight = 'bold';
}

function OT_close() {

    if (document.layers)
        calcz.visibility='hide';
    else
        calcz.style.visibility='hidden';
    if (calcz!=null) {
        if (document.layers)
            document.releaseEvents(Event.MOUSEDOWN);
        else
            document.onmousedown=null;
    }
    calcz=null;
    laukums=null;
    abbbc=1;
}

function OT_render(month,year) {

    if (calcz==null) return;
    var t_y=datums.getFullYear();
    var t_m=datums.getMonth()+1;
    var t_d=datums.getDate();
    var d=new Date(year,month-1,1);
    var max=(month==2?28+((year%4==0)&&((year%100!=0)||(year%400==0))?1:0):30+(month<8?1-((month-1)%2):(month-1)%2));
    var html='<table border=0 class="topmenu" cellpadding=0 cellspacing=0 bgcolor="#A0A3AA" style=" z-index:10"><tr><td><table border=0 cellpadding=3 cellspacing=1 width=150><tr bgcolor="#EBF3FE"><td valign="top" align="center" colspan="7" height="1" color="#3E4663"><a href="javascript:void(0)" onclick="OT_render(';
    html+=(month>1?month-1:12)+',' +(month>1?year:year-1)+')"><img src="/arn/images/a_left.gif" width=8 height=8 border=0></a><span style="font-family: verdana" color="#3E4663" class="topmenu22">&nbsp;&nbsp;';
    html+=menesis[month-1]+' '+year+'&nbsp;&nbsp;</span><a href="javascript:void(0)" onclick="OT_render('+(month<12?month+1:1)+','+(month<12?year:year+1)+')"><img src="/arn/images/a_right.gif" width=8 height=8 border=0></a></td></tr><tr bgcolor="#C6CBCF">';
    html+='<td align=center class="topmenu33" style="color:3E4663">P</td>\
    <td align=center class="topmenu33" style="color:3E4663">O.</td>\
    <td align=center class="topmenu33" style="color:3E4663">T.</td>\
    <td align=center class="topmenu33" style="color:3E4663">C.</td>\
    <td align=center class="topmenu33" style="color:3E4663">P.</td>\
    <td align=center class="topmenu33" style="color:FF0000">S.</td>\
    <td align=center class="topmenu33" style="color:FF0000">Sv.</td></tr>';
    var offset=d.getDay();
    var count=1,i,a;
    for (i=1;i<=max;i++) {

        if (count==1) html+='<tr bgcolor=white>';
        if ((i==1)&&(offset>1)) {
            //alert(offset);

            html+='<td colspan='+(offset-1)+' bgcolor="#FFFFFF" class="topmenu22">&nbsp;</td>';
            count=offset;
        }
        else if ((i==1)&&(offset==0)) {
            //alert(offset);
            if (offset <=  0) offset = 7;

            html+='<td colspan='+(offset-1)+' bgcolor="#FFFFFF" class="topmenu22">&nbsp;</td>';
            count=offset;
        }
if (month==mmz && year==yyz && i==ddz) {
 html+='<td align=center onmouseover="movein4(this)" onmouseout="movein4(this)" style="background-color: #C6CBCF;"><font face="arial,helvetica" size=1><a class="ipt3" ';
  if (count>5)
{
html+=' style="color:#FF0000" ';
        }
 html+=' href="javascript:cal_settings('+year+','+month+','+i+')" onclick="">'+i+'</a></font></td>';
         }
else {
html+='<td align=center onmouseover="movein3(this)" onmouseout="moveout3(this)" style=""><font face="arial,helvetica" size=1><a class="ipt3"  ';
  if (count>5)
{
html+=' style="color:#FF0000" ';
        }
 html+='  href="javascript:cal_settings('+year+','+month+','+i+')" onclick="">'+i+'</a></font></td>';    }
        if ((i==max)&&(count<7)) {
            html+='<td colspan='+(7-count)+' bgcolor="#FFFFFF" class="topmenu22">&nbsp;</td>';
            count=7;
        }
        count++;
        if (count>7) {
            count=1;
            html+='</tr>';
        }
    }
    html+='</table></td></tr></table>';
    if (document.layers) {
        calcz.document.open('text/html');
        calcz.document.write(html);
        calcz.document.close();
    } else
        calcz.innerHTML=html;

}


var IE = document.all?true:false;
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
var tempX = 0;
var tempY = 0;
function getMouseXY(e) {

if (IE) { // grab the x-y pos.s if browser is IE
 
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
}
else {  // grab the x-y pos.s if browser is NS
tempX = e.pageX;
tempY = e.pageY;
}
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;}
mouseeX = tempX;
mouseeY = tempY;
//window.status=mouseeX+" "+mouseeY;
return true;
}
 /*=====================================================
 ================= popupWindow.js ======================
 =====================================================*/ 
// Browsera noteikana
var glIs_MSIE		= false;
var glIs_Opera		= false;
var glIs_FireFox	= false;

var gcUserAgent = navigator.userAgent;
var gcBrowser = 'Unknow';
var gaSupported = Array();
gaSupported['CreatePopup'] = false;

if(gcUserAgent.indexOf( "MSIE" ) != -1)
{
	glIs_MSIE = true;
	gcBrowser = 'IE';
	gaSupported['CreatePopup'] = true;
}
if(gcUserAgent.indexOf( "Opera" ) != -1)
{
	glIs_Opera = true;
	gcBrowser = 'Opera';
}
if(gcUserAgent.indexOf( "Firefox" ) != -1)
{
	glIs_FireFox = true;
	gcBrowser = 'FireFox';
}

var goPopupWindowObject = null;

function PopupWindow()
{
	this.cAlign = 'Mouse'; // Objekts pc kura noteikt popupa pozciju
	this.cStyleLink = null;
	this.cScriptLink = '/js/all.js';
	this.cOnUnload = null;
}
PopupWindow.prototype.GetElem = function(tcID)
{
	return goPopupWindowObject.document.getElementById(tcID);
}
PopupWindow.prototype.Close = function(tcID)
{
	
	if(goPopupWindowObject == null)
		return;

	switch(gcBrowser)
	{
		case 'FireFox'	:
			goPopupWindowObject.style.visibility = 'hidden';
			window.onclick = null;
			break;
		case 'IE'		:
			goPopupWindowObject.hide();
			break;
	}
}
//goPopupWindowObject = window.createPopup();
PopupWindow.prototype.Open = function(tcContent, tcSourceObjectID)
{
	var lnLeft, lnTop;
	var loSourceObj = document.getElementById(tcSourceObjectID);
		//alert(tcContent);

	if(glIs_MSIE)
	{

		if(this.cAlign == 'Mouse')
		{
			lnLeft 	= event.clientX;
			//document.body.scrollTop
			lnTop	= event.clientY;
		}

		if(this.cAlign == 'Object')
		{
			lnLeft 	= document.body.scrollLeft 	+ GetLeft(loSourceObj) +2 ;
			lnTop	= document.body.scrollTop	+ GetTop(loSourceObj) + loSourceObj.offsetHeight+4;
			
		}
		if(this.cAlign == 'Manual')
		{
			lnLeft	= this.nLeft;
			lnTop	= this.nTop;
		}
		// Ja popaps jau nav izveidots tad izveidojam to
		//if(!goPopupWindowObject) 
			goPopupWindowObject = window.createPopup();
		lcOnUnload = '';
		/*
		if(this.cOnUnload)
			lcOnUnload = " onunload='"+this.cOnUnload+"' ";
		*/
		tcContent = "<BODY style='margin: 0 0 0 0; padding: 0 0 0 0' "+ lcOnUnload +">"+tcContent+"</body>";
		if(this.cStyleLink)
		{
			tcContent = "<link href='"+this.cStyleLink+"' rel='stylesheet' type='text/css'>\r\n"
				+ tcContent;
		}
		if(this.cScriptLink)
		{
			tcContent = "<script type='text/javascript' src='"+this.cScriptLink+"'></script>\r\n"
				+ tcContent;
		}
		
		// Ierakstam popup HTML saturu		
		goPopupWindowObject.document.write(tcContent);
		goPopupWindowObject.document.body.style.border = 'none';
		goPopupWindowObject.document.body.style.margin = '0 0 0 0';
		goPopupWindowObject.document.body.style.overflow = 'visible';
		
		// Aktivizjam popupu, bet lai lietotjs to neredz
		goPopupWindowObject.show( 0, 0, 0, 0, 0);
		var loFrameDiv = goPopupWindowObject.document.getElementById('frame');

		// Noskaidrojam popup izmrus
		
		var lnRealHeight = goPopupWindowObject.document.body.scrollHeight;
		var lnRealWidth = goPopupWindowObject.document.body.scrollWidth;
		
		
		// Veram ciet un va aktulaj izmr
		goPopupWindowObject.hide();
		goPopupWindowObject.show(lnLeft, lnTop, lnRealWidth, lnRealHeight, document.body);			
		//alert(goPopupWindowObject.document.body.onunload);
		//goPopupWindowObject.document.body.onunload = PopupWindow_Close;
		//goPopupWindowObject.show(lnLeft, lnTop, w, h, document.body);			
		event.returnValue = false;
		event.cancelBubble = true;
	}
	if(glIs_FireFox)
	{
		lnLeft	= GetLeft(loSourceObj);
		lnTop 	= GetTop(loSourceObj)+GetHeight(loSourceObj);
		goPopupWindowObject = document.getElementById('PopupWindowDiv');
		goPopupWindowObject.innerHTML = tcContent;
		lnWidth 	= GetWidth(goPopupWindowObject);
		lnHeight 	= GetHeight(goPopupWindowObject);
		
		if(lnTop + lnHeight > document.height)
		{
			lnTop = GetTop(loSourceObj) - lnHeight - 2;
		}
		if(lnLeft + lnWidth > document.width)
		{
			lnLeft = document.width - lnWidth;
		}
		if(lnTop < 0)
		{
			lnTop = 0;
		}
		
		goPopupWindowObject.style.top = lnTop;
		goPopupWindowObject.style.left = lnLeft;
		goPopupWindowObject.style.visibility = 'visible';
		window.captureEvents(Event.CLICK);
		window.onclick = PopupWindow_ClickEvent;
		window.oncontextmenu = PopupWindow_ClickEvent;
		glPopupWindow_IgnoreFirstClick = true;
	}
}
function PopupWindow_Close()
{
	alert('kuku');
}
function PopupWindow_ClickEvent(toEvent)
{
	if(glPopupWindow_IgnoreFirstClick)
	{
		glPopupWindow_IgnoreFirstClick = false;
		return;
	}
	//alert('c');
	var x 		= toEvent.pageX;
	var y 		= toEvent.pageY;
	var left 	= GetLeft(goPopupWindowObject);
	var top 	= GetTop(goPopupWindowObject);
	var right 	= left + GetWidth(goPopupWindowObject);
	var bottom 	= top + GetHeight(goPopupWindowObject);
	if(x < left || x > right || y < top || y > bottom)
		goPopupWindow.Close();
	//alert(toEvent.pageX);
	//alert('kuku');
}

var goPopupWindow = new PopupWindow();

 /*=====================================================
 ================= cms.js ======================
 =====================================================*/ 
function UniqueID()
{
	ldDate = new Date();
	return ldDate.getTime();
}
function CenterWindow(toWin, tnWidth, tnHeight)
{
	lnX = screen.width / 2	- tnWidth / 2;
	lnY = screen.height / 2	- tnHeight / 2;
	toWin.moveTo(lnX, lnY);
}

function GetWindow_Width()
{
	return document.body.offsetWidth;
}
function GetWindow_Height()
{
	return document.body.offsetHeight;
}

function GetCenterWindow_Left(tnWidth)
{
	return screen.width / 2	- tnWidth / 2;
}
function GetCenterWindow_Top(tnHeight)
{
	return screen.height / 2	- tnHeight / 2;
}

function openPopup(tcUrl, tnWidth, tnHeight, tcWindowName, tlResizeable ,tlScrolled, tnPosX, tnPosY, tcCustomOptions)
{
	if(("" + tcWindowName) == "undefined")
	{
		tcWindowName = UniqueID();
	}

	tcWindowName = "popup_"+tcWindowName;

	tlResizeable 	= typeof(tlResizeable) 	== "undefined" || !tlResizeable ? false : true;
	tlScrolled	= typeof(tlScrolled) 	== "undefined" || !tlScrolled ? false : true;

	var lcScrolled 	= tlScrolled  ? 'yes' : 'no';
	var lcResizable = tlResizeable ? 'yes' : 'no'; 
	
	// Ja logam ir iespejams mainit izmerus tad ieprieksejie varetu but ieks cookie 
	if(tlResizeable)
	{
		
		var lcCookieSizes = GetCookie("WinSize_"+tcWindowName);

		if(lcCookieSizes)
		{
			var laSizes =lcCookieSizes.split('x');
			tnWidth 	= laSizes[0] - 1;
			tnHeight 	= laSizes[1] - 1;   
		}	
	}

	var lnLeft	= tnPosX != null ? tnPosX : GetCenterWindow_Left(tnWidth);
	var lnTop	= tnPosY != null ? tnPosY : GetCenterWindow_Top(tnHeight);

	var lcSettings = 
		"left="			+lnLeft		+
		",top="			+lnTop		+
		",scrollbars="	+lcScrolled	+
		",resizable="	+lcResizable+
		",width="		+tnWidth	+
		",height="		+tnHeight;

	if(tcCustomOptions != null)
	{
		lcSettings += ',' + tcCustomOptions;
	}
	

	loWin = window.open(tcUrl, tcWindowName, lcSettings);
	loWin.focus();
}


function openPopupScrolled(tcUrl, tnWidth, tnHeight)
{
	loWin = open(tcUrl, "popup"+UniqueID(), "scrollbars=yes,resizable=no,width="+tnWidth+",height="+tnHeight+"");
	loWin.focus();
}

function editSimpleText(tcTask, tnChapterID, tcLangID, tcFieldName, tcLogicID)
{
	if(tcTask == 'edit' || tcTask == 'add')
	{
		$lcUrl = "editSimpleText.php?task=" +tcTask
			+ "&chapterID="		+ tnChapterID
			+ "&textLangID="	+ tcLangID
			+ "&field_name="	+ tcFieldName
			+ "&logic_id=" 		+ tcLogicID;
		//alert();
		openPopup($lcUrl, 650, 550);
	}
	if(tcTask == 'view')
	{
		window.location = "?text_lang_id="+tcLangID;
	}
	if(tcTask == 'drop' && AreYouSure())
	{
		window.location = "?delete_text_id="+tnChapterID;
	}
	
}

// ============== GALLERY CHAPTER
function editGalleryChapter(tnID)
{
	manageGalleryChapter("edit", tnID);
}
function deleteGalleryChapter(tnID)
{
	manageGalleryChapter("drop", tnID);
}
function addGalleryChapter(tnParentID)
{
	manageGalleryChapter("add", 0, tnParentID);
}

function manageGalleryChapter(tcTask, tnID, tnParentID)
{
	if(tcTask == "add" || tcTask == "edit" || tcTask == "drop")
	{
		lcUrl = "popup/editGalleryChapter.php?task=" + tcTask;
		if(tcTask == "add")
			lcUrl += "&parent_id=" + tnParentID;
		else
			lcUrl += "&id=" + tnID;
		openPopup(lcUrl, 500, 450);
	}
	else
	{
		window.location.href = "?task=" + tcTask + "&id=" + tnID;
	}
}
// ============== GALLERY FOLDER
function editGalleryFolder(tnID)
{
	manageGalleryFolder("edit", tnID);
}
function deleteGalleryFolder(tnID)
{
	manageGalleryFolder("drop", tnID);
}
function addGalleryFolder(tnParentID)
{
	manageGalleryFolder("add", 0, tnParentID);
}

function manageGalleryFolder(tcTask, tnID, tnParentID)
{
	if(tcTask == "add" || tcTask == "edit" || tcTask == "drop")
	{
		lcUrl = "popup/editGalleryFolder.php?task=" + tcTask;
		if(tcTask == "add")
			lcUrl += "&parent_id=" + tnParentID;
		else
			lcUrl += "&id=" + tnID;
		openPopup(lcUrl, 500, 450);
	}
	else
	{
		window.location.href = "?task=" + tcTask + "&id=" + tnID;
	}
}

