﻿if(typeof WebForm_OnSubmitOriginal == 'undefined')
{
	if(typeof WebForm_OnSubmit == 'undefined')
		WebForm_OnSubmit = function(){return true;};

	if(typeof Sys != "undefined")
	{
		Sys.Application.add_load(function() {
			if(!document.forms[0].onsubmit) {
				document.forms[0].onsubmit = WebForm_OnSubmit;
			}
			
		});
	}

	WebForm_OnSubmitOriginal = WebForm_OnSubmit;

	x_OnSubmitFunctions = {};
	WebForm_OnSubmit = function()
	{
		var res = WebForm_OnSubmitOriginal();
		try {
			if(res) {
				for(var i in x_OnSubmitFunctions)
					x_OnSubmitFunctions[i]();
			}
		}
		catch(e) {
		}

		return res;
	}
}

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";

if(isIE)
{
	//document._getElementsByName = document.getElementsByName;
	document.getElementsByName = function(name){
		var temp = document.all;
		var matches = [];
		for(var i=0;i<temp.length;i++){
		  if(temp[i].name == name){
			matches.push(temp[i]);
		  }
		}
		return matches;
	};
}

function LTrim( value ) {
     var re = /\s*((\S+\s*)*)/;
     return value.replace(re, "$1");
}
function RTrim( value ) {
     var re = /((\s*\S+)*)\s*/;
     return value.replace(re, "$1");
}
function trim( value ) {
     return LTrim(RTrim(value));
}

function trunc(text, length)
{
	if(length && text.length > length)
		text = text.substring(0, length) + "...";
		
	return text;
}

if(typeof $ == "undefined")
{
	$ = function(id){
				return document.getElementById(id);
			}
}

function createId(prefix)
{
	prefix = prefix? prefix + "": "x_";
	return prefix + Math.round(Math.random() * 1000000000000000);
}

function createTimeout(id, f)
{
	if(!window.timeoutfunctions) window.timeoutfunctions = {};
	window.timeoutfunctions[id] = f;
}

function callTimeout(id, delay, param)
{
	if(window.timeoutfunctions[id])
	{
		setTimeout("window.timeoutfunctions['" + id + "'](" + param + ")", delay);
	}
}
	
var Ajax = function(){};

Ajax.Request = function(url, options)
{
	var method = options.method? options.method.toUpperCase(): "POST";
	var onSuccess = options.onSuccess? options.onSuccess: options.onComplete;
	
	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";
	//UserGuid сейчас нужен только для RealtyMind
	if($("hdnUserGuid"))
		request.get_headers()["X_UserGuid"] = $("hdnUserGuid").value;
	request.set_timeout(90000);
	if(onSuccess) request.add_completed(onSuccess);
	request.invoke();
}

Ajax.Updater = function(updateId, url, options)
{
	var onSuccess = options.onSuccess? options.onSuccess: options.onComplete;
	var context = {updateId: updateId, onComplete: onSuccess};
	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";
	if($("hdnUserGuid"))
		request.get_headers()["X_UserGuid"] = $("hdnUserGuid").value;
	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);
}

var Accordion = new function()
{
	this.controls = [];
	//var me = this;
	//if(!isIE) Sys.Application.add_load(function(){me.onLoad()});
}

Accordion.onLoad = function()
{
	var me = this;
	$addHandler(window, "resize", function(){me.onresizeWindow()});	
}

Accordion.onresizeWindow = function()
{
	this.updateSize();
}

Accordion.updateSize = function(id)
{
	var sroolls = [];

	for(var j = 0; j < this.controls.length; j++)
	{
		if(id && this.controls[j] != id) continue
		
		var el = $(this.controls[j]);
		
		/*var rows = el.tBodies[0].rows;

		var cell;
		
		for(var i = 0; i < rows.length; i += 2)
		{
			cell = rows[i+1].cells[0];
			if(rows[i].cells[0].getAttribute("hidden") != "1" && rows[i+1].style.display != "none") break;
		}

		var divs = cell.getElementsByTagName("div");*/
		var divs = el.getElementsByTagName("div");
		
		for(var i = 0; i < divs.length; i++)
		{
			var div = divs[i];
			if(div.style.height == "100%" || div.getAttribute("resizable") == "1")
			{
				div.setAttribute("resizable", "1");
				sroolls.push(div);
				div.style.height = "1px";
			}
		}
	}
	
	for(var i = 0; i < sroolls.length; i++)
	{
		var div = sroolls[i];
		if(!isIE)
		{
			var tempF = function(obj){return function(){Accordion.setHeight(obj)}};
			setTimeout(tempF(div), 100);
		}
		else
		{
			div.style.height = "100%";
		}
	}
}

Accordion.create = function(id, tabclass, activetabclass, contentclass, params)
{
	var el = $(id);
	
	el.setAttribute("tabclass", tabclass);
	el.setAttribute("activetabclass", activetabclass);
	el.setAttribute("contentclass", contentclass);
	
	function param_default(pname, def) { if (params && typeof params[pname] != "undefined") return params[pname]; else return def; };
	
	var startState = param_default("startState", 0);
	var bOpenAll = (startState == 1);
	
	var rows = el.tBodies[0].rows;

	for(var i = 0; i < rows.length; i += 2)
	{
		var tdh = rows[i].cells[0];
		var tdc = rows[i+1].cells[0];
		
		tdh.className = el.getAttribute("tabclass");
		//tdc.style.display = "none";
			
		var tempF = function(tab)
					{
					    $addHandler(tdh, "click", function(){Accordion.changeTab(id, tab)});
					}(i);

		tdc.className = el.getAttribute("contentclass");
		tdc.style.width = "100%";
		tdc.setAttribute("tdcheight", tdc.style.height);
		if(!bOpenAll) tdc.style.height = "100%";
		//tdc.style.display = "none";
		if(!bOpenAll) rows[i+1].style.display = "none";
	}
	
	//el.tBodies[0].rows[0].cells[0].className = el.getAttribute("activetabclass");
	//el.tBodies[0].rows[1].cells[0].style.display = "";
	this.controls.push(id)

	if(!bOpenAll)
		this.changeTab(id, 0);
	else
		this.updateSize(id);
		
}

Accordion.reset = function(id)
{
	var el = $(id);
	
	var rows = el.tBodies[0].rows;

	for(var i = 0; i < rows.length; i += 2)
	{
		var tdh = rows[i].cells[0];
		var tdc = rows[i+1].cells[0];
		
		tdh.className = el.getAttribute("tabclass");
		tdc.className = el.getAttribute("contentclass");
		tdc.style.height = tdc.getAttribute("tdcheight");
		rows[i+1].style.display = "";
	}
	this.updateSize(id);
}

