﻿if(typeof Sys != "undefined")
{
	Sys.Application.add_load(InitControls_js)
}

function InitControls_js()
{
	var a = document.createElement("a");
	a.style.display = "none";
	a.id = "lnkHidden_Controls";
	document.getElementsByTagName("form")[0].appendChild(a);
	Controls.links.hidden = a;
}

Controls = function(){};

Controls.links = {};
Controls.loading = {};
Controls.loading.isLock = false;
Controls.loading.i = 0;

var isIE = navigator.appVersion.match(/MSIE/) == "MSIE";

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ViewCard Functions
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ViewCard = {};

ViewCard.openSection = function(id, noScroll)
{
	var objDiv = $("div" + id);
	var objImgMin = $("imgMin" + id);
	objDiv.style.display = "";
	objImgMin.className = "ImgArrowsIn";
	if($("imgMin" + id + "S"))
		$("imgMin" + id + "S").className = "ImgArrowsIn";

	var value = ViewCard.hdnOpenSections.value;
	var _id = "<" + id + ">";
	if(value.indexOf(_id) == -1)
		value += _id;
	ViewCard.hdnOpenSections.value = value;
	if(!noScroll && $("divViewControlScroll"))
		$("divViewControlScroll").scrollTop = $("gotoViewControl" + id).offsetTop;

}

ViewCard.hideSection = function(id, noScroll)
{
	var objDiv = $("div" + id);
	var objImgMin = $("imgMin" + id);
	objDiv.style.display = "none";
	objImgMin.className = "ImgArrowsOut";
	if($("imgMin" + id + "S"))
		$("imgMin" + id + "S").className = "ImgArrowsOut";

	var value = ViewCard.hdnOpenSections.value;
	var _id = "<" + id + ">";
	if(value.indexOf(_id) != -1)
		value = value.replace(_id, "");
	ViewCard.hdnOpenSections.value = value;
	if(!noScroll && $("divViewControlScroll"))
		$("divViewControlScroll").scrollTop = $("gotoViewControl" + id).offsetTop;
}

ViewCard.restoreSections = function()
{
	var value = ViewCard.hdnOpenSections.value;
	if(value != "")
	{
		var arr = value.split("><");
		for(var i = 0; i < arr.length; i++)
		{
			var id = arr[i].replace("<", "").replace(">", "");
			ViewCard.openSection(id, true);
		}
	}
}