Accordion.hideTab = function(id, hid)
{
	var el = $(id);
	var rows = el.tBodies[0].rows;

	for(var i = 0; i < rows.length; i += 2)
	{
		var tdh = rows[i].cells[0];
		if(tdh.id == hid)
		{
			rows[i].style.display = "none";
			rows[i+1].style.display = "none";
			rows[i].cells[0].setAttribute("hidden", "1");
			if(tdh.className == el.getAttribute("activetabclass"))
				Accordion.changeTab(id)
			return;
		}
	}
}

Accordion.showTab = function(id, hid)
{
	var el = $(id);
	var rows = el.tBodies[0].rows;

	for(var i = 0; i < rows.length; i += 2)
	{
		var tdh = rows[i].cells[0];
		if(tdh.id == hid)
		{
			rows[i].style.display = "";
			rows[i+1].style.display = "";
			rows[i].cells[0].setAttribute("hidden", "0");
			return;
		}
	}
}

Accordion.changeTab = function(id, tab)
{
	var el = $(id);
	
	var rows = el.tBodies[0].rows;

	for(var i = 0; i < rows.length; i += 2)
	{
		var tdh = rows[i].cells[0];
		var tdc = rows[i+1].cells[0];
		
		tdh.className = el.getAttribute("tabclass");
		//tdc.style.display = "none";
		rows[i+1].style.display = "none";
	}

	if(tab != null)
	{
		if(typeof tab == "number")
		{
			el.tBodies[0].rows[tab].cells[0].className = el.getAttribute("activetabclass");
			//el.tBodies[0].rows[tab+1].cells[0].style.display = "";
		}
		else
		{
			for(var i = 0; i < rows.length; i += 2)
			{
				var tdh = rows[i].cells[0];
				if(tdh.id == tab)
				{
					rows[i].cells[0].className = el.getAttribute("activetabclass");
					//rows[i+1].cells[0].style.display = "";
					tab = i;
					break;
				}
			}
		}
	}
	else
	{
		for(var i = 0; i < rows.length; i += 2)
		{
			if(rows[i].cells[0].getAttribute("hidden") != "1")
			{
				rows[i].cells[0].className = el.getAttribute("activetabclass");
				//rows[i+1].cells[0].style.display = "";
				tab = i;
				break;
			}
		}
	}
	rows[tab+1].style.display = "";

	/*if(isIE)
	{
		return;
	}*/
	
	/*var cell = el.tBodies[0].rows[tab+1].cells[0];
	
	var divs = cell.getElementsByTagName("div");
	var sroolls = [];
	
	for(var i = 0; i < divs.length; i++)
	{
		var div = divs[i];
		if(div.style.height == "100%" || div.getAttribute("resizable") == "1")
		{
			div.setAttribute("resizable", "1");
			sroolls.push(div);
			div.style.height = "1px";
		}
	}

	for(var i = 0; i < sroolls.length; i++)
	{
		var div = sroolls[i];
		setTimeout("Accordion.setHeight('" + div.id + "');", 100);
		//div.style.height = div.parentNode.offsetHeight + "px";
	}*/
	Accordion.updateSize(id);
	
	//var innerHTML = el.innerHTML;
	//el.innerHTML = innerHTML;
}

Accordion.setHeight = function(el)
{
	el.style.height = (el.parentNode.offsetHeight - 2) + "px";
}

function DownList()
{
}

DownList.current = null;
DownList.data = {};
DownList.params = {};
DownList.callbackfunctions = {};
DownList.id = "tblDownListList";

DownList.init = function(id, data, callbackfunction, params)
{
	params = params? params: {};
	
	var el = $(id);
	
	DownList.data[id] = data;
	DownList.params[id] = params;
	DownList.callbackfunctions[id] = callbackfunction;

	el.onmouseover = function(){DownList.show(id)};
	
	//el.onmouseover = function(){if(this.className != "DownList_ButtonHover") this.className = "DownList_ButtonHover";};
	//el.onmouseout = function(){if(this.className != "DownList_Button") this.className = "DownList_Button";};
	
	if(params.isShowChecked)
		DownList.showChecked(id)
}

DownList.show = function(id)
{
	clearTimeout(DownList.timeoutDownList);
	
	var listID = DownList.id;
	
	DownList.current = listID;
	
	var table = $(listID);
	if(table == null)
	{
		var table = document.createElement("table");
		table.id = listID;
		table.cellPadding = 0;
		table.cellSpacing = 0;
		table.className = "DownListTable";
		table.onmouseout = function(){DownList.hide()};
		//table.style.position = "absolute";
	}
	
	
	var data = DownList.data[id];
	var params = DownList.params[id];
	
	while(table.rows.length) table.deleteRow(0);
	
	var tempF = function(value)
		{
			return function(){DownList.hideNow(); DownList.callbackfunctions[id](value);}
		}
	for(var i = 0; i < data.length; i++)
	{
		if(data[i].hidden) continue;
		var row = table.insertRow(-1)
		var cell = row.insertCell(-1);
		var cell = row.insertCell(-1);
		if(data[i].disabled)
		{
			cell.className = "DownListDisabledItem";
			cell.onmouseover = function(){clearTimeout(DownList.timeoutDownList);};
		}
		else
		{
			cell.className = "DownListItem";
			//cell.setAttribute("v", data[i].v);
			cell.onmouseover = function(){clearTimeout(DownList.timeoutDownList); this.className = "DownListSelectedItem"};
			cell.onmouseout = function(){this.className = "DownListItem"};
			cell.onclick = tempF(data[i].v);
		}
		if(data[i].checked)
			cell.innerHTML = "<img src='/media/checked.gif' align='bottom'/>&nbsp;";
		else
			cell.innerHTML = "&nbsp;&nbsp;&nbsp;"
		cell.innerHTML += data[i].n;
	}
	
	var el = $(id);
	el.onmouseout = function(){/*this.className = "DownList_Button";*/ DownList.hide()};
	
	/*if(typeof noDivScroll != "undefined" && noDivScroll)
	{
		var pageY = 0;
		var pageX = 0;
		par = textEl;
		while(par)
		{	
				pageY += par.offsetTop;
				pageX += par.offsetLeft;
				par=par.offsetParent;
		}
		pageY += document.getElementById(comboBoxData[BoxID].txtName).offsetHeight;
		boxList.style.left =pageX;
		boxList.style.top = pageY;
	}
	else
	{*/
		var parentEl = el.parentNode;
		//alert(parentEl.tagName);
		parentEl.insertBefore(table, el);
		table.style.marginTop = el.offsetHeight;
		if(params.marginLeft)
			table.style.marginLeft = params.marginLeft;
		//if(!isIE) table.style.marginLeft = el.offsetLeft;
	//}

	table.style.display = "";
}

DownList.hide = function()
{
	clearTimeout(DownList.timeoutDownList);
	DownList.timeoutDownList = setTimeout("DownList.hideNow()", 500)
}

DownList.hideNow = function()
{
	var listID = DownList.id;
	var table = $(listID);
	if(table) 
		table.style.display = "none";
}

DownList.getChecked = function(id)
{
	var data = DownList.data[id];

	for(var i = 0; i < data.length; i++)
		if(data[i].checked) return data[i].v;
		
	return null;
}

DownList.setChecked = function(id, v)
{
	var data = DownList.data[id];

	for(var i = 0; i < data.length; i++)
		if(data[i].v == v)
			data[i].checked = true;
		else
			data[i].checked = false;
	
	var params = DownList.params[id];
	
	if(params.isShowChecked)
		DownList.showChecked(id)
}

DownList.showChecked = function(id)
{
	var data = DownList.data[id];

	for(var i = 0; i < data.length; i++)
		if(data[i].checked)
		{
			var parent = $(id).parentNode;
			var el = parent.getElementsByTagName("dlstteg")
			if(el.length == 0)
			{
				el = document.createElement("dlstteg");
				parent.appendChild(el);
			}
			else
				el = el[0];
			el.innerHTML = data[i].n;
		}
	
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function DropList()
{
}

DropList.data = {};
DropList.callbackfunction = {};
DropList.timeout = null;
DropList.el = null;

/*DropList.init = function(el, data, callbackfunction)
{
	var el = $(id);
	
	DropList.data = data;
	DownList.callbackfunction = callbackfunction;

	el.onmouseout = DropList.hide;
	
	//el.onmouseover = function(){if(this.className != "DownList_ButtonHover") this.className = "DownList_ButtonHover";};
	//el.onmouseout = function(){if(this.className != "DownList_Button") this.className = "DownList_Button";};
	
	if(params.isShowChecked)
		DownList.showChecked(id)
}*/

DropList.getList = function()
{
	return document.getElementById("drpDropList");
}

DropList.show = function(el, data, callbackfunction)
{
	DropList.clearTimeout();
	
	var list = DropList.getList();
	if(list == null)
	{
		list = document.createElement("select");
		list.id = "drpDropList";
		list.style.position = "absolute";
		list.style.zIndex = 255;
		list.multiple = true;
		list.onmouseover = DropList.clearTimeout;
		list.onmouseout = DropList.hide;
		//list.ondblclick = comboBoxListSelected;
		document.getElementsByTagName("form")[0].appendChild(list);
	}
	if(DropList.el != el)
	{
		//var parentEl = el.parentNode;
		//parentEl.insertBefore(list, el);
		//el.insertBefore(list, el.firstChild);
		//list.style.marginTop = el.offsetHeight;
		var bounds = Sys.UI.DomElement.getBounds(el);
		list.style.left = bounds.x + "px";
		list.style.top = (bounds.y + el.offsetHeight) + "px";
		list.onchange = function(){callbackfunction(getSelectedValue(this)); DropList.hideNow()};
		el.onmouseout = DropList.hide;
		DropList.hideNow();
		
		var options = list.options;
		options.length = 0;
		for(var i = 0; i < data.length; i++)
		{
			options[options.length] = new Option(data[i].name, data[i].value, false, false);
		}
	}
	if(data.length)
		list.style.display = "";

}

DropList.clearTimeout = function()
{
	if(DropList.timeout != null)
	{
		clearTimeout(DropList.timeout);
		DropList.timeout = null;
	}
}

DropList.hide = function()
{
	clearTimeout(DropList.timeout);
	DropList.timeout = setTimeout("DropList.hideNow()", 500)
}

DropList.hideNow = function()
{
	var list = DropList.getList();
	list.style.display = "none";
}



function restoreValues(values, prefix, content, bWithHiddens)
{
	//content = content? $(content): document;
	content = document;

	if (typeof values == "string")
		eval("var arrValues = " + values);
	else
		var arrValues = values;

	for (var k in arrValues)
	{
		var id = prefix? prefix + k: k;
		var el = content.getElementById(id);
		var value = decodeURIComponent(arrValues[k]);
		if (el)
		{
			switch (el.type)
			{
				case "text":
				case "textarea":
				case "select-one":
					el.value = value;
					el.value = value;
					break;

				case "hidden":
					if(bWithHiddens) el.value = value;
					break;
				
				case "radio":
				case "checkbox":
					el.checked = (value == "1" || value == "true");
					break;
				
				//default:
					//el.style.display = arrValues[k] == "" ? "": "none";
				default:
					if(typeof el.src != "undefined")
						el.src = value;
					else if(typeof el.innerHTML != "undefined")
						el.innerHTML = value;
			}
		}
		//Для радиобаттонов
		var els = content.getElementsByName(id)
		if (els.length)
			for(var i = 0; i < els.length; i++)
			{
				el = els[i];
				if(el.value == value)
					el.checked = true;
			}
	}
}

function collectValues(prefix, content, tfValues)
{
	var docXml = (new DOMParser()).parseFromString("<values></values>", "text/xml");

	content = content? $(content): document;

	var tfValues = tfValues? tfValues: ["1", "0"];
	var trueValue = tfValues[0];
	var falseValues = tfValues[1];
	
	var arr = content.getElementsByTagName("input");
	
	for (var i = 0; i < arr.length; i++)
	{
		if(!arr[i].id || prefix && arr[i].id.indexOf(prefix) == -1 && (!arr[i].name || arr[i].name.indexOf(prefix) == -1)) continue;

		var id = prefix? arr[i].id.replace(prefix, ""): arr[i].id;
		var value;
		switch(arr[i].type)
		{
			case "checkbox":
				value = arr[i].checked? trueValue: falseValues;
				break;
			case "radio":
				if(arr[i].value != "on")
				{
					if(arr[i].checked)
					{
						value = arr[i].value;
						id = prefix? arr[i].name.replace(prefix, ""): arr[i].name;;
					}
					else continue;
				}
				else
				{
					value = arr[i].checked? trueValue: falseValues;
				}
				break;
			default:
				value = arr[i].value;
		}

		var ele = docXml.createElement(id); 
		docXml.documentElement.appendChild(ele);
		Sarissa.setText(ele, value)
	}

	arr = content.getElementsByTagName("textarea");
	for (var i = 0; i < arr.length; i++)
	{	
		if(!arr[i].id || prefix && arr[i].id.indexOf(prefix) == -1) continue;

		var id = prefix? arr[i].id.replace(prefix, ""): arr[i].id;
		var value = arr[i].value;

		var ele = docXml.createElement(id); 
		docXml.documentElement.appendChild(ele);
		Sarissa.setText(ele, Sarissa.escape(value))
	}

	arr = content.getElementsByTagName("select");
	for (var i = 0; i < arr.length; i++)
	{	
		if(!arr[i].id || prefix && arr[i].id.indexOf(prefix) == -1) continue;

		var id = prefix? arr[i].id.replace(prefix, ""): arr[i].id;
		var value = arr[i].value;

		var ele = docXml.createElement(id); 
		docXml.documentElement.appendChild(ele);
		Sarissa.setText(ele, Sarissa.escape(value))
	}
	
	return new XMLSerializer().serializeToString(docXml);
}

function decodeValues(values)
{
	for(var i in values)
		values[i] = decodeURIComponent(values[i]);
}
/* Enter Handle*/
var eventKey;

 function registerSubmitHandlers() {
   if ( typeof(autoSubmitNames)!="undefined" ) {
     for( i = 0; i<autoSubmitNames.length; i++ ) {
       var ob = document.getElementById(autoSubmitNames[i]);
       if ( ob!=null )
         ob.onkeydown = doSubmit;
     }
     if ( !document.all ) {
       eventKey = "e.keyCode";
       document.captureEvents(Event.KeyDown);
     }
     else
       eventKey = "event.keyCode";
   }
 }

 function doLinkSubmit(linkID) {
	if(typeof $(linkID).onclick == "function")
		$(linkID).onclick();
	if ( document.all )
		document.getElementById(linkID).click();
	else
		document.location.href = document.getElementById(linkID).href;
 }

 function doSubmit(e) {
   if ( eval(eventKey)==13 ) {
     for( i=0; i<autoSubmitNames.length; i++ ) {
       if ( autoSubmitNames[i]==this.id ) {
         eval(autoSubmit[i]);
         return false;
       }
     }
   }
 }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Validation 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var intErrorBorderWidth = 2;
var errorElement;
var blnValidationMessageDisplayed = false;

function showValidationMessage(objElement,strMessage)
{
	blnValidationMessageDisplayed = true;
	showBorder(objElement, strMessage);
	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");
	
	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 = "Please select correct value";
	
	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"))
		{
			//Дополнительная проверка на корректность расстановки запятых
			var reg = /^(\d+(,\d{3})*)?$/;
			if (!reg.test(tempValue)) return strMessage;
			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)
    {
		if(comExpression != "")
		{
	        hideValidationMessage(objElem);
	        hideValidationMessage(comElem);
	        var tempValue = objElem.value;
	        var comValue = comElem.value;
	        if(objElem.getAttribute("empty-value") == tempValue) tempValue = "";
	        if(comElem.getAttribute("empty-value") == comValue) comValue = "";
	        if(objElem.getAttribute("money")) tempValue = tempValue.replace(/,/g, "");
	        if(comElem.getAttribute("money")) comValue = comValue.replace(/,/g, "");
	        /*if(objElem.getAttribute("compare-addvalue"))
			{
				tempValue += objElem.getAttribute("compare-addvalue");
				comValue += objElem.getAttribute("compare-addvalue");
			}*/
	        tempValue = parseFloat(tempValue);
	        comValue = parseFloat(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;
	        }
		}
		else
		{
			return compareValues(comElem);
		}
    }
    return true;
}
function validate(objElement)
{
	//alert("blur_" + objElement.id);
	var strResult = "";
	//alert(blnValidationMessageDisplayed);
	//if (!blnValidationMessageDisplayed)
	{
		strResult = getValidationResultMessage(objElement);
		//alert(strResult);
		if (!strResult == "") 
		{
			showValidationMessage(objElement, strResult);
		}
	}
	return strResult;
}


function validateForm(container)
{
	var strResult = "";
	blnValidationMessageDisplayed = false;
	var arrElements = getValidationElementsArray(container);
	for (var i = 0; i < arrElements.length; i++) 
	{
        if(arrElements[i].offsetHeight == 0 || arrElements[i].disabled) continue;
		strResult = validate(arrElements[i]);
		if (blnValidationMessageDisplayed) return strResult;
	}
	return strResult;
}

function getValidationElementsArray(container)
{
	var container = container? $(container): document;
	var arrResult = new Array();
	var arrElements = [];
	arrElements.push(container.getElementsByTagName("input"));
	arrElements.push(container.getElementsByTagName("select"));
	arrElements.push(container.getElementsByTagName("textarea"));
	arrElements.push(container.getElementsByTagName("div"));
	for (var i = 0; i < arrElements.length; i++) 
	{
		var arr = arrElements[i];
		for(var j = 0; j < arr.length; j++)
		{
			var objValidationNode = arr[j].getAttribute("validation");
			if (objValidationNode == "1") 
			{
				arrResult.push(arr[j]);
			}
		}
	}
	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 = 60;
		//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, message)
{

	/*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 = "";*/
	
	var erDiv = $("validation_erDiv");
	var erSpan;
	if(!erDiv)
	{
		erSpan = document.createElement("span");
		erSpan.style.position = "absolute";
		erDiv = document.createElement("div");
		erDiv.id = "validation_erDiv";
		erDiv.className = "validation_erDiv";
		erSpan.appendChild(erDiv);
		//erDiv.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;";
	}
	erSpan = erDiv.parentNode;
	
	var parentEl = objElement.parentNode;
	parentEl.insertBefore(erSpan, objElement);
	
	var offTop = parseInt(objElement.style.marginTop);
	var offLeft = parseInt(objElement.style.marginLeft);
	offTop = isNaN(offTop)? 0: offTop;
	offLeft = isNaN(offLeft)? 0: offLeft;

	var offHeight = objElement.offsetHeight;
	if(objElement.tagName == "DIV")
	{
		offHeight = objElement.parentNode.offsetHeight;
	}
	
	//erDiv.style.paddingLeft = objElement.offsetWidth / 2 - 10 + "px";
	if(isIE)
	{
		erDiv.style.width = (objElement.offsetWidth + 3) + "px";
		erDiv.style.height = (offHeight + 3) + "px";
		erDiv.style.marginLeft = (offLeft - 2) + "px";
		erDiv.style.marginTop = (offTop - 1) + "px";
	}
	else
	{
		erDiv.style.width = (objElement.offsetWidth - 1) + "px";
		erDiv.style.height = (offHeight - 1) + "px";
		erDiv.style.marginLeft = (offLeft - 2) + "px";
		erDiv.style.marginTop = (offTop - 2) + "px";
	}
	erDiv.onclick = function(){hideValidationMessage(document); objElement.focus()};
	erDiv.title = message;
	
	erSpan.style.display = "";

	vld_obj = objElement;
	//vld_flashOn();
}

var vld_timeout;
var vld_obj;

function vld_flashOn()
{
	//if(isIE) return;
	clearTimeout(vld_timeout);

	var erDiv = $("validation_erDiv");
	var parentEl = vld_obj.parentNode;
	parentEl.insertBefore(erDiv, vld_obj);
	
	/*if(erDiv.style.display != "none")
		erDiv.style.display = "none";
	else
		erDiv.style.display = "";*/

	/*if(erDiv.innerHTML != "&nbsp;&nbsp;&nbsp;&nbsp;")
		erDiv.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;";
	else
		erDiv.innerHTML = "&nbsp;!!!";*/
		
	vld_timeout = setTimeout("vld_flashOn()", 500);
}

function vld_flashOff()
{
	//if(isIE) return;
	clearTimeout(vld_timeout);
}

function hideBorder()
{
	/*getBorderDiv("brdLeft").style.display = "none";
    getBorderDiv("brdRight").style.display = "none";
	getBorderDiv("brdTop").style.display = "none";
	getBorderDiv("brdBottom").style.display = "none";*/
	//vld_flashOff();
	var erDiv = $("validation_erDiv");
	if(erDiv)
	{
		erDiv.parentNode.style.display = "none";
	}
}

function doElementOnFocus()
{
	hideValidationMessage(this);
}

function doElementOnBlur()
{
	validate(this);
}

function attachValidationEventsToElement(objElement)
{
	if(objElement.onfocus == null) objElement.onfocus = doElementOnFocus;
	if(objElement.onblur == null) objElement.onblur = doElementOnBlur;
}

function attachEventsToElements(container)
{
	var arrElements = getValidationElementsArray(container)
	for (var i = 0; i < arrElements.length; i++) 
	{
		attachValidationEventsToElement(arrElements[i]);
	}
}

function attachValidationEventsToElements(container)
{
	attachEventsToElements(container);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Indication 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//loading gif function
function loadingON(nolock){
	//nolock = true;
	Controls.loading.i++;

    $("loading").style.display='block'
	
	//st = document.body.scrollTop || document.documentElement.scrollTop;
	
	//$("loading").style.left = (screen.availWidth - $("loading").style.offsetWidth) / 2 + 'px';
	//$("loading").style.top = (st + (screen.availHeight - $("loading").style.offsetHeight) / 2) + 'px';

	//if (!window.loading) window.loading = 0;
	//window.loading += 1;
	var pageSize = PopupWindow.getPageSize();
	
	var top =pageSize.windowHeight / 2;
	top += pageSize.yScroll;
	var left = pageSize.windowWidth / 2;

	$("loading").style.left = left - 107 + 'px';
	$("loading").style.top = top + 'px';

	//alert($("loading").style.left + ";" + $("loading").style.top);
	if(!nolock){
        PopupWindow.disableScreen();
		Controls.loading.isLock = true;
    }
}
function loadingOFF(nolock){
	//nolock = true;
	Controls.loading.i--;

	if(nolock && Controls.loading.isLock)
			return;
	if(!nolock){
		Controls.loading.isLock = false;
        PopupWindow.enableScreen();
	}
	
	if(Controls.loading.i < 0) Controls.loading.i = 0;
	if(!Controls.loading.i)
		$("loading").style.display='none';
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//select. add option
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function addOption (oListbox, text, value, isDefaultSelected, isSelected)
{
	for(var i = 0; i < oListbox.options.length; i++)
		if(oListbox.options[i].value == value)
		{
			oListbox.value = value;
			return;
		}

	var oOption = document.createElement("option");
	oOption.appendChild(document.createTextNode(text));
	oOption.setAttribute("value", value);

	if (isDefaultSelected) oOption.defaultSelected = true;
	if (isSelected) oOption.selected = true;

	oListbox.appendChild(oOption);
}

function CFL(str) {
	var newVal = '';
	var val = str.split(/\s+/);
	for(var c=0; c < val.length; c++) {
			newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length).toLowerCase() + ' ';
	}
	return newVal.substring(0,newVal.length - 1);
}

//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);
}

//Move Monitoring
//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 MoveMonitor()
{
}

MoveMonitor.els = {};
MoveMonitor.el = null;

MoveMonitor.init = function(el, params)
{
	//var callback = Function.createCallback(MoveMonitor.mouseDown, $("kb_splitter"));
	MoveMonitor.els[el] = params;
	AddEventHandler(el, "mousedown", MoveMonitor.mouseDown);
	
	//el.onmousedown = MoveMonitor.mouseDown;
}

MoveMonitor.mouseDown = function(evt)
{
	var el = this;
	
	/*var left = parseInt(el.style.left.replace("px", ""))
	var top = parseInt(el.style.top.replace("px", ""))
	if(isNaN(left))
	{
		left = evt.clientX;
	}
	if(isNaN(top))
	{
		top = evt.clientY;
	}
	var location = {x: left, y: top};*/
	
	MoveMonitor.el = el;
	MoveMonitor.startX = evt.clientX;
	MoveMonitor.startY = evt.clientY;
	//MoveMonitor.startPX = location.x;
	//MoveMonitor.startPY = location.y;
	MoveMonitor.movemode = true;

	AddEventHandler(document, "mousemove", MoveMonitor.mouseMove);
	AddEventHandler(document, "mouseup", MoveMonitor.mouseUp);

	if(MoveMonitor.els[el].down) MoveMonitor.els[el].down();
}

MoveMonitor.mouseMove = function(evt)
{
	if(!MoveMonitor.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 el = MoveMonitor.el;
	
	//var left = parseInt(el.style.left.replace("px", ""))
	//var top = parseInt(el.style.top.replace("px", ""))
	//var location = {x: left, y: top};

	var dx = x - MoveMonitor.startX;
	var dy = y - MoveMonitor.startY;

	//var newX = location.x + dx;
	//var newY = location.y + dy;
	//if(newX < 0) newX = 0;
	//if(newY < 0) newY = 0;

	MoveMonitor.startX = x;
	MoveMonitor.startY = y;

	//$(PopupWindow.moveId + "content").innerHTML = (left) + " " + (location.x + dx) + " " + (top) + " " + (location.y + dy);
	
	//el.style.left = newX + "px";
	//el.style.top = newY + "px";
	//Sys.UI.DomElement.setLocation(popup, location.x + dx, location.y + dy);
	
	if(MoveMonitor.els[el].move) MoveMonitor.els[el].move(dx, dy);
}

MoveMonitor.mouseUp = function(evt, context)
{
	MoveMonitor.movemode = false;
	RemoveEventHandler(document, "mousemove", MoveMonitor.mouseMove);
	RemoveEventHandler(document, "mouseup", MoveMonitor.mouseUp);
	var el = MoveMonitor.el;
	if(MoveMonitor.els[el].up) MoveMonitor.els[el].up();
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Remove default value from dropdown
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function removeDefaultValue(obj, value)
{
	if(obj.value != value)
	{
		for(var i = 0; i < obj.options.length; i++)
		{
			var op = obj.options[i];
			if(op.value == value)
			{
				obj.options[i] = null;
				return;
			}
		}
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//showContextMenu
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var hideContextMenuTimeout = null;

function showContextMenu(e, params, className, options) {
	clearTimeout(hideContextMenuTimeout);

	var header = option_default(options, "title", "");
	className = className? className: "popupShowContextMenu";
	
	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;
		popupDiv.style.position = "absolute";
		popupDiv.onmouseout = hideContextMenu;
		document.getElementsByTagName("form")[0].appendChild(popupDiv);
		
		imgDiv = document.createElement("div");
		imgDiv.className = className + "Arrow";
		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();
							}
				};

	if(header.length != 0)
	{
		var div = document.createElement("div");
		div.className = className + "Header";
		div.innerHTML = header;
		popupDiv.appendChild(div);
	}
	
    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;
}

function executeScript(id)
{
	var cont = id? $(id): document;
	
	var scripts = cont.getElementsByTagName("script");
	
	for(var i = 0; i < scripts.length; i++)
	{
		window.eval(scripts[i].innerHTML);
	}
}

function formatCurrency(num) 
{
    num = parseInt(num)
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return "$" + (((sign)?'':'-') + num);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TreeView Control
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var TreeView = function(){}

TreeView.events = {};

TreeView.selected = {};

TreeView.expandCollapse = function(prefix, name)
{
	var img = document.getElementsByName(prefix + "img" + name)[0];
	var ul = document.getElementsByName(prefix + "ul" + name)[0];
	
	if(ul.style.display != "")
		TreeView._expand(img, ul)
	else
		TreeView._collapse(img, ul)
}

TreeView._expand = function(img, ul)
{
	img.className = "LibC_o"
	ul.style.display = "";
	ul.style.visibility = "";
}

TreeView._collapse = function(img, ul)
{
	img.className = "LibC_c"
	ul.style.display = "none";
	ul.style.visibility = "hidden";
}

TreeView.select = function(prefix, name)
{
	if(TreeView.selected[prefix])
	{
		var lnks = document.getElementsByName(TreeView.selected[prefix]);
		if(lnks.length)
			lnks[0].className = "";
	}
	var name = prefix + "lnk" + name;
	var lnks = document.getElementsByName(name);
	if(!lnks.length) return;
	var lnk = lnks[0];
	lnk.className = "Selected"
	TreeView.selected[prefix] = name;

	// Нужно развернуть родительские секции
	var pUL = getObjectParentByTagName(lnk, "ul");
	while(pUL && pUL.getAttribute("name") != prefix + "ul")	// prefix + "ul" - root элемент
	{
		
		var img = getObjectPreviousByTagName(pUL, "img");
		TreeView._expand(img, pUL)
		pUL = getObjectParentByTagName(pUL, "ul");
	}
	
}
/*TreeView.regEvent = function(name, eventtype, f)
{
	if(!TreeView.events[name])
		TreeView.events[name] = {};
	
	TreeView.events[name][eventtype] = f;
}

TreeView.raiseevent = function(name, eventtype, param)
{
		if(typeof TreeView.events[name] != "undefined" && typeof TreeView.events[name][eventtype] != "undefined" && TreeView.events[name][eventtype]) TreeView.events[name][eventtype](param);
}*/

TreeView.raiseevent = function(namepfx, eventtype, param)
{
		if(typeof SectionControl.events[eventtype] != "undefined" && SectionControl.events[eventtype]) SectionControl.events[eventtype](namepfx, param);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Search Control
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var SearchControl = function(){}
SearchControl.dURL = "/controls/BSWeb/SearchDispatcher.aspx"
SearchControl.result = {};
SearchControl.result.conteiner = "ModuleContent";

SearchControl.onSearchClick = function()
{
	var defaultValue = trim($("SearchForm_txtSearchQuery").getAttribute('defaultvalue'));
	var query = trim($("SearchForm_txtSearchQuery").value);
	
	if(defaultValue.toLowerCase() == query.toLowerCase() || query.length == 0) return;
	
	// Если нет пользовательских обработчиков поиска, то вызываем коровский обработчик
	if(typeof SearchControl.events["onSearchClick"] == "undefined" || !SearchControl.events["onSearchClick"])
	{
		var pars = "Action=Search";
		pars += "&SearchQuery=" + encodeURIComponent(query);
		loadingON(true);
		new Ajax.Request(SearchControl.dURL, {method: 'post', onSuccess: SearchControl.searched, parameters: pars} );
		return;
	}	
	SearchControl.raiseevent("onSearchClick", query);
}

SearchControl.searched = function(s)
{
	loadingOFF(true);
	SearchControl.showResults(s.get_responseData());
}

SearchControl.events = {};

SearchControl.raiseevent = function(eventtype, param)
{
		if(typeof SearchControl.events[eventtype] != "undefined" && SearchControl.events[eventtype]) SearchControl.events[eventtype](param);
}

SearchControl.showResults = function(html)
{
	// Пытаемся найти контейнер для результатов поиска
	var el = $(SearchControl.result.conteiner);
	if(el)
		el.innerHTML = html;
}

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);
		}
	}
		
	if($("bswebbreadcrumbentry"))
	{
		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);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Pager Control
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var PagerControl = function(id, options)
{
	var me = this;
	this.id = id;
	this.options = options;
	this.events = {};
	PagerControl.instances[id] = me;
}

PagerControl.instances = {};

PagerControl.find = function(id){
	var x = PagerControl.instances[id];
	if(x){
		return x;
	}
}
	
PagerControl.prototype.raiseevent = function(eventtype, param)
{
		if(typeof this.events[eventtype] != "undefined" && this.events[eventtype]) this.events[eventtype](param);
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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.events = {};
DataGridControl.raiseevent = function(eventtype, param)
{
		Sys.Debug.traceDump(param);
		if(typeof DataGridControl.events[eventtype] != "undefined" && DataGridControl.events[eventtype]) DataGridControl.events[eventtype](param);
}

DataGridControl.pageIndexChangedHandler = function(p)
{
		Sys.Debug.traceDump(p);
}

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;
}

DataGridControl.prototype.update = function(s)
{
	var parentNode = $(this.id).parentNode;
	parentNode.innerHTML = s;
	// Устраняем увеличение вложенности
	// Грид выглядит следующим образом  <div><div id="GridGuid">...</div></div>
	// parentNode = это верхний див без id
	// s содержит целиком весь грид, а не только div с id-шником
	// parentNode.innerHTML = s; приведёт к <div><div><div id="GridGuid">...</div></div></div>
	var divs = parentNode.getElementsByTagName("div");
	var div0 = divs[0];	// div без id
	var div1 = divs[1];	// div с id
	parentNode.removeChild(div0);
	parentNode.appendChild(div1);
	executeScript(this.id);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MEGAhint
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function stripNode(node,limit,force){
    if(!force && (node.getAttribute("megahint"))) return;
    var len = node.getAttribute("chomp") || limit
    var dots = node.getAttribute("dots") || ".."
	var oldtext=node.innerHTML
    var field = ""
	if(!dots){
	    var dots=".."
	}
    if(node.getAttribute("field")){
        field = node.getAttribute("field")
        if(field.indexOf("Sort ") == -1){
            field = field + ": " + oldtext
        }
    }else{
        field = oldtext
    }
	if(oldtext.length>len){
		node.innerHTML=oldtext.substr(0,len)+dots
		doMegaHint(node,field, force)
    }else if(node.getAttribute("field")){
		doMegaHint(node,field, force)
    }
	else
	{
		clearMegaHint(node)
	}
}

function doMegaHint(node,textOfHint, force){
    //if(node.getAttribute("megahint")) return;
	if(!force & node.onmousemove && node.onmouseover && node.onmouseout)
		return;
	if(!textOfHint)
		textOfHint = node.getAttribute("megahint");
    node.setAttribute("megahint",textOfHint)
	AddEventHandler(node, "mousemove", function(event) { megahint(this.getAttribute("megahint"),event)});
	AddEventHandler(node, "mouseover", function(event) { megahint(this.getAttribute("megahint"),event)});
	AddEventHandler(node, "mouseout", function () { megahintoff() });
    //node.onmousemove=node.onmouseover=function(event) { megahint(this.getAttribute("megahint"),event)}
    //node.onmouseout=function () { megahintoff() }
    //node.style.cursor = 'default'
}

function clearMegaHint(node)
{
    node.onmousemove = node.onmouseover = null;
    node.onmouseout = null;
}

var megahintDiv = null;

function megahint(text,e){
	var x = 0;
	var y = 0;
	if(!e) {
		var event = window.event;
		x = event.x;
		y = event.y;
		
	} else {
		x = e.clientX;
		y = e.clientY;
	}
    if(!megahintDiv){
		div = document.createElement("DIV")
		div.id = "megahint";
		div.className = "megahint";
		if(isIE)
			div.className += " select-free";
		div.style.position = "absolute";
		div.innerHTML = '<div id="megahint_c"></div><!--[if lte IE 6.5]><iframe></iframe><![endif]-->';
		//document.getElementsByTagName("body")[0].appendChild(div);
		document.getElementsByTagName("form")[0].appendChild(div);
		megahintDiv = div;
    }
	if(text.length < 100)
		megahintDiv.style.whiteSpace = 'nowrap';
	else
		megahintDiv.style.whiteSpace = 'normal';
    $("megahint_c").innerHTML = text;
    megahintDiv.style.display = "block";
    megahintDiv.style.left = (x + 10) + 'px'
	if(megahintDiv.offsetLeft + megahintDiv.offsetWidth + 30 > document.documentElement.offsetWidth){
	    megahintDiv.style.left = parseInt(megahintDiv.style.left) - (megahintDiv.offsetLeft+megahintDiv.offsetWidth + 30 - document.documentElement.offsetWidth)
	}
    megahintDiv.style.top = y + document.documentElement.scrollTop + 2  + 'px';
}

function megahintoff(){
	if(megahintDiv){
		megahintDiv.style.display = "none";
	}
}

function getInputElements(container)
{
	var container = container? $(container): document;
	var arrResult = new Array();
	var arrElements = [];
	arrElements.push(container.getElementsByTagName("input"));
	arrElements.push(container.getElementsByTagName("select"));
	arrElements.push(container.getElementsByTagName("textarea"));
	arrElements.push(container.getElementsByTagName("div"));
	for (var i = 0; i < arrElements.length; i++) {
		var arr = arrElements[i];
		for(var j = 0; j < arr.length; j++) {
				arrResult.push(arr[j]);
		}
	}
	return arrResult;
}

// ScrollToElement; Scroll To Element

function scrollToElement(elId)
{
	var el = document.getElementById(elId);
	
	if(!el) return;
	
	var parEl = el.parentNode;
	
	var mark = scrollToElement.mark;
	if(!mark)
	{
		mark = document.createElement("a");
		scrollToElement.mark = mark;
	}

	mark.name = "elId";
	
	parEl.appendChild(mark);
	
	location.href = "#" + elId;
}

scrollToElement.mark = null;


// location href

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;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Show Tool Tip
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function showTooltip(obj)
{
	if(!obj.title) return;
	doMegaHint(obj, setTooltip(obj.title));
	obj.title = "";
}

function setTooltip(tip)
{
	var s = "";
	
    s += "<div style='background-color: #FEE7DD; width: 250px; margin: 0px; padding: 0px 5px 5px 5px; vertical-align: top;border: 1px #F15D22 solid; line-height: 15px;'>";
	s += "<font style='font-family: verdana; font-size: 11px; color: #143156;'>";
    s += tip;
    s += "</font>";
    s += "</div>";

	return s;
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// С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 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")
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Drop down functions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getSelectedValue(drp)
{
	var value = null;
	for(var i = 0; i < drp.options.length; i++)
		if(drp.options[i].selected)
		{
			value = drp.options[i].value
			break;
		}
	
	return value;
}


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;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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);
	}
}


/* Mouse over/out context div visibility */
var Visibility = function(){};

Visibility.initOnMouseOverVisibility = function (el, layer)
{
	el = (typeof el == 'string')? $(el): el;
	layer = (typeof layer == 'string')? $(layer): layer;
	el.onmouseover = function(){Visibility.show(el, layer)};
}

Visibility.show = function(el, layer)
{
	clearTimeout(el.vistimeout);
	var bounds = Sys.UI.DomElement.getBounds(el);
	var div = layer? layer: getObjectNexByTagName(el, "div");
	if(div)
	{
		//div.style.left = bounds.x + "px";
		//div.style.top = (bounds.y + bounds.height) + "px";
		if(div.style.display == 'none') div.style.display = '';
		div.style.visibility = "";
		
		if(typeof el.vistimeout == "undefined")
		{
			el.vistimeout = null;
			$addHandler(el, "mouseout", function(evt){Visibility.hide(evt, el, layer)});
			$addHandler(div, "mouseout", function(evt){Visibility.hide(evt, el, layer)});
			div.onmouseover = function(){clearTimeout(el.vistimeout)};
		}
	}
}

Visibility.hide = function(evt, el, layer)
{
	clearTimeout(el.vistimeout);
	el.vistimeout = setTimeout(function(){Visibility.hideNow(evt, el, layer)}, 200);
}

Visibility.hideNow = function(evt, el, layer)
{
	var div = layer? layer: getObjectNexByTagName(el, "div");
	if(div)
	{
		var bounds = Sys.UI.DomElement.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";
		}
	}
}

//PopupMenu
var popupMenuArray = new Array();
var popupMenuData = {};

function visibilityPopupMenu(id)
{
	var el = $(id);
	
	if(el.style.display != "none")
		hidePopupMenu();
	else
	{
		hidePopupMenu();
		showPopupMenu(id);
	}
}

var timeoutPopupMenu = null;

function initPopupMenu(id, btnId)
{
	var btn = $(btnId);
	var div = $(id);
	btn.onmouseover = function(){showPopupMenu(id, btnId)};
}

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);

				if(!btn.popupactivated)
				{
					btn.popupactivated = true;
					$addHandler(btn, "mouseout", function(evt){hidePopupMenu(evt, id)});
					$addHandler(el, "mouseout", function(evt){hidePopupMenu(evt, id)});
					el.onmouseover = function(){clearTimeout(timeoutPopupMenu)};
				}

				/*btn.onmouseout = function(e)
				{
					hidePopupMenu();
				}*/
				popupMenuData[id] = {btnId: btnId};
				if(btn.className.indexOf(" popupmenuactive") == -1)
					btn.className = btn.className + " popupmenuactive";
			}
			//$("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();
			}
			//Делаем подсветку пунктов меню
			var t = el.getElementsByTagName("table")[1];
			if(!t.popupactivated) {
				t.popupactivated = true;
				if(t)
				{
					var fover = function()
								{
									this.className = "popupitemactive";
								}
					var fout = function()
								{
									if(isIE)
									{
										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 + 2) && clientX < (left - 2 + this.offsetWidth) && clientY > (top + 2) && clientY < (top - 2 + this.offsetHeight))
											return;
									}
									this.className = "popupitem";
								}
					var rows = t.tBodies[0].rows;
					for(var i = 0; i < rows.length; i++)
					{
						rows[i].cells[0].onmouseover = fover;
						rows[i].cells[0].onmouseout = fout;
						rows[i].cells[0].className = "popupitem";
					}
				}
			}
		}
		else
		{
			setDivPosition(id);
		}
	
		popupMenuArray.push(id);
	}
}