ViewCard.expandCollapse = function(id)
{
	var objDiv = document.getElementById("div" + id);
	if (objDiv.style.display == "none")
	{ 
		ViewCard.openSection(id);
	}
	else
	{
		ViewCard.hideSection(id);
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DataGrid Control
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


DataGridControl = function(id, options)
{
	this.id = id;
	if($(id))
		this.table = $(id).getElementsByTagName("table")[0];
	this.handles = {};
	this.options = options;
	DataGridControl.instances[id] = this;
}

DataGridControl.instances = {};

DataGridControl.find = function(divId){
	var x = DataGridControl.instances[divId];
	if(x){
		return x;
	}
}

DataGridControl.prototype.formatData = function()
{
	for(var i = 0; i < this.table.rows.length; i++)
		for(var j = 0; j < this.table.rows[i].cells.length; j++)
		{
			var cell = this.table.rows[i].cells[j];
			var format, v;
			format = cell.getAttribute("format");
			v = cell.innerHTML;
			
			if (v == "") continue;
			var t = v;
			
			switch(format)
			{
				case "C": t = formatCurrency(v); break;
								 
				case "Y": t = v.split(" ")[0]; break;
				
				//case "S": t = v.gsub(/,/,", "); break;
				
				case "N": t = parseFloat(v).toFixed(cell.getAttribute("precision")); break;
				
				//case "CFL": t = CFL(v); break;
			}
			
			cell.innerHTML = t;
		}
}

DataGridControl.prototype.setDefaultStyle = function()
{
	for(var i = 0; i < this.table.rows.length; i++)
		for(var j = 0; j < this.table.rows[i].cells.length; j++)
		{
			var cell = this.table.rows[i].cells[j];
			var cssname = cell.getAttribute("cssname");
			
			if(cssname != null && cell.className != cssname)
				cell.className = cssname;
		}
}

DataGridControl.prototype.highlight = function(guid)
{
	var bFound = false;
	for(var i = 0; i < this.table.rows.length; i++)
	{
		var row = this.table.rows[i];
		
		if(row.getAttribute("guid") == guid)
		{
			for(var j = 0; j < row.cells.length; j++)
			{
				var cell = row.cells[j];
				if(!cell.getAttribute("cssname"))
					cell.setAttribute("cssname", cell.className)

				cell.className = cell.getAttribute("cssname") + "alt";
				bFound = true;
				//alert(cell.getAttribute("cssname") + "_alt");
			}
		}
	}
	
	return bFound;
}

DataGridControl.prototype.remove = function(guid)
{
	var bFound = false;
	for(var i = 0; i < this.table.rows.length; i++)
	{
		var row = this.table.rows[i];
		
		if(row.getAttribute("guid") == guid)
		{
			this.table.deleteRow(i);
			bFound = true;
		}
	}
	
	return bFound;
}

DataGridControl.prototype.getMarked = function()
{
	var guids = "";
	var comma = "";
	
	for(var i = 0; i < this.table.rows.length; i++)
	{
	
		var row = this.table.rows[i];
		
		var marks = row.getElementsByTagName("input")
		
		for(var j = 0; j < marks.length; j++)
		{
			if(marks[j].type == "checkbox" && marks[j].getAttribute("markitem") != null && marks[j].checked)
			{
				guids += comma + row.getAttribute("guid");
				comma = ",";
				break;
			}
			
		}
	}
	
	return guids;
}

DataGridControl.dURL = "/controls/BSWeb/DG_SetCheckMark.aspx";

DataGridControl.prototype.setCheckMark = function(mark,ID)
{
	var action = mark.checked? "setCheckMark": "clearCheckMark";
	var ind = mark.checked? 1: -1;
	var pars = "action=" + action + "&dgID=" + this.id + "&IDs=" + ID;
	var me = this;
    new Ajax.Request(DataGridControl.dURL, {method: 'post', onSuccess: function(e){}, parameters: pars} );
	this.options.selCnt += ind;
	this.updateSelectedCount();
}

DataGridControl.prototype.checkAllMark = function(mark)
{
	var checked = mark.checked;
	var marks = this.options.table.getElementsByTagName("input")
	var ind = 0;
	var IDs = "";
	var comma = "";
	for(var j = 0; j < marks.length; j++)
	{
		if(marks[j].type == "checkbox" && marks[j].getAttribute("markitem") != null)
		{
			if(!marks[j].checked && checked)
				ind++;
			if(marks[j].checked && !checked)
				ind--;
			marks[j].checked = checked;
			IDs += comma + marks[j].getAttribute("guid");
			comma = ",";
		}
	}
	var action = checked? "setCheckMark": "clearCheckMark";
	var pars = "action=" + action + "&dgID=" + this.id + "&IDs=" + IDs;
	var me = this;
    new Ajax.Request(DataGridControl.dURL, {method: 'post', onSuccess: function(e){}, parameters: pars} );
	this.options.selCnt += ind;
	this.updateSelectedCount();
}

DataGridControl.prototype.updateSelectedCount = function()
{
	if(this.options.selCnt < 0)
		this.options.selCnt = 0;
	this.options.lblSelectCount.innerHTML = this.options.selCnt;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Ajax
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var Ajax = function(){};

Ajax.Request = function(url, options)
{
	var method = options.method? options.method.toUpperCase(): "POST";

	var request = new Sys.Net.WebRequest();
	request.set_url(url);
	request.set_httpVerb(method);
	request.set_body(options.parameters);
	request.get_headers()["CustomClientClasses_AsyncPostBack"] = "true";
	request.get_headers()["Cache-Control"] = "no-cache";
	request.set_timeout(90000);
	request.add_completed(options.onSuccess? options.onSuccess: options.onComplete);
	request.invoke();
}

Ajax.Updater = function(updateId, url, options)
{
	var context = {updateId: updateId, onComplete: options.onComplete};
	var callback = function(s){Ajax._UpdaterComplete(s, context)};


	var method = options.method? options.method.toUpperCase(): "POST";

	var request = new Sys.Net.WebRequest();
	request.set_url(url);
	request.set_httpVerb(method);
	request.set_body(options.parameters);
	request.get_headers()["CustomClientClasses_AsyncPostBack"] = "true";
	request.get_headers()["Cache-Control"] = "no-cache";
	request.set_timeout(90000);
	request.add_completed(callback);
	request.invoke();
}

Ajax._UpdaterComplete = function(sender, context)
{
	var updateId = context.updateId;
	
	var reply = sender.get_responseData();

    $(updateId).innerHTML = reply;
	
	context.onComplete(sender);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Search Control And Filter Control functions
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function searchControlInit(controlID)
{
	var arrInput = document.getElementById(controlID).getElementsByTagName("input");
	for(var i in arrInput)
	{
		if(arrInput[i].id && arrInput[i].getAttribute && !arrInput[i].getAttribute("onkeypress"))
		{
				//alert(typeof arrInput[i].onkeypress +  ' ' + arrInput[i].id)
				arrInput[i].onkeypress = filterControlApplayFilter;
		}
	}
	
	var bDisplay = false;
	var arrFilters = document.getElementById(controlID).getElementsByTagName("div")
	for(var j in arrFilters)
	{
		if(typeof arrFilters[j].id != 'undefined')
			if (arrFilters[j].getAttribute("name") == "filterControlExpandCollapseSection")
			{
				var bInput = false;
				var bSelect = false;
				var bInputDisplay = false;
				var bSelectDisplay = false;
				var arrInput = arrFilters[j].getElementsByTagName("input");
				var index = arrInput.length;
				var arrOther = arrFilters[j].getElementsByTagName("select");
				for(var i = 0; i < arrOther.length; i++, index++) arrInput[index] = arrOther[i];
				for(var i in arrInput)
				{
					if(typeof arrInput[i].id != 'undefined')
						if (arrInput[i].id != "")
						{
							switch(arrInput[i].type)
							{
								case "checkbox":
									bInput = true;
									if(arrInput[i].checked) bInputDisplay = true;
									break;
								case "select-one":
									bSelect = true;
									if(arrInput[i].value != "") bSelectDisplay = true;
									break;
								case "text":
									bInput = true;
									if(arrInput[i].value != "") bInputDisplay = true;
									break;
							}
						}
				}
				if(bSelectDisplay && !bInput || bInputDisplay)
				{
					arrFilters[j].style.display = "";
					bDisplay = true;
				}
			}
	}
	//if(bDisplay) filterControlVisibility();
	var arrInput = document.getElementsByTagName("select");
	for(var i in arrInput)
		if(typeof arrInput[i].onchange == "function" && typeof arrInput[i].getAttribute != 'undefined')
			if (arrInput[i].getAttribute("listboxid") != null)
				arrInput[i].onchange();
				
}

function filterControlExpandCollapseDiv(divName)
{
	if (document.getElementById(divName).style.display == "none")
	{
		document.getElementById(divName).style.display = "";
		var arrInput = document.getElementById(divName).getElementsByTagName("input");
		for(var i in arrInput)
		{
			if(typeof arrInput[i].id != 'undefined')
				if (arrInput[i].id != "")
				{
					switch(arrInput[i].type)
					{
						case "checkbox":
						case "text":
							if(arrInput[i].offsetWidth != 0)
								{
									arrInput[i].focus();
									return;
								}
					}
				}
		}
	}
	else
		document.getElementById(divName).style.display = "none";
	//document.getElementById("FilterControlContainer").style.left = get_ww() - document.getElementById("FilterControlContainer").offsetWidth - 50;
}

function searchControlVisibility(strSearchName, blnValue)
{
	if (blnValue)
	{
		document.getElementById(strSearchName).style.display = "";
	}
	else
	{
		document.getElementById(strSearchName).style.display = "none";
	}
}

function filterControlClear()
{
	var arrInput = document.getElementById("filterPanel").getElementsByTagName("input");
	var index = arrInput.length;
	var arrOther = document.getElementById("filterPanel").getElementsByTagName("select");
	for(var i = 0; i < arrOther.length; i++, index++) arrInput[index] = arrOther[i];
	for(var i in arrInput)
	{
		if(typeof arrInput[i].id != 'undefined')
			if (arrInput[i].id != "")
			{
				switch(arrInput[i].type)
				{
					case "checkbox":
						arrInput[i].checked = false;
						break;
					case "select-one":
						/*var bDefaultSelected = false;
						for (var j = 0; j < arrInput[i].options.length; j++)
						{
							if(arrInput[i].options[j].defaultSelected)
							{
								arrInput[i].selectedIndex = j;
								bDefaultSelected = true;
								break;
							}
						}
						if(!bDefaultSelected)*/ arrInput[i].selectedIndex = 0;
						if(typeof arrInput[i].onchange == "function") arrInput[i].onchange();
						break;
					case "text":
						arrInput[i].value = "";
						break;
				}
			}
	}
	
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Listboxes common functions
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var listboxesDropdownsData = new Array();
var listboxesDataControl = "EditDetailsControl"

function handleListboxRelation(elem, child)
{

	var options = new Array();
	var j = 0;
	for(var i in listboxesData[child])
	{
		if(listboxesData[child][i] == elem.value) options[j++] = i;
	}
	
	var arrInput = document.getElementsByTagName("select");
	for(var i in arrInput)
		if(typeof arrInput[i].getAttribute != 'undefined')
			if (arrInput[i].getAttribute("listboxid") == child)
			{
				var objElem = arrInput[i];
				var oldValue = objElem.value;
				if(listboxesDropdownsData[objElem.id] == null)
				{
					listboxesDropdownsData[objElem.id] = new Array();
					for(var j = 0; j < objElem.options.length; j++)
					{
						listboxesDropdownsData[objElem.id][objElem.options[j].value] = objElem.options[j].text;
					}
				}
				objElem.options.length = 0;
				if(elem.value != "")
				{
					var bSelected = false;
					var ind = 0;
					if(listboxesDataControl != "EditDetailsControl") objElem.options[ind++] = new Option("", "");
					for(var j = 0; j < options.length; j++)
						if(options[j] == oldValue)
						{
							objElem.options[ind] = new Option(listboxesDropdownsData[objElem.id][options[j]], options[j]);
							objElem.options[ind++].selected = true;
							bSelected = true;
						}
						else
							objElem.options[ind++] = new Option(listboxesDropdownsData[objElem.id][options[j]], options[j]);
					if(listboxesDataControl != "EditDetailsControl" && !bSelected) objElem.value = "";
				}
				else
				{
					for(var j in listboxesDropdownsData[objElem.id])
					{
						if(j == oldValue)
						{
							objElem.options[j] = new Option(listboxesDropdownsData[objElem.id][j], j);
							objElem.options[j].selected = true;
						}
						else
							objElem.options[j] = new Option(listboxesDropdownsData[objElem.id][j], j);
						objElem.value = "";
					}
				}
				if(typeof objElem.onchange == "function") objElem.onchange();
				//alert("parent value: " + elem.value + "; child: " + child + "\n id: " + arrInput[i].id);
				//objElem.value = oldValue;
			}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//BSWebCalendar.js
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var popCalDstFldID;
var popCalDstFld;
var temp;
var popCalDateVal;
var Visible = false;
var currentDate = new Date();
var divName;

function popupCalendar()
{
	var tmpDate         = new Date();
	var tmpString       = "";
	var tmpNum          = 0;
	var dstWindowName   = "";

	if (arguments.length < 1)
	{
		alert("popupCalendar(): Wrong number of arguments.");
		return void(0);
	}

	if (Visible && popCalDstFldID == popupCalendar.arguments[0])	
	{
		closeCalPopup_BSWeb();
		return void(0);
	}

	Visible = true;
	
	dstWindowName = 'Cal';
	popCalDstFldID = popupCalendar.arguments[0];
	temp = popupCalendar.arguments[0];
	
	popCalDstFmt = 'dd.MM.yyyy'; //Localized Short Date Format String
	//popCalMonths = 'Январь,Февраль,Март,Апрель,Май,Июнь,Июль,Август,Сентябрь,Октябрь,Ноябрь,Декабрь'; //Localized Month Names String
	//popCalDays = 'В,П,В,С,Ч,П,С';   //Localized Day Names String
	//popCalToday = 'Сегодня';  //Localized Today string
	//popCalClose = 'Нет';  //Localized Close string
	//popCalTitle = 'Календарь';  //Window Title
	popCalFirstDayWeek = 1;  //First Day of Week

	popCalMonths = ''; //Localized Month Names String
	popCalDays = '';   //Localized Day Names String
	popCalToday = '';  //Localized Today string
	popCalClose = '';  //Localized Close string
	popCalTitle = '';  //Window Title
	

	if (popCalDstFldID != "")
	  popCalDstFld = document.getElementById(popCalDstFldID);

	if (popCalDstFmt == "")
	  popCalDstFmt = "m/d/yyyy";

	if (popCalMonths == "")
	  popCalMonths = "Январь,Февраль,Март,Апрель,Май,Июнь,Июль,Август,Сентябрь,Октябрь,Ноябрь,Декабрь";
 
	if (popCalDays == "")
	  popCalDays = "Вс,Пн,Вт,Ср,Чт,Пт,Сб";
	
	if (popCalToday == "" || typeof popCalToday == "undefined")
	  popCalToday = "Today";

	if (popCalClose == "" || typeof popCalClose == "undefined")
	  popCalClose = "Close";

	if (popCalTitle == "" || typeof popCalTitle == "undefined")
	  popCalTitle = "Calendar";

	tmpString = new String(popCalDstFld.value);  

	if(tmpString == "")
		popCalDateVal = new Date()
	else
	{
		tmpNum = tmpString.lastIndexOf( "/" );
		if ( (tmpString.length - tmpNum) == 3 )
		{
			tmpString = tmpString.substring(0,tmpNum + 1)+"20"+tmpString.substr(tmpNum+1);
			popCalDateVal = new Date(tmpString);
		}
		else
		{
			popCalDateVal = getDateFromFormat(tmpString,popCalDstFmt);
		}
	}
	
	if( popCalDateVal.toString() == "NaN" || popCalDateVal.toString() == "0")
	{
		popCalDateVal = new Date();
		//popCalDstFld.value = "";
	}

 	var dateString = String(popCalDateVal.getMonth()+1) + "/" + String(popCalDateVal.getDate()) + "/" + String(popCalDateVal.getFullYear());

	// сформировать и настроить слой
	tmp = GetCalendarLayer_BSWeb();
	if (!tmp)
	{
		var newlayer = document.createElement("DIV");
		newlayer.id = "CalendarID";
		newlayer.style.position = "absolute";
		newlayer.style.left = 0;
		newlayer.style.top = 0;
		newlayer.style.zIndex = 50;
		document.getElementsByTagName("body")[0].appendChild(newlayer);
		tmp = GetCalendarLayer_BSWeb();
	}

	var tmpCalendar;
	var x = 0;
	var y = 0;

	//tmpCalendar = document.getElementById(popupCalendar.arguments[0]+"");            
	        //tmpCalendar = document.all('CalendarID')
			tmpCalendar = document.getElementById(popupCalendar.arguments[0]+"");
			pageY=0;pageX=0
			par=tmpCalendar
			while(par){	
					pageY+=par.offsetTop
					pageX+=par.offsetLeft
					par=par.offsetParent
			}
			pageY+=tmpCalendar.offsetHeight
			
            /*horizontal = document.body.scrollWidth - tmp.offsetWidth;
            vertical = document.body.scrollHeight - tmp.offsetHeight;
            X_pos = document.body.scrollLeft + pageX -150; 
			st=document.body.scrollTop || document.documentElement.scrollTop;
            Y_pos =st + pageY + 10; 
            X_pos2_right = document.body.scrollLeft + pageX - tmp.offsetWidth - 5; 
            Y_pos2 = st + pageY - tmp.offsetHeight - 5;
            if (X_pos2_right < 0) 
                X_pos2_right=0;
            if (X_pos < horizontal)
                tmp.style.left = X_pos + "px";
            else
                tmp.style.left = X_pos2_right + "px";
            if (Y_pos < vertical)
                tmp.style.top = Y_pos + "px";
            else
				tmp.style.posTop = Y_pos2 + "px";*/
				//alert(pageX + " " + tmp.offsetWidth + " " + document.body.scrollWidth);
			if(document.body.scrollWidth < pageX + 185)
				pageX -= (pageX + 185 - document.body.scrollWidth);
		    tmp.style.left=pageX + "px";
			tmp.style.top=pageY + "px";
            tmp.style.visibility = "visible";


	// вывести календарь
	
	//tmpCalendar.innerText=""
	reloadCalPopup_BSWeb(dateString, dstWindowName);
	checkDropLists(tmp, true);
	
	return void(0);}
 
function closeCalPopup_BSWeb()
{
	popCalData=""
	
	var tmp = GetCalendarLayer_BSWeb();
	
	tmp.innerHTML=popCalData;

	Visible = false;
	checkDropLists(tmp, false);
	
	return void(0);
}
 
function reloadCalPopup_BSWeb() //[0]dateString, [1]dstWindowName
{
	var tmpDate = new Date( reloadCalPopup_BSWeb.arguments[0] );
	
	if (tmpDate.toString() == "Invalid Date")
	    tmpDate = new Date();
	
	tmpDate.setDate(1);
	
	var popCalData = calPopupSetData_BSWeb(tmpDate,reloadCalPopup_BSWeb.arguments[1]);
	
	var tmp = GetCalendarLayer_BSWeb();
	tmp.innerHTML = popCalData;
	tmp.innerHTML = popCalData;
	tmp.innerHTML = popCalData;
	tmp.innerHTML = popCalData;
	tmp.innerHTML = popCalData;
	return void(1);
}
 
function calPopupSetData_BSWeb(firstDay,dstWindowName)
{
	var popCalData = "";
    var lastDate = 0;
	var fnt = "";
	var dtToday = new Date();
	var thisMonth = firstDay.getMonth();
	var thisYear = firstDay.getFullYear();
	var nPrevMonth = (thisMonth == 0 ) ? 11 : (thisMonth - 1);
	var nNextMonth = (thisMonth == 11 ) ? 0 : (thisMonth + 1);
	var nPrevMonthYear = (nPrevMonth == 11) ? (thisYear - 1): thisYear;
	var nNextMonthYear = (nNextMonth == 0) ? (thisYear + 1): thisYear;
	var sToday = String((dtToday.getMonth()+1) + "/01/" + dtToday.getFullYear());
	var sPrevMonth = String((nPrevMonth+1) + "/01/" + nPrevMonthYear);
	var sNextMonth = String((nNextMonth+1) + "/01/" + nNextMonthYear);
	var sPrevYear1 = String((thisMonth+1) + "/01/" + (thisYear - 1));
	var sNextYear1 = String((thisMonth+1) + "/01/" + (thisYear + 1));
	var sPrevYear5 = String(thisMonth + "/01/" + (thisYear - 5));
	var sNextYear5 = String(thisMonth + "/01/" + (thisYear + 5));
	var sPrevYear10 = String(thisMonth + "/01/" + (thisYear - 10));
	var sNextYear10 = String(thisMonth + "/01/" + (thisYear + 10));
	var sMonthFmt = "m/01/" + thisYear;
 	var tmpDate = new Date( sNextMonth );

	tmpDate = new Date( tmpDate.valueOf() - 1001 );
	lastDate = tmpDate.getDate();

	if (this.popCalMonths.split) // javascript 1.1 defensive code
	{
		var monthNames = this.popCalMonths.split(",");
		var dayNames = this.popCalDays.split(",");
	}
	else  // Need to build a js 1.0 split algorithm, default English for now
	{
		var monthNames = new Array("Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь");
		var dayNames = new Array("Вс","Пн","Вт","Ср","Чт","Пт","Сб")
	}

 	var styles = "<style><body{font-family:verdana;font-size: 10px; color: #143156;}; td {  font-family: verdana; font-size: 10px; color: #143156}; A {text-decoration: none; color: #143156; font-family:verdana;font-size: 10px;};TD.day {}</style>"
	var cellAttribs = "align=\"center\" BGCOLOR=\"#FFFFFF\"onMouseOver=\"temp=this.style.backgroundColor;this.style.backgroundColor='#e0e6f1';\" onMouseOut=\"this.style.backgroundColor=temp;\""
	var cellToday = "align=\"center\" bordercolor=\"#e0e6f1\" BGCOLOR=\"#e0e6f1\"onMouseOver=\"temp=this.style.backgroundColor;this.style.backgroundColor='#e0e6f1';\" onMouseOut=\"this.style.backgroundColor=temp;\""
	var cellBg = "align=\"center\" class=\"CalcHeader\""

	var htmlHead = "<TABLE width=\"170\" BGCOLOR=\"white\" BORDER=\"1\" cellspacing=\"0\" cellpadding=\"0\" BORDERCOLOR=\"#839bc7\"><TR><TD>";
	var htmlTail = "</TD></TR></TABLE>";
	//var closeAnchor = "<input type=button style=\"FONT_SIZE: 7pt\" value=\""+popCalClose+"\" onClick=\"javascript:closeCalPopup()\">";            
	var closeAnchor="<table border='0' cellpadding='0' cellspacing='0' onclick='closeCalPopup_BSWeb()'><tr><td valign='top' style='background: url(/images/calc/button_87.png)'><div style='width: 5px; height: 23px'></div></td><td valign='top' class='button_bg_act_grey' style='padding-left: 0px;' nowrap>&nbsp;Закрыть</td><td valign='top' style='background: url(/images/calc/button_91.png)'><div style='width: 6px; height: 23px'></div></td></tr></table>"
	
	//var todayAnchor = "<input type=button style=\"FONT_SIZE: 7pt\" value=\""+popCalToday+"\" onClick=\"javascript:calPopupSetDate(popCalDstFld,'" + constructDate(dtToday.getDate(), dtToday.getMonth()+1, dtToday.getFullYear()) + "');closeCalPopup()\">";
	var todayAnchor="<table border='0' cellpadding='0' cellspacing='0' class='button_base' onclick=\"calPopupSetDate(popCalDstFld,'" + constructDate(dtToday.getDate(), dtToday.getMonth()+1, dtToday.getFullYear()) + "');closeCalPopup_BSWeb()\"><tr><td valign='top'><img src='/images/calc/button_87.png'></td><td valign='top' class='button_bg_act_grey' style='padding-left: 0px;' nowrap>&nbsp;Сегодня</td><td valign='top'><IMG src='/images/calc/button_91.png'></td></tr></table>"
	
	var prevMonthAnchor = "<img src=\"/images/calc/Arrow_left.gif\" onclick=\"javascript:reloadCalPopup_BSWeb('"+sPrevMonth+"','"+dstWindowName+"');\"  style='cursor:pointer'/>";
	var nextMonthAnchor = "<img src=\"/images/calc/Arrow_right.gif\" onclick=\"javascript:reloadCalPopup_BSWeb('"+sNextMonth+"','"+dstWindowName+"');\"  style='cursor:pointer'/>";
	var prevYear1Anchor = "<img src=\"/images/calc/Arrow_double_left.gif\" onclick=\"javascript:reloadCalPopup_BSWeb('"+sPrevYear1+"','"+dstWindowName+"');\"  style='cursor:pointer'/>";
	var nextYear1Anchor = "<img src=\"/images/calc/Arrow_double_right.gif\" onclick=\"javascript:reloadCalPopup_BSWeb('"+sNextYear1+"','"+dstWindowName+"');\"  style='cursor:pointer'/>";
	var prevYear5Anchor = "<a href=\"javascript:void(0)\" style=\"color: #0068A5;\" onclick=\"javascript:reloadCalPopup_BSWeb('"+sPrevYear5+"','"+dstWindowName+"');\" >" + (thisYear-5) + "</a>";
	var nextYear5Anchor = "<a href=\"javascript:void(0)\" style=\"color: #0068A5;\" onclick=\"javascript:reloadCalPopup_BSWeb('"+sNextYear5+"','"+dstWindowName+"');\" >" + (thisYear+5) + "</a>";
	var prevYear10Anchor = "<a href=\"javascript:void(0)\" style=\"color: #0068A5;\" onclick=\"javascript:reloadCalPopup_BSWeb('"+sPrevYear10+"','"+dstWindowName+"');\" >" + (thisYear-10) + "</a>";
	var nextYear10Anchor = "<a href=\"javascript:void(0)\" style=\"color: #0068A5;\" onclick=\"javascript:reloadCalPopup_BSWeb('"+sNextYear10+"','"+dstWindowName+"');\" >" + (thisYear+10) + "</a>";

	var sMonthsLine = "";
	for(var iMonth = 1, comma = ""; iMonth < 13; iMonth++, comma = "&nbsp;")
		sMonthsLine += comma + "<a href=\"javascript:void(0)\" style=\"color: #0068A5;\" onclick=\"javascript:reloadCalPopup_BSWeb('"+sMonthFmt.replace("m", iMonth)+"','"+dstWindowName+"');\" >" + iMonth + "</a>";

	popCalData += (htmlHead + fnt);
	popCalData += ("<DIV align=\"center\" style=\"width: 140px; background-color: white; \">");
	
	popCalData += ("<TABLE bgcolor=\"#F3F8FD\" cellspacing=\"0\" cellpadding=\"0\" width=\"170\">");          
	popCalData += ("<TR border=\"1\" bordercolor=\"#e0e6f1\"><TD style=\"margin: 0px\" width=\"35\" align=\"center\" "+cellBg);
	popCalData += (" >");
	popCalData += (prevMonthAnchor + "&nbsp;" + prevYear1Anchor + "</TD>");
	popCalData += ("<TD width=\"80\" align=\"center\" "+cellBg+ " >");
	popCalData += ("&nbsp;&nbsp;"+fnt+"<p style=\"margin: 0px; padding: 3px; color: #0068A5; font-family: verdana; font-weight: bold; font-size: 11px;\">" + monthNames[thisMonth] + ",<br>" + thisYear + "&nbsp;&nbsp;</p></TD>");
	popCalData += ("<TD style=\"margin: 0px\"  width=\"35\" align=\"center\" "+cellBg);
	popCalData += (" >");
	popCalData += (nextYear1Anchor + "&nbsp;" + nextMonthAnchor+"</TD></TR>");
	popCalData += "</TABLE>";
/*
	popCalData += ("<TABLE bgcolor=\"#F3F8FD\" cellspacing=\"0\" cellpadding=\"0\" width=\"170\">");          
	popCalData += ("<TR border=\"1\" bordercolor=\"#e0e6f1\"><TD style=\"margin: 0px\" width=\"10\" align=\"center\" "+cellBg);
	popCalData += (" >");
	popCalData += ("<p style=\"margin: 0px; padding: 3px; color: #0068A5; font-family: verdana; font-weight: bold; font-size: 11px;\">" + prevYear10Anchor + "&nbsp;" + prevYear5Anchor + "</p></TD>");
	popCalData += ("<TD width=\"20px\" align=\"center\" "+cellBg+ " ></TD>");
	popCalData += ("<TD style=\"margin: 0px\"  width=\"10\" align=\"center\" "+cellBg);
	popCalData += (" >");
	popCalData += ("<p style=\"margin: 0px; padding: 3px; color: #0068A5; font-family: verdana; font-weight: bold; font-size: 11px;\">" + nextYear5Anchor + "&nbsp;" + nextYear10Anchor+"</p></TD></TR>");
	popCalData += "</TABLE>";


	popCalData += ("<TABLE bgcolor=\"#F3F8FD\" cellspacing=\"0\" cellpadding=\"0\" width=\"170\">");          
	popCalData += ("<TR border=\"1\" bordercolor=\"#e0e6f1\"><TD style=\"margin: 0px\" width=\"10\" align=\"center\" "+cellBg+"></TD>");
	popCalData += ("<TD width=\"100%\" align=\"center\" "+cellBg+ " ><p style=\"margin: 0px; padding: 3px; color: #0068A5; font-family: verdana; font-weight: bold; font-size: 11px;\">" + sMonthsLine + "</p></TD>");
	popCalData += ("<TD style=\"margin: 0px\"  width=\"10\" align=\"center\" "+cellBg);
	popCalData += (" ></TD></TR>");
	popCalData += "</TABLE>";
*/	
	popCalData += ("<TABLE BORDERCOLOR=\"#FFFFFF\" BORDER=\"0\" cellspacing=\"1\" cellpadding=\"1\"  width=\"170\">" );
	popCalData += ("");
	popCalData += ("<TR>");

	var xday = 0;
	for (xday = 0; xday < 7; xday++)
	{
		popCalData += ("<TD width=\"30\" style=\"BORDER-BOTTOM-STYLE: solid; border-bottom-width: 1px; BORDER-BOTTOM-COLOR: #000000\" align=\"center\">"+"<FONT COLOR=\"#143156\" style=\"font-family: verdana; font-size: 11px; line-height: 11px; \">"+dayNames[(xday+popCalFirstDayWeek)%7]+"</FONT></TD>");
	};
	popCalData += ("</TR>");
	
	var calDay = 0;
	var monthDate = 1;
	var weekDay = firstDay.getDay();
	do
	{
		popCalData += ("<TR>");
		for (calDay = 0; calDay < 7; calDay++)
		{
			if(((weekDay+7-popCalFirstDayWeek)%7 != calDay) || (monthDate > lastDate))
			{
				popCalData += ("<TD width=\"30\">"+"&nbsp;</TD>");
				continue;
			}
			else
			{
				anchorVal = "<A style=\"font-size: 11px; color: #143156\" HREF=\"javascript:void(0)\">";
				jsVal = "javascript:calPopupSetDate(popCalDstFld,'" + constructDate(monthDate,thisMonth+1,thisYear) + "');closeCalPopup_BSWeb()";

				popCalData += ("<TD width=\"30\" ")
				var x = (firstDay.getMonth() == popCalDateVal.getMonth()) && (monthDate == popCalDateVal.getDate()) && (thisYear == popCalDateVal.getFullYear()); 
//				var y = (firstDay.getMonth() == dtToday.getMonth()) && (monthDate == dtToday.getDate()) && (thisYear == dtToday.getFullYear());
				
				if ( x )
					{
						popCalData += (cellToday+" onClick=\""+jsVal+"\">"+anchorVal);
					}	
				else
					{
						popCalData += (cellAttribs+" onClick=\""+jsVal+"\">"+anchorVal);
					}	
				
				popCalData += (monthDate+"</A></TD>")
				
				weekDay++;
				monthDate++;
			}
		}
		weekDay = popCalFirstDayWeek;
		popCalData += ("</TR>");
	} while( monthDate <= lastDate );

	popCalData += ("</TABLE></DIV>");
	popCalData += ("<h></h>")
		
	popCalData += ("<div class='calc' style=\"font-size: 11px; font-family: verdana; margin: 0px\"><TABLE BORDER=\"0\" cellspacing=\"0\" callpadding=\"0\" width=\"170\">");          
	popCalData += ("<TR><TD><CENTER>"+todayAnchor+"</CENTER></TD><TD><CENTER>"+closeAnchor+"</CENTER></TD>");
	popCalData += ("</TR></TABLE>");

	return( popCalData );
}
 
function calPopupSetDate()
{
	calPopupSetDate.arguments[0].value = calPopupSetDate.arguments[1];
}

// utility function
function padZero(num)
{
  return ((num <= 9) ? ("0" + num) : num);
}

// Format short date
function constructDate(d,m,y)
{
  var fmtDate = this.popCalDstFmt
  fmtDate = fmtDate.replace ('dd', padZero(d))
  fmtDate = fmtDate.replace ('d', d)
  fmtDate = fmtDate.replace ('MM', padZero(m))
  fmtDate = fmtDate.replace ('M', m)
  fmtDate = fmtDate.replace ('yyyy', y)
  fmtDate = fmtDate.replace ('yy', padZero(y%100))
  return fmtDate;
}

function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
	
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
		
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
7				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
	var newdate=new Date(year,month-1,date);
	return newdate;
}

function GetCalendarLayer_BSWeb()
{
	return document.getElementById('CalendarID');
}

function formatdate(mydate)
{
	var s = mydate+"";
	var t = "";
	
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//checkDropLists(objLayer,hide)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function checkDropLists(objLayer,hide)
{
	DropLists = document.getElementsByTagName("SELECT");

	var pCount = 0;
	//alert(isNaN(parseInt(obj.style.left.replace(/\px|\,/g,''))) || isNaN(parseInt(obj.style.top.replace(/\px|\,/g,''))));
	while(isNaN(parseInt(objLayer.style.left.replace(/\px|\,/g,''))) || isNaN(parseInt(objLayer.style.top.replace(/\px|\,/g,''))))
	{
		//alert(obj.obj.style.left + " " + obj.obj.style.left);
		objLayer = objLayer.offsetParent;
		if(++pCount > 5) break;
	}

	
	var width = parseInt(objLayer.offsetWidth);
	var height = parseInt(objLayer.offsetHeight);

 	for(i = 0; i < DropLists.length; i++)
	{
		obj = DropLists[i];
		var x = 0;
		var y = 0;
		var pr = 0;
		var otherNested = 1;
		
		while (obj != null)
		{
			//alert(x+";"+y);
			x += obj.offsetLeft;
			y += obj.offsetTop;
			if (obj.id.indexOf("tblDataRootNested") != -1) {
				pr = 1;
			}
			if (obj.id == objLayer.id) otherNested = 0;
			obj = obj.offsetParent;
		}
		
		x += -parseInt(objLayer.style.left.replace(/\px|\,/g,'')) + DropLists[i].offsetWidth;
		y += -parseInt(objLayer.style.top.replace(/\px|\,/g,'')) + DropLists[i].offsetHeight;

		if (hide && !pr) 
		{
			//alert(x+";"+y);
			if (x >= 0 && x <= (width + DropLists[i].offsetWidth) && y >=0 && y <= (height + DropLists[i].offsetHeight)) {
				DropLists[i].style.visibility = "hidden";
			}
		}
		else DropLists[i].style.visibility = "visible";
		
		if (!hide && pr || otherNested && pr) DropLists[i].style.visibility = "hidden";
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Validation 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var intErrorBorderWidth = 2;
var errorElement;
var blnValidationMessageDisplayed = false;

function showValidationMessage(objElement,strMessage)
{
	blnValidationMessageDisplayed = true;
	showBorder(objElement);
	errorElement = objElement;
}

function hideValidationMessage(objElement)
{	
	//alert("focus_" + objElement.id);
	//if (errorElement == objElement)
	{
//		if (!blnValidationMessageDisplayed) hideBorder();
		if (errorElement == objElement || objElement == document)
        {
            hideBorder();
            blnValidationMessageDisplayed = false;
        }
	}
}

function getRegularExpression(objElement)
{
	var strResult = "";
	var strRegExp = "";
	if (objElement.getAttribute("validation-expression")) strRegExp = objElement.getAttribute("validation-expression");
	
	strRegExp = strRegExp.replace("double", "-?\\d+[\.|\,]?\\d*");
	strRegExp = strRegExp.replace("int", "\\d+");
	var strValidFormat = "";
	if (objElement.getAttribute("validation-format")) 
		strValidFormat = objElement.getAttribute("validation-format")
	else
		return strRegExp;
	
	switch (strValidFormat)
	{
		case "email": 	if (strRegExp == "")
							strResult = "^[A-Za-z0-9._]+@[A-Za-z0-9._]+\\.[A-Za-z]{2,4}$";
						else
							strResult = strRegExp;
						break;
	
		case "name":	if (strRegExp == "") 
							strResult = "^.+$"; //"^[A-Za-z_]{2,}\s{0,1}-{0,1}[A-Za-z_]{0,}$"
						else
							strResult = strRegExp;
						break;
		case "phone":	if (strRegExp == "") 
							strResult = "^\d{0,3}$"
						else
							strResult = strRegExp;
						break;
						
	}
	return strResult;
}

function getValidationResultMessage(objElement)
{
	var strMessage = "";
	if (objElement.getAttribute("validation-message")) strMessage = objElement.getAttribute("validation-message");
    else strMessage = "Форма содержит некорректные значения. Пожалуйста, исправьте!";
	
	var strType = "";
	
	/*
	if (objElement.tagName.toLowerCase() == "select")
		strType = "select";
	else
		
	else
		strType = objElement.getAttribute("type").toLowerCase();
	*/
	
	switch (objElement.tagName.toLowerCase())
	{
		case "select": 	strType = "select";
						break;
		case "div": 	strType = "div";
						break;
		case "textarea": 	strType = "text";
						break;
        default: strType = objElement.getAttribute("type").toLowerCase();
	}
	
	if (strType == "text")
	{
		var strRegExp = getRegularExpression(objElement);
		var varRegExp = RegExp(strRegExp);
		var tempValue = trim(objElement.value);
        if(objElement.getAttribute("money")) tempValue = tempValue.replace(/,/g, "");
		if (!tempValue.match(varRegExp)) return strMessage;
        if(compareValues(objElement))
            return "";
        else
            return strMessage;
	}
	
	if (strType == "checkbox")
	{
		if (objElement.checked) return ""; else return strMessage;
	}
	
	if (strType == "select")
	{
 		if (objElement.value == "-3") return strMessage;
        if(compareValues(objElement))
            return "";
        else
            return strMessage;
	}
	
	if (strType == "div")
	{

        var arrObj = objElement.getElementsByTagName("input");
        
        for (var i = 0; i < arrObj.length; i++)
            if (arrObj[i].checked) 
                return "";
        
		return strMessage;
	}
}

function compareValues(objElem)
{
    var comElem = "";
    var comExpression = "";
    if(objElem.getAttribute("compare-element") != null) comElem = objElem.getAttribute("compare-element");
    if(objElem.getAttribute("compare-expression") != null) comExpression = objElem.getAttribute("compare-expression");
    if(comElem != "" && comExpression!= "")
    {
        hideValidationMessage($(comElem));
        var tempValue = objElem.value;
        var comValue = $(comElem).value;
        if(objElem.getAttribute("money")) tempValue = tempValue.replace(/,/g, "");
        if($(comElem).getAttribute("money")) comValue = comValue.replace(/,/g, "");
        tempValue = parseInt(tempValue);
        comValue = parseInt(comValue);
        if(isNaN(tempValue) || isNaN(comValue)) return true;
        switch(comExpression)
        {
            case "=":
                if (tempValue == comValue) return true; else return false;
            break;
            case ">":
                if (tempValue > comValue) return true; else return false;
            break;
            case "<":
                if (tempValue < comValue) return true; else return false;
            break;
            case ">=":
                if (tempValue >= comValue) return true; else return false;
            break;
            case "<=":
                if (tempValue <= comValue) return true; else return false;
            break;
            case "!=":
                if (tempValue != comValue) return true; else return false;
            break;
        }
    }
    return true;
}
function validate(objElement)
{
	//alert("blur_" + objElement.id);
	var strResult = "";
	//alert(blnValidationMessageDisplayed);
	//if (!blnValidationMessageDisplayed)
	{
		strResult = getValidationResultMessage(objElement);
		if(strResult == "")
			if(typeof objElement.validate == "function") strResult = objElement.validate();
		//alert(strResult);
		if (strResult != "") 
		{
			showValidationMessage(objElement, strResult);
		}
	}
	return strResult;
}


function validateForm()
{
	var strResult = "";
	blnValidationMessageDisplayed = false;
	var arrElements = getValidationElementsArray();
	for (var i = 0; i < arrElements.length; i++) 
	{
        //if(arrElements[i].offsetHeight == 0 || arrElements[i].disabled) continue;
		strResult = validate(arrElements[i]);
		if(strResult == "")
			if(typeof arrElements[i].validate == "function") strResult = arrElements[i].validate();
		if (blnValidationMessageDisplayed || strResult != "") return strResult;
	}
	return strResult;
}

function getValidationElementsArray()
{
	var arrResult = new Array();
	var arrElements = document.getElementsByTagName("*");
	var intCount = 0;
	for (var i = 0; i < arrElements.length; i++) 
	{
		var objValidationNode = arrElements[i].getAttributeNode("validation");
		if (objValidationNode) 
		{
			if (objValidationNode.value == "1")
			{
				arrResult[intCount] = arrElements[i];
				intCount += 1;
			}
		}
	}
	return arrResult;
}


function checkForm()
{
	var strResult = ""
	strResult = validateForm();
	if (!strResult == "") alert(strResult);
}


function getBorderDiv(strDivID)
{
	var objResult = document.getElementById(strDivID);
	if (!objResult)
	{
		objResult = document.createElement("DIV");
		objResult.id = strDivID;
		objResult.style.position = "absolute";
		objResult.style.fontSize = "0px";
		objResult.style.left = "0px";
		objResult.style.top = "0px";
		objResult.style.width = "0px";
		objResult.style.height = "0px";
		objResult.style.backgroundColor = "red";
        objResult.style.zIndex = 255;
		//document.getElementsByTagName("form")[0].appendChild(objResult);
		document.getElementsByTagName("body")[0].appendChild(objResult);
	
	}
	return objResult;
}

function updateValidationBorder()
{
    if(errorElement == null) return;
    if(blnValidationMessageDisplayed == false) return;
    showBorder(errorElement)
}

function showBorder(objElement)
{

	var brdLeft = getBorderDiv("brdLeft");
	var brdRight = getBorderDiv("brdRight");
	var brdTop = getBorderDiv("brdTop");
	var brdBottom = getBorderDiv("brdBottom");
	
	pageY = 0; pageX = 0;
	par = objElement;
	while (par)
	{	
		pageY += par.offsetTop;
		pageX += par.offsetLeft;
		par = par.offsetParent;
	}
	
	sl = document.body.scrollLeft; 
	st = document.body.scrollTop || document.documentElement.scrollTop;

	//alert(objElement.id);
	//left
	brdLeft.style.left = sl + pageX - intErrorBorderWidth + "px"; //objElement.offsetLeft - intErrorBorderWidth;
	//alert(brdLeft.style.left);
	brdLeft.style.top = pageY - intErrorBorderWidth + "px"; // objElement.offsetHeight; //objElement.offsetTop -intErrorBorderWidth;
	brdLeft.style.width = intErrorBorderWidth + "px";
	brdLeft.style.height = objElement.offsetHeight + intErrorBorderWidth * 2 + "px";
	brdLeft.style.display = "";
	//alert(brdLeft.style.left);
	
	//right
	brdRight.style.left = sl + pageX + objElement.offsetWidth + "px";
	brdRight.style.top = pageY - intErrorBorderWidth + "px";
	brdRight.style.width = intErrorBorderWidth + "px";
	brdRight.style.height = objElement.offsetHeight + intErrorBorderWidth * 2 + "px";
	brdRight.style.display = "";
	
	//top
	brdTop.style.left = sl + pageX - intErrorBorderWidth + "px";
	brdTop.style.top = pageY - intErrorBorderWidth + "px";
	brdTop.style.width = objElement.offsetWidth + intErrorBorderWidth * 2 + "px";
	brdTop.style.height = intErrorBorderWidth + "px";
	brdTop.style.display = "";
	
	//bottom
	brdBottom.style.left = sl + pageX - intErrorBorderWidth + "px";
	brdBottom.style.top = pageY + objElement.offsetHeight + "px";
	brdBottom.style.width = objElement.offsetWidth + intErrorBorderWidth * 2 + "px";
	brdBottom.style.height = intErrorBorderWidth + "px";
	brdBottom.style.display = "";

}

function hideBorder()
{
	getBorderDiv("brdLeft").style.display = "none";
    getBorderDiv("brdRight").style.display = "none";
	getBorderDiv("brdTop").style.display = "none";
	getBorderDiv("brdBottom").style.display = "none";
}

function doElementOnFocus(obj)
{
	hideValidationMessage(obj);
}

function doElementOnBlur(obj)
{
	validate(obj);
}

function attachValidationEventsToElement(objElement)
{
	//if(objElement.onfocus == null) objElement.onfocus = doElementOnFocus;
	//if(objElement.onblur == null) objElement.onblur = doElementOnBlur;
	AddEventHandler(objElement, "focus", doElementOnFocus);
	AddEventHandler(objElement, "blur", doElementOnBlur);
}

function attachValidationEventsToElements()
{
	var arrElements = getValidationElementsArray()
	for (var i = 0; i < arrElements.length; i++) 
	{
		attachValidationEventsToElement(arrElements[i]);
	}
}

//Common functions
function AddEventHandler(obj, eventName, functionNotify) {
	if (obj.attachEvent) {
		obj.attachEvent('on' + eventName, function (evt){if(!evt) evt = window.event; functionNotify.call(obj, evt);});
	}
	else if (obj.addEventListener) {
		obj.addEventListener(eventName, function(evt){if(!evt) evt = window.event; functionNotify.call(obj, evt)}, false);
	}
	else {
		obj['on' + eventName] = functionNotify;
	}
}
function RemoveEventHandler(obj, eventName, functionNotify) {
if (obj.detachEvent) {
		obj.detachEvent('on' + eventName, functionNotify);
	}
	else if (obj.removeEventListener) {
		obj.removeEventListener(eventName, functionNotify, true);
	}
	else {
		obj['on' + eventName] = null;
	}
}

function getObjectParentByTagName(obj,tName)
{
	while (obj) {
		obj = obj.parentNode;
		if (obj.tagName.toLowerCase() == tName.toLowerCase()) return obj;
	}
	return;
}

function doOnClickFileListImage(eID)
{
	var oEl = document.getElementById(eID);
	var oImg = document.getElementById("FileListControl_imgPhoto");
	if(oImg == null)
	{
		oImg = document.createElement("img");
		oImg.id = "FileListControl_imgPhoto";
		oImg.style.position = "absolute";
		oImg.style.left = 0;
		oImg.style.top = 0;
		oImg.style.borderStyle = "solid";
		oImg.style.borderWidth = "1px";
		oImg.style.borderColor = "black";
		oImg.style.zIndex = 10;
		oImg.onclick = function(){this.style.display = "none";};
		document.getElementsByTagName("body")[0].appendChild(oImg);
	}
	oImg.src = "";
	oImg.src = oEl.src;
	oImg.style.display = "";
	var st = document.body.scrollTop || document.documentElement.scrollTop;
	var sw = document.body.scrollLeft || document.documentElement.scrollLeft;
	oImg.style.left = (sw + (get_ww() - oImg.offsetWidth)/2) + "px";
	oImg.style.top = (st + (get_wh() - oImg.offsetHeight)/2) + "px";
}

function alertMessage(message, className)
{
	hideSelect();
	var newlayer = document.getElementById("divAlertMessage");
	if(!newlayer)
	{
		newlayer = document.createElement("div");
		newlayer.id = "divAlertMessage";
		document.getElementsByTagName("body")[0].appendChild(newlayer);
	}
	var html = '<table cellspacing="0" cellpadding="0" border="0" style="border-collapse: collapse; border-collapse: separate;"><tr><td class="{0}">';
	
	if(newlayer != null)
	{
		newlayer.style.position = "absolute";
		newlayer.style.zIndex = 255;
		newlayer.className = "AlertMessageContainer";
		if(className) html = html.replace("{0}", className);
		else html = html.replace("{0}", "AlertMessage");
		var st = document.body.scrollTop || document.documentElement.scrollTop;
		var sw = document.body.scrollLeft || document.documentElement.scrollLeft;
		newlayer.style.top = (st + get_wh() / 3) + 'px';
		newlayer.style.left = (sw + get_ww() / 8) + 'px';
		newlayer.style.width = get_ww() * 3 / 4 + 'px';
		html += "<div width=\"100%\" style=\"text-align:right;\"><a style=\"font-size: 14px; font-weight: bold; color: #f15d22;\" href=\"javascript:void(0);\" onclick=\"document.getElementById('divAlertMessage').style.display = 'none';\">X</a></div>";
		html += message;
		html += "<br>";
		html += "<p style='text-align: center;'><a style='font-weight: bold; text-decoration: underline; padding-top: 5px;' href='javascript:void(0);' onclick='document.getElementById(\"divAlertMessage\").style.display = \"none\"; showSelect();'>Закрыть</a></p>";
		html += '</td><td style="//background: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=/images/shadow_r.png, sizingmethod=crop);"></td></tr>';
		html += '<tr><td style="//background: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=/images/shadow_b.png, sizingmethod=crop);"></td>';
		html += '<td><img src="/images/blank.gif" align="top" alt="" style="height: 5px; width: 5px; border-width: 0px; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=/images/shadow_br.png, sizingmethod=scale);" /></td></tr></table>';
		newlayer.innerHTML = html;
		newlayer.style.display = "";
	}
}

function hideSelect()
{
    if (isIE) 
	{
		var arrSelect = document.getElementsByTagName("select");
		for(var i = 0; i < arrSelect.length; i++)
		{
			var element = arrSelect[i];
	        if (!isDefined(element.oldVisibility))
			{
	          element.oldVisibility = element.style.visibility ? element.style.visibility : "visible";
	          element.style.visibility = "hidden";
	        }
		};
    }
}

function showSelect()
{
	if (isIE)
	{
		var arrSelect = document.getElementsByTagName("select");
		for(var i = 0; i < arrSelect.length; i++)
		{
			var element = arrSelect[i];
			if (isDefined(element.oldVisibility))
			{
			// Why?? Ask IE
				try
				{
					element.style.visibility = element.oldVisibility;
				}
				catch(e)
				{
					element.style.visibility = "visible";
				}
				element.oldVisibility = null;
			}
			else
			{
				if (element.style.visibility)
					element.style.visibility = "visible";
			}
		};
	}
}

function getElementByAttribute(eTagName, eAtName, eEtValue)
{
	var arrInput = document.getElementsByTagName(eTagName);
	for(var i in arrInput)
		if(typeof arrInput[i].getAttribute != 'undefined')
			if (arrInput[i].getAttribute(eAtName) == eEtValue)
				return arrInput[i];
	return null;
}

function get_ww()
{
	var frameWidth=800;
	if (self.innerWidth)
		frameWidth = self.innerWidth;
	else if (document.documentElement && document.documentElement.clientWidth)
		frameWidth = document.documentElement.clientWidth;
	else if (document.body)
		frameWidth = document.body.clientWidth;
	return frameWidth;
}

function get_wh()
{
	var frameHeight=640;
	if (self.innerHeight)
		frameHeight = self.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight)
		frameHeight = document.documentElement.clientHeight;
	else if (document.body)
		frameHeight = document.body.clientHeight;
	return frameHeight;
}

function addServerControl(name, clientID, section)
{
	if(typeof serverControls == "undefined") serverControls = new Array();
	if(section)
	{
		if(!serverControls[section]) serverControls[section] = new Array();
		serverControls[section][name] =  clientID;
	}
	else
	{
		if(!serverControls.common) serverControls.common = new Array();
		serverControls.common[name] =  clientID;
	}
}

function getServerControl(name, section, onlyID)
{
	section = section? section: "common";
	if(serverControls && serverControls[section] && serverControls[section][name])
	{
		if(onlyID)
			return serverControls[section][name];
		else
			return document.getElementById(serverControls[section][name]);
	}
	else
	{
		return null;
	}
}

if(typeof $ == "undefined")
{
	$ = function(eID){return document.getElementById(eID);};
}

function loadingON()
{
	if($("loadind") == null) return;
    $("loadind").style.display = "block";
}

function loadingOFF()
{
	if($("loadind") == null) return;
	$("loadind").style.display = "none";
}

function elementVisibility(id)
{
	var el = $(id);
	
	if(el.style.display != "none")
		el.style.display = "none";
	else
		el.style.display = "";
}

var popupMenuArray = new Array();

function visibilityPopupMenu(id)
{
	var el = $(id);
	
	if(el.style.display != "none")
		hidePopupMenu();
	else
	{
		hidePopupMenu();
		showPopupMenu(id);
	}
}

var timeoutPopupMenu = null;

function showPopupMenu(id, btnId)
{
	//if(hidePopupMenuTimer) clearTimeout(hidePopupMenuTimer);
	if(timeoutPopupMenu != null)
	{
		clearTimeout(timeoutPopupMenu);
		timeoutPopupMenu = null;
	}
	
	if(popupMenuArray.length > 0 && popupMenuArray[popupMenuArray.length - 1] != id)
	{
		hidePopupMenuNow();
	}

	var el = $(id);
	
	if(!el)
		return;

	if(popupMenuArray.length == 0 || popupMenuArray[popupMenuArray.length - 1] != id)
	{
		el.style.display = "";
		
		if(el.getAttribute("popuptype") == "menu")
		{
			if(btnId)
			{
				var btn = $(btnId);
				btn.onmouseout = function(e)
				{
					hidePopupMenu();
				}
			}
			//$("MainMenu").innerHTML = left + " " + top;
			el.onmouseout = function(e)
			{
				var clientX = event.clientX;
				var clientY = event.clientY;
				var obj = this.getBoundingClientRect();
				var left = obj.left;
				var top = obj.top;
				//$("MainMenu").innerHTML = clientX + " " + divX;
				if(clientX < (left + 5) || clientX > (left - 5 + this.offsetWidth) || clientY < (top + 5) || clientY > (top - 5 + this.offsetHeight))
					hidePopupMenu();
			}
			el.onmouseover = function(e)
			{
				showPopupMenu(id);
			}
			el.onclick = function(e)
			{
				hidePopupMenu();
			}
		}
		else
		{
			setDivPosition(id);
		}
	
		popupMenuArray.push(id);
	}
}

//var hidePopupMenuTimer = null;

function hidePopupMenu()
{
	//alert(0);
	timeoutPopupMenu = setTimeout("hidePopupMenuNow()", 500);
}

function hidePopupMenuNow()
{
	/*if(delay)
	{
		hidePopupMenuTimer = setTimeout("hidePopupMenu()", 500);
		return;
	}*/
	
	while(popupMenuArray.length)
	{
		var elID =popupMenuArray.pop();
		$(elID).style.display = "none";
	}
}

function scrollToElement(elId)
{
	var el = document.getElementById(elId);
	
	var parEl = el.parentNode;
	
	var mark = document.createElement("a");
	mark.name = "elId";
	
	parEl.appendChild(mark);
	
	//alert(0);
	location.href = "#" + elId;

/*	var scrollY = 0;
	while(par && par.getAttribute("markname") != markname)
	{	
			scrollY += par.offsetTop;
			par = par.offsetParent;
	}
	
	alert(scrollY);
	
	if(par)
	{
		var divs = par.getElementsByTagName("div");
		for(var i = 0; i < divs.length; i++)
		{
			var div = divs[i];
			if(div.getAttribute("markname") == markname)
			{
				alert(0);
				div.scrollTop = scrollY;
				return;
			}
		}
	}*/
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//showContextMenu
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var hideContextMenuTimeout = null;

function showContextMenu(e, params, className) {
	clearTimeout(hideContextMenuTimeout);

	if(!e) e = event; 
	var x = e.clientX;
	var y = e.clientY;
	var popupDiv = $("popupShowContextMenu");
	var imgDiv = $("popupShowContextMenuArrow");
	if(!popupDiv) 
	{
		popupDiv = document.createElement("div");
		popupDiv.id = "popupShowContextMenu"
		popupDiv.className = className ? className : "popupShowContextMenu";
		popupDiv.style.position = "absolute";
		popupDiv.onmouseout = hideContextMenu;
		document.getElementsByTagName("form")[0].appendChild(popupDiv);
		
		imgDiv = document.createElement("div");
		imgDiv.className = className ? className + "Arrow" : "popupShowContextMenuArrow";
		imgDiv.id = "popupShowContextMenuArrow"
		imgDiv.style.position = "absolute";
		imgDiv.onmouseout = hideContextMenu;
		imgDiv.onmouseover = function(){clearTimeout(hideContextMenuTimeout)};
		document.getElementsByTagName("form")[0].appendChild(imgDiv);
	}
	else
	{
		if((popupDiv.style.left == (x + "px"))&&(popupDiv.style.display == "block")) return;
	}
	while (popupDiv.childNodes.length > 0)
        popupDiv.removeChild(popupDiv.childNodes[0]); 
		
	var tempF = function(item)
				{
					return function()
							{
								imgDiv.style.display = 'none';
							    popupDiv.style.display = 'none';
							    item.f();
							}
				};
    for(var i = 0; i < params.length; i++)
    {
        var item = params[i];
	    var element = CreateLink(item.name, item.icon);
	    element.onclick = tempF(item);
		element.onmouseout = hideContextMenu;
		element.onmouseover = function(){clearTimeout(hideContextMenuTimeout)};
       	popupDiv.appendChild(element);
		element = document.createElement("br");
		popupDiv.appendChild(element);
    }
	st=document.body.scrollTop || document.documentElement.scrollTop;
	popupDiv.style.top = st+y + 19;
	popupDiv.style.left = x;
	popupDiv.style.display = "block";

	imgDiv.style.top = st+y;//parseInt(imgDiv.currentStyle.height.replace("px", ""));
	imgDiv.style.left = x
	imgDiv.style.display = "block";
}

function hideContextMenu()
{
	clearTimeout(hideContextMenuTimeout);
	hideContextMenuTimeout = setTimeout("hideNowContextMenu()", 500);
}

function hideNowContextMenu()
{
	var popupDiv = $("popupShowContextMenu");
	var imgDiv = $("popupShowContextMenuArrow");
	if(popupDiv) 
	{
		popupDiv.style.display = "none";
		imgDiv.style.display = "none";
	}
}

function CreateLink(text, imgsrc)
{
	var element = document.createElement("a");
	element.className = "CommandButton";
	element.setAttribute("href", "javascript:void(0);");
	element.innerHTML = text;
	if(imgsrc)
	{
		element.innerHTML = "<img src='" + imgsrc + "' style='border: 0px none ; margin: 0px; padding: 0 5px 0 0; vertical-align: middle;'/>" + text;
	}
	return element;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// setDivPosition()
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function setDivPosition(id)
{
	var el = $(id);
	var pageSize = PopupWindow.getPageSize();
	Sys.Debug.trace(el.offsetWidth + " " + el.offsetHeight);
	el.style.left = Math.round((pageSize.windowWidth - el.offsetWidth) / 2) + "px";
	el.style.top = Math.round((pageSize.windowHeight - el.offsetHeight) / 2) + "px";
}

//////////////////////////////////////////////////
// Scroll divs
/////////////////////////////////////////////////
function setScrolls(contaner)
{
	contaner = getContainer(contaner);

	var divs = contaner.getElementsByTagName("div");

	var tf = function(div)
	{
		div.style.height = "1px";
		Sys.Application.add_load(function(){setHeight(div)});
	};
	
	for(var i = 0; i < divs.length; i++)
	{
		if(divs[i].getAttribute("resizable") == "1")
		{
			if(isIE)
			{
				divs[i].style.height = "100%";
			}
			else
			{
				tf(divs[i]);
			}
		}
	}
}

function getContainer(contaner)
{
	contaner = contaner? contaner: document;
	if(typeof contaner == "string")
		contaner = $(contaner);
	
	return contaner;
}

function setScroll(div)
{
	if(typeof div == "string")
		div = $(div);
		
	if(isIE)
	{
		div.style.height = "100%";
	}
	else
	{
		div.style.height = "1px";
		Sys.Application.add_load(function(){setHeight(div)});
	}
}

function setHeight(el, height)
{
	height = height? height: el.parentNode.offsetHeight;
	el.style.height = (height - 2) + "px";
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Move Popups
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function MoveObject()
{
}

MoveObject.mouseDown = function(evt, id)
{
 var id = id;

 var popup = $(id);
 
 var left = parseInt(popup.style.left.replace("px", ""))
 var top = parseInt(popup.style.top.replace("px", ""))
 if(isNaN(left))
 {
  left = evt.clientX;
  popup.style.left = left + "px"
 }
 if(isNaN(top))
 {
  top = evt.clientY;
  popup.style.top = top + "px"
 }
 var location = {x: left, y: top};
 
 MoveObject.moveId = id;
 MoveObject.startX = evt.clientX;
 MoveObject.startY = evt.clientY;
 MoveObject.startPX = location.x;
 MoveObject.startPY = location.y;
 MoveObject.movemode = true;

 $addHandler(document, "mousemove", MoveObject.mouseMove);
 $addHandler(document, "mouseup", MoveObject.mouseUp);
}

MoveObject.mouseMove = function(evt)
{
 if(!MoveObject.movemode) return;

 if(document.selection && document.selection.empty) document.selection.empty();
 
 var x = evt.clientX;
 var y = evt.clientY;

 //$(PopupWindow.moveId + "content").innerHTML = (x) + " " + (y);

 if(x < 0) return;
 if(y < 0) return;
 
 var popup = $(MoveObject.moveId);
 
 var left = parseInt(popup.style.left.replace("px", ""))
 var top = parseInt(popup.style.top.replace("px", ""))
 var location = {x: left, y: top};

 var dx = x - MoveObject.startX;
 var dy = y - MoveObject.startY;

 var newX = location.x + dx;
 var newY = location.y + dy;
 //if(newX < 0) newX = 0;
 //if(newY < 0) newY = 0;

 MoveObject.startX = x;
 MoveObject.startY = y;

 //$(PopupWindow.moveId + "content").innerHTML = (left) + " " + (location.x + dx) + " " + (top) + " " + (location.y + dy);
 
 popup.style.left = newX + "px";
 popup.style.top = newY + "px";
 //Sys.UI.DomElement.setLocation(popup, location.x + dx, location.y + dy);
 
}

MoveObject.mouseUp = function(evt, context)
{
 MoveObject.movemode = false;
 $removeHandler(document, "mousemove", MoveObject.mouseMove);
 $removeHandler(document, "mouseup", MoveObject.mouseUp);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Сlass fliping
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function setClassFliping(obj, class1, class2, t)
{
 if(typeof obj == "string") obj = $(obj);
 if(obj.classfliptimeout) clearTimeout(obj.classfliptimeout);
 obj.className = class1;
 obj.classfliptimeout = setTimeout(function(){setClassFliping(obj, class2, class1, t)}, t);
}

function option_default(options, pname, def) {
	if (options && typeof options[pname] != "undefined") return options[pname]; else return def;
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Breadcrumb
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var Breadcrumb = function(){}

Breadcrumb.onclick = function(obj)
{
	SearchControl.raiseevent("onclick");
}

Breadcrumb.set = function(items, options)
{

	var overrideRoot = option_default(options,	"overrideRoot", true);

	if(overrideRoot)
	{
		var last = $("bswebbreadcrumblast");	// Последняя страница в цепочке страниц
		var popups = last.getElementsByTagName("div");	// Ищем и удаляем попап для послденей страницы
		if(popups.length)
			last.removeChild(popups[0]);
		
		if(items.length)	// Заполняем попап для последней страницы
		{
			var popup = Breadcrumb._createPopup(items[0]);
			if(popup) last.appendChild(popup);
		}
	}
		
	var next = $("bswebbreadcrumbentry").nextSibling;	// Удяляем динамическую часть
	while(next)
	{
		var temp = next.nextSibling;
		$("bswebbreadcrumb").removeChild(next);
		next = temp;
	}
	
	for(var i = (overrideRoot? 1: 0); i < items.length; i++)
	{
		var item = items[i];
		var div = document.createElement("div");
		div.className = "stat";
		var separator = document.createElement("span");
		separator.innerHTML = Breadcrumb.separator;
		div.appendChild(separator);
		var link = document.createElement("a");
		div.appendChild(link);
		link.href = item.href;
		link.innerHTML = item.name;
		link.onmouseover = function(){Breadcrumb.showItems(this)};
		link.onclick = item.onclick;

		var popup = Breadcrumb._createPopup(items[i]);
		if(popup) div.appendChild(popup);

		$("bswebbreadcrumb").appendChild(div);
	}
}

Breadcrumb._createPopup = function(data)
{
	if(!data.items.length) return null;
	var div = document.createElement("div");
	div.className = "popup";
	div.style.visibility = "hidden";
	div.style.position = "absolute";
	div.style.left = "-1000px";
	div.style.top = "-1000px";
	var ul = document.createElement("ul");
	div.appendChild(ul);
	for(var i = 0; i < data.items.length; i++)
	{
		var li = document.createElement("li");
		ul.appendChild(li);
		var lnk = document.createElement("a");
		li.appendChild(lnk);
		if(isIE) lnk.style.width = "100%";
		lnk.innerHTML = data.items[i].name;
		lnk.href = data.items[i].href;
		lnk.onclick = data.items[i].onclick;
	}
	
	return div;
}

Breadcrumb.showItems = function(el)
{
	clearTimeout(el.breadcrumbtimeout);
	var bounds = getBounds(el);
	var div = getObjectNexByTagName(el, "div");
	if(div)
	{
		var size = PopupWindow.getPageSize();
		div.style.left = bounds.x + "px";
		div.style.top = (bounds.y + bounds.height) + "px";
		div.style.visibility = "";
		div.onmouseover = function(){clearTimeout(el.breadcrumbtimeout)};
		AddEventHandler(div, "mouseout", function(evt){Breadcrumb.hideItems(evt, el)});
	}
	if(typeof el.breadcrumbtimeout == "undefined")
	{
		el.breadcrumbtimeout = null;
		AddEventHandler(el, "mouseout", function(evt){Breadcrumb.hideItems(evt, el)});
	}
}

Breadcrumb.hideItems = function(evt, el)
{
	clearTimeout(el.breadcrumbtimeout);
	
	if(isIE)
	{
		var eventSubj=document.createEventObject();
		el.breadcrumbtimeout = setTimeout(function(){Breadcrumb.hideItemsNow(eventSubj, el)}, 200);
	}
	else
		el.breadcrumbtimeout = setTimeout(function(){Breadcrumb.hideItemsNow(evt, el)}, 200);
}

Breadcrumb.hideItemsNow = function(evt, el)
{
	var div = getObjectNexByTagName(el, "div");
	if(div)
	{
		var bounds = getBounds(div);
		if(evt.clientX < bounds.x + 5 || evt.clientX > bounds.x + bounds.width - 5 || evt.clientY < bounds.y + 5 || evt.clientY > bounds.y + bounds.height - 5)
		{
			div.style.left = "-1000px";
			div.style.top = "-1000px";
			div.style.visibility = "hidden";
		}
	}
}

Breadcrumb.events = {};

Breadcrumb.raiseevent = function(eventtype, param)
{
		if(typeof Breadcrumb.events[eventtype] != "undefined" && Breadcrumb.events[eventtype]) Breadcrumb.events[eventtype](param);
}

/* Get Bounds */

function getBounds(el)
{
	var pageX = 0;
	var pageY = 0;
	par = el;
	while(par)
	{	
			pageX += par.offsetLeft;
			pageY += par.offsetTop;
			par=par.offsetParent;
	}
	//pageX += document.body.scrollLeft || document.documentElement.scrollLeft;
	//pageY += document.body.scrollTop || document.documentElement.scrollTop;
	
	return{x: pageX, y: pageY, width: el.offsetWidth, height: el.offsetHeight};
}


/* DOM functions */

function getObjectParentByTagName(obj,tName)
{
	while (obj) {
		obj = obj.parentNode;
		if (obj.tagName.toLowerCase() == tName.toLowerCase()) return obj;
	}
	return;
}

function getObjectPreviousByTagName(obj,tName)
{
	obj = obj.previousSibling;
	while (obj) {
		if (obj.nodeType == 1 && obj.tagName.toLowerCase() == tName.toLowerCase()) return obj;
		obj = obj.previousSibling;
	}
	return;
}

function getObjectNexByTagName(obj,tName)
{
	obj = obj.nextSibling;
	while (obj) {
		if (obj.nodeType == 1 && obj.tagName.toLowerCase() == tName.toLowerCase()) return obj;
		obj = obj.nextSibling;
	}
	return;
}

function hasParent(obj, parent)
{
	while (obj) {
		if (obj.parentNode == parent) return true;
		obj = obj.parentNode;
	}
	return false;
}

function setClassOver(obj)
{
	if(typeof obj == "string") obj = $(obj);
	obj.setAttribute("outclass", obj.className)
	obj.onmouseover = _setClassOver;
	obj.onmouseout = _setClassOut;
}

function _setClassOut(){
	this.className = this.getAttribute("outclass")
}

function _setClassOver(){
	this.className = this.getAttribute("overclass")
}

function locationHref(targetUrl)
{
	if(document.all)
	{
		if(Controls.links.hidden)
		{
			Controls.links.hidden.href = targetUrl;
			setTimeout(function(){Controls.links.hidden.click()}, 1);
		}
	}
	else
		document.location.href = targetUrl;
}
function CancelBubbling(e)
{

if (!e)var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();

}