//var hidePopupMenuTimer = null;

function hidePopupMenu(evt, id)
{
	var el = $(id);
	if(el)
	{
		var bounds = Sys.UI.DomElement.getBounds(el);
		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)
		{
			clearTimeout(timeoutPopupMenu);
			timeoutPopupMenu = setTimeout("hidePopupMenuNow()", 500);
		}
	}
}

function hidePopupMenuNow()
{

	/*if(delay)
	{
		hidePopupMenuTimer = setTimeout("hidePopupMenu()", 500);
		return;
	}*/
	
	while(popupMenuArray.length)
	{
		var elID =popupMenuArray.pop();
		$(elID).style.display = "none";
		if(popupMenuData[elID])
		{
			var btn = $(popupMenuData[elID].btnId);
			btn.className = btn.className.replace(" popupmenuactive", "");
			popupMenuData[elID] = 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;
}

/********************************************************************************************************************/
// Image Handling
/********************************************************************************************************************/

function doViewImage(objImg)
{
	var oEl = objImg;
	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.style.cursor = "pointer";
		oImg.onclick = function(){this.style.display = "none";};
		//oImg.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";
}


/* 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};
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Redirect Page
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function showWindowContent()
{
	var url = showWindowContent.arguments[0];
	var windowType = showWindowContent.arguments[1];
	var params = showWindowContent.arguments[2];
	var width = showWindowContent.arguments[3];
	var height = showWindowContent.arguments[4];
	var param5 = showWindowContent.arguments[5];
	
	

	var s = "";
	if (width) {
		s += ",width=" + width;
		s += ",left=" + (screen.width - width) / 2;
	}else
	{
		width = 800;
		s += ",width=" + width;
		s += ",left=" + (screen.width - width) / 2;
	}
	if (height) {
		s += ",height=" + height;
		var st = document.body.scrollTop || document.documentElement.scrollTop;
		s += ",top=" + (st + (screen.height - height) / 2); 
	}else
	{
		height = 560;
		s += ",height=" + height;
		var st = document.body.scrollTop || document.documentElement.scrollTop;
		s += ",top=" + (st + (screen.height - height) / 2); 
	}
	
	var target = "_blank";
	
	switch (windowType)
	{
		case 4:	// Print Page
			if(url.indexOf("?") == -1)
				url += "?";
			else
				url += "&";
			url += "SkinSrc=[L]Skins/Minimalist-Black-Glass/Horizontal-Tabbed-Print&Print=1"
		case 1:
			// target=_blank, with skin
			break;
		case 2:
			//self
			target = "_self";
			break;
	}
	
	setTimeout(function()
	{
		wnd = window.open(url,target,'status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes' + s);
	}, 10);
}

//Copy to clipboard

function copyToClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
	}
	else
	{
		// You have to sign the code to enable this or allow the action in about:config by changing
		//user_pref("signed.applets.codebase_principal_support", true);
		//netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

		var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;

		// create a transferable
		var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;

		// specify the data we wish to handle. Plaintext in this case.
		trans.addDataFlavor('text/unicode');

		// To get the data from the transferable we need two new objects
		var str = new Object();
		var len = new Object();

		var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);

		var copytext=meintext;

		str.data=copytext;

		trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);

		var clipid=Components.interfaces.nsIClipboard;

		if (!clip) return false;

		clip.setData(trans,null,clipid.kGlobalClipboard);	   
	}
}

/* Cookie */
function deleteCookie(name, path, domain) {
        if (getCookie(name)) {
                document.cookie = name + "=" + 
                ((path) ? "; path=" + path : "; path=/") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
}

function getCookie(name) {
        var prefix = name + "=";
        var cookieStartIndex = document.cookie.indexOf(prefix);
        if (cookieStartIndex == -1)
                return null;
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
        if (cookieEndIndex == -1)
                cookieEndIndex = document.cookie.length;
        return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

function setCookie(name, value, expires, path, domain, secure) {
		var expDate = new Date(Date.parse(new Date()) + expires * 1000);
        var curCookie = name + "=" + escape(value) +
                ((expires) ? "; expires=" + expDate.toUTCString() : "") +
               ((path) ? "; path=" + path : "; path=/") +
                ((domain) ? "; domain=" + domain : "") +
                ((secure) ? "; secure" : "");
        if ((name + "=" + escape(value)).length <= 4000)
                document.cookie = curCookie;
        else
                if (confirm("Cookie 4kb limit failed!"))
                        document.cookie = curCookie;
}



function disableForm(content)
{
	var tags = ["input", "textarea", "select"];
	for(var t = 0; t < tags.length; t++)
	{
		var arr = content.getElementsByTagName(tags[t]);
		
		for (var i = 0; i < arr.length; i++)
		{
			arr[i].disabled = true;
		}
	}
	
	var btns = content.getElementsByTagName("a");
	for (var i = 0; i < btns.length; i++)
	{
		btns[i].style.visibility = "hidden";
	}
}


function enableForm(content)
{
	var tags = ["input", "textarea", "select"];
	for(var t = 0; t < tags.length; t++)
	{
		var arr = content.getElementsByTagName(tags[t]);
		
		for (var i = 0; i < arr.length; i++)
		{
			arr[i].disabled = false;
		}
	}

	var btns = content.getElementsByTagName("a");
	for (var i = 0; i < btns.length; i++)
	{
		btns[i].style.visibility = "";
	}
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Login Popup
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function loginOpen(url)
{
	url = url && typeof url == "string"? url: encodeURIComponent(location.pathname + location.search);
	new PopupWindow('/DesktopModules/BSWeb.Login/Controls/LoginPopup.aspx?returnurl=' + url, {width: 400, height: 180, className: 'window_modal', title: 'Login required'});
}