﻿function bsweb(){
}

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;

    bsweb.x_OnSubmitFunctions = {};
    WebForm_OnSubmit = function() {
        var res = WebForm_OnSubmitOriginal();
        try {
            if (res) {
                for (var i in bsweb.x_OnSubmitFunctions){
                    bsweb.x_OnSubmitFunctions[i]();
				}
            }
        }
        catch (e) {
        }

        return res;
    }
}

bsweb.InitControls_js = function()
{
	var a = document.createElement("a");
	a.style.display = "none";
	a.id = "lnkHidden_Controls";
	document.getElementsByTagName("form")[0].appendChild(a);
	bsweb.Controls.links.hidden = a;
}

if(typeof Sys != "undefined")
{
	Sys.Application.add_load(bsweb.InitControls_js)
}

bsweb.Controls = function(){};

bsweb.Controls.links = {};
bsweb.Controls.loading = {};
bsweb.Controls.loading.isLock = false;
bsweb.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;
	};
}

bsweb.LTrim = function( value ) {
     var re = /\s*((\S+\s*)*)/;
     return value.replace(re, "$1");
}
bsweb.RTrim = function( value ) {
     var re = /((\s*\S+)*)\s*/;
     return value.replace(re, "$1");
}
bsweb.trim = function( value ) {
     return bsweb.LTrim(bsweb.RTrim(value));
}


bsweb.trunc = function(text, length)
{
	if(length && text.length > length)
		text = text.substring(0, length) + "...";
		
	return text;
}

if(typeof bsweb.$ == "undefined")
{
	bsweb.$ = function(id){
				return document.getElementById(id);
			}
}

bsweb.createId = function(prefix)
{
	prefix = prefix? prefix + "": "x_";
	return prefix + Math.round(Math.random() * 1000000000000000);
}

bsweb.Ajax = function(){};

bsweb.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(bsweb.$("hdnUserGuid"))
		request.get_headers()["X_UserGuid"] = bsweb.$("hdnUserGuid").value;
	request.set_timeout(90000);
	if(onSuccess) request.add_completed(onSuccess);
	request.invoke();
}

bsweb.Ajax.Updater = function(updateId, url, options)
{
	var onSuccess = options.onSuccess? options.onSuccess: options.onComplete;
	var context = {updateId: updateId, onComplete: onSuccess};
	var callback = function(s){bsweb.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(bsweb.$("hdnUserGuid"))
		request.get_headers()["X_UserGuid"] = bsweb.$("hdnUserGuid").value;
	request.set_timeout(90000);
	request.add_completed(callback);
	request.invoke();
}

bsweb.Ajax._UpdaterComplete = function(sender, context)
{
	var updateId = context.updateId;
	
	var reply = sender.get_responseData();

    bsweb.$(updateId).innerHTML = reply;
	
	context.onComplete(sender);
}

bsweb.DownList = function()
{
}

bsweb.DownList.current = null;
bsweb.DownList.data = {};
bsweb.DownList.params = {};
bsweb.DownList.callbackfunctions = {};
bsweb.DownList.id = "tblDownListList";

bsweb.DownList.init = function(id, data, callbackfunction, params)
{
	params = params? params: {};
	
	var el = bsweb.$(id);
	
	bsweb.DownList.data[id] = data;
	bsweb.DownList.params[id] = params;
	bsweb.DownList.callbackfunctions[id] = callbackfunction;

	el.onmouseover = function(){bsweb.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)
		bsweb.DownList.showChecked(id)
}

bsweb.DownList.show = function(id)
{
	clearTimeout(bsweb.DownList.timeoutDownList);
	
	var listID = bsweb.DownList.id;
	
	bsweb.DownList.current = listID;
	
	var table = bsweb.$(listID);
	if(table == null)
	{
		var table = document.createElement("table");
		table.id = listID;
		table.cellPadding = 0;
		table.cellSpacing = 0;
		table.className = "DownListTable";
		table.onmouseout = function(){bsweb.DownList.hide()};
		//table.style.position = "absolute";
	}
	
	
	var data = bsweb.DownList.data[id];
	var params = bsweb.DownList.params[id];
	
	while(table.rows.length) table.deleteRow(0);
	
	var tempF = function(value)
		{
			return function(){bsweb.DownList.hideNow(); bsweb.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(bsweb.DownList.timeoutDownList);};
		}
		else
		{
			cell.className = "DownListItem";
			//cell.setAttribute("v", data[i].v);
			cell.onmouseover = function(){clearTimeout(bsweb.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 = bsweb.$(id);
	el.onmouseout = function(){/*this.className = "DownList_Button";*/ bsweb.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 = "";
}

bsweb.DownList.hide = function()
{
	clearTimeout(bsweb.DownList.timeoutDownList);
	bsweb.DownList.timeoutDownList = setTimeout("bsweb.DownList.hideNow()", 500)
}

bsweb.DownList.hideNow = function()
{
	var listID = bsweb.DownList.id;
	var table = bsweb.$(listID);
	if(table) 
		table.style.display = "none";
}

bsweb.DownList.getChecked = function(id)
{
	var data = bsweb.DownList.data[id];

	for(var i = 0; i < data.length; i++)
		if(data[i].checked) return data[i].v;
		
	return null;
}

bsweb.DownList.setChecked = function(id, v)
{
	var data = bsweb.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 = bsweb.DownList.params[id];
	
	if(params.isShowChecked)
		bsweb.DownList.showChecked(id)
}

bsweb.DownList.showChecked = function(id)
{
	var data = bsweb.DownList.data[id];

	for(var i = 0; i < data.length; i++)
		if(data[i].checked)
		{
			var parent = bsweb.$(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;
		}
	
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bsweb.DropList = function()
{
}

bsweb.DropList.data = {};
bsweb.DropList.callbackfunction = {};
bsweb.DropList.timeout = null;
bsweb.DropList.el = null;

/*bsweb.DropList.init = function(el, data, callbackfunction)
{
	var el = bsweb.$(id);
	
	bsweb.DropList.data = data;
	DownList.callbackfunction = callbackfunction;

	el.onmouseout = bsweb.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)
}*/

bsweb.DropList.getList = function()
{
	return document.getElementById("bsweb_drpDropList");
}

bsweb.DropList.show = function(el, data, callbackfunction)
{
	bsweb.DropList.clearTimeout();
	
	var list = bsweb.DropList.getList();
	if(list == null)
	{
		list = document.createElement("select");
		list.id = "bsweb_drpDropList";
		list.style.position = "absolute";
		list.style.zIndex = 255;
		list.multiple = true;
		list.onmouseover = bsweb.DropList.clearTimeout;
		list.onmouseout = bsweb.DropList.hide;
		//list.ondblclick = comboBoxListSelected;
		document.getElementsByTagName("form")[0].appendChild(list);
	}
	if(bsweb.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(bsweb.getSelectedValue(this)); bsweb.DropList.hideNow()};
		el.onmouseout = bsweb.DropList.hide;
		bsweb.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 = "";

}

bsweb.DropList.clearTimeout = function()
{
	if(bsweb.DropList.timeout != null)
	{
		clearTimeout(bsweb.DropList.timeout);
		bsweb.DropList.timeout = null;
	}
}

bsweb.DropList.hide = function()
{
	clearTimeout(bsweb.DropList.timeout);
	bsweb.DropList.timeout = setTimeout("bsweb.DropList.hideNow()", 500)
}

bsweb.DropList.hideNow = function()
{
	var list = bsweb.DropList.getList();
	list.style.display = "none";
}



bsweb.restoreValues = function(values, prefix, content, bWithHiddens)
{
	//content = content? bsweb.$(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;
			}
	}
}


bsweb.loadXml = function(xmlData) {
	if (window.ActiveXObject) {
		//for IE
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(xmlData);
		return xmlDoc;
	} else if (document.implementation && document.implementation.createDocument) {
		//for Mozila
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(xmlData,"text/xml");
		return xmlDoc;
	}
}

if(!window.Node || !Node.ELEMENT_NODE){
    Node = {ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, ENTITY_REFERENCE_NODE: 5,  ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12};
}

bsweb.innerText = function(oNode, text)
{
	if(text == null)
		return bsweb._getInnerText(oNode);
		
	if(typeof oNode.textContent != "undefined")
		oNode.textContent = text;
	else
		oNode.text = text;
}

bsweb._getInnerText = function(oNode, deep){
    var s = "";
    var nodes = oNode.childNodes;
    for(var i=0; i < nodes.length; i++){
        var node = nodes[i];
        var nodeType = node.nodeType;
        if(nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE){
            s += node.data;
        } else if(deep === true && (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE || nodeType == Node.DOCUMENT_FRAGMENT_NODE)){
            s += Sarissa.getText(node, true);
        }
    }
    return s;
}

bsweb.xmlEncode = function(sXml){
    return sXml.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
}

bsweb.collectValues = function(prefix, content, tfValues)
{
	var docXml = bsweb.loadXml("<values></values>");

	content = content? bsweb.$(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);
		bsweb.innerText(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);
		bsweb.innerText(ele, bsweb.xmlEncode(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);
		bsweb.innerText(ele, bsweb.xmlEncode(value))
	}
	
	return docXml.xml;
}

bsweb.decodeValues = function(values)
{
	for(var i in values)
		values[i] = decodeURIComponent(values[i]);
}
/* Enter Handle*/
bsweb.eventKey;

bsweb.registerSubmitHandlers = function() {
   if ( typeof(bsweb_autoSubmitNames)!="undefined" ) {
     for( i = 0; i<bsweb_autoSubmitNames.length; i++ ) {
       var ob = document.getElementById(bsweb_autoSubmitNames[i]);
       if ( ob!=null )
         ob.onkeydown =  bsweb.doSubmit;
     }
     if ( !document.all ) {
       bsweb.eventKey = "e.keyCode";
       document.captureEvents(Event.KeyDown);
     }
     else
       bsweb.eventKey = "event.keyCode";
   }
 }

bsweb.doLinkSubmit = function(linkID) {
	if(typeof bsweb.$(linkID).onclick == "function")
		bsweb.$(linkID).onclick();
	if ( document.all )
		document.getElementById(linkID).click();
	else
		document.location.href = document.getElementById(linkID).href;
 }

 bsweb.doSubmit = function(e) {
   if (eval(bsweb.eventKey)==13) {
     for( i=0; i<bsweb_autoSubmitNames.length; i++ ) {
       if (bsweb_autoSubmitNames[i]==this.id ) {
         eval(bsweb_autoSubmit[i]);
         return false;
       }
     }
   }
 }

 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Validation 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bsweb.errorElement;
bsweb.blnValidationMessageDisplayed = false;

/*bsweb.showValidationMessage = function(objElement,strMessage)
{
	bsweb.blnValidationMessageDisplayed = true;
	bsweb.showBorder(objElement, strMessage);
	bsweb.errorElement = objElement;
}*/

bsweb.showValidationMessage = function(objElement,strMessage)
{
	bsweb.showBorder(objElement, strMessage);
}

/*bsweb.hideValidationMessage = function(objElement)
{	
	//alert("focus_" + objElement.id);
	//if (errorElement == objElement)
	{
//		if (!blnValidationMessageDisplayed) hideBorder();
		if (bsweb.errorElement == objElement || objElement == document)
        {
            bsweb.hideBorder();
            bsweb.blnValidationMessageDisplayed = false;
        }
	}
}*/

bsweb.hideValidationMessage = function(objElement, fromOnFocus)
{	
    bsweb.hideBorder(objElement, fromOnFocus);
}

bsweb.getRegularExpression = function(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+$");
	strRegExp = strRegExp.replace("email", "^[A-Za-z0-9._+-]+@[A-Za-z0-9._+-]+\\.[A-Za-z]{2,4}$");

	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;
}

bsweb.getValidationResultMessage = function(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" || strType == "select")
	{
		var strRegExp = bsweb.getRegularExpression(objElement); //
		var varRegExp = RegExp(strRegExp);
		var tempValue = bsweb.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(bsweb.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(bsweb.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;
	}
}

bsweb.compareValues = function(objElem)
{
    var comElem;
    var comExpression = "";
    if(objElem.getAttribute("compare-element") != null) comElem = bsweb.$(objElem.getAttribute("compare-element"));
    if(objElem.getAttribute("compare-expression") != null) comExpression = objElem.getAttribute("compare-expression");
    if(comElem)
    {
		if(comExpression != "")
		{
	        bsweb.hideValidationMessage(objElem);
	        bsweb.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 bsweb.compareValues(comElem);
		}
    }
    return true;
}
bsweb.validate = function(objElement)
{
	//alert("blur_" + objElement.id);
	var strResult = "";
	//alert(blnValidationMessageDisplayed);
	//if (!blnValidationMessageDisplayed)
	{
		strResult = bsweb.getValidationResultMessage(objElement);
		//alert(strResult);
		if (!strResult == "") 
		{
			bsweb.showValidationMessage(objElement, strResult);
		}
		else {
			bsweb.hideValidationMessage(objElement);
		}
	}
	return strResult;
}


bsweb.validateForm = function(container)
{
	var strResult = "";
	bsweb.blnValidationMessageDisplayed = false;
	var arrElements = bsweb.getValidationElementsArray(container);
	for (var i = 0; i < arrElements.length; i++) 
	{
        if(arrElements[i].offsetHeight == 0 || arrElements[i].disabled) continue;
		var res = bsweb.validate(arrElements[i]);
		strResult += (res? res + '\n': '');
		//if (bsweb.blnValidationMessageDisplayed) return strResult;
	}
	return strResult;
}

bsweb.getValidationElementsArray = function(container)
{
	var container = container? bsweb.$(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 = bsweb.validateForm();
	if (!strResult == "") alert(strResult);
}


bsweb.getBorderDiv = function(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;
}

bsweb.updateValidationBorder = function()
{
    if(bsweb.errorElement == null) return;
    if(bsweb.blnValidationMessageDisplayed == false) return;
    bsweb.showBorder(bsweb.errorElement)
}

bsweb.showBorder = function(objElement, message)
{
	if(isIE && objElement && objElement.tagName == "SELECT") {
		objElement.style.setAttribute('backgroundColor', '#FF0000');;
	}
	else {
		if(objElement.className.indexOf('bsweberrorel') == -1)
			objElement.className += ' bsweberrorel';
	}
		
	return;
	/*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 = bsweb.$("bsweb_validation_erDiv");
	var erSpan;
	if(!erDiv)
	{
		erSpan = document.createElement("span");
		erSpan.style.position = "absolute";
		erDiv = document.createElement("div");
		erDiv.id = "bsweb_validation_erDiv";
		erDiv.className = "bsweb_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 - 1) + "px";
		erDiv.style.height = (offHeight - 1) + "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(){bsweb.hideValidationMessage(document); objElement.focus()};
	erDiv.title = message;
	
	erSpan.style.display = "";

	bsweb.vld_obj = objElement;
	//vld_flashOn();
}

bsweb.vld_timeout;
bsweb.vld_obj;

function vld_flashOn()
{
	//if(isIE) return;
	clearTimeout(bsweb.vld_timeout);

	var erDiv = bsweb.$("bsweb_validation_erDiv");
	var parentEl = bsweb.vld_obj.parentNode;
	parentEl.insertBefore(erDiv, bsweb.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;!!!";*/
		
	bsweb.vld_timeout = setTimeout("vld_flashOn()", 500);
}

bsweb.vld_flashOff = function()
{
	//if(isIE) return;
	clearTimeout(bsweb.vld_timeout);
}

bsweb.hideBorder = function(objElement, fromOnFocus)
{
	if(isIE && !fromOnFocus && objElement && objElement.tagName == "SELECT") {
		objElement.style.setAttribute('backgroundColor', '#FFFFFF');
	}
	else {
		if(objElement.className.indexOf('bsweberrorel') != -1)
			objElement.className = objElement.className.replace('bsweberrorel', '');
	}
		
	return;
	/*getBorderDiv("brdLeft").style.display = "none";
    getBorderDiv("brdRight").style.display = "none";
	getBorderDiv("brdTop").style.display = "none";
	getBorderDiv("brdBottom").style.display = "none";*/
	//vld_flashOff();
	var erDiv = bsweb.$("bsweb_validation_erDiv");
	if(erDiv)
	{
		erDiv.parentNode.style.display = "none";
	}
}

bsweb.doElementOnFocus = function()
{
	bsweb.hideValidationMessage(this);
}

bsweb.doElementOnBlur = function()
{
	bsweb.validate(this);
}

bsweb.attachValidationEventsToElement = function(objElement)
{
	if(objElement.onfocus == null) objElement.onfocus = bsweb.doElementOnFocus;
	if(objElement.onblur == null) objElement.onblur = bsweb.doElementOnBlur;
}

bsweb.attachEventsToElements = function(container)
{
	var arrElements = bsweb.getValidationElementsArray(container)
	for (var i = 0; i < arrElements.length; i++) 
	{
		bsweb.attachValidationEventsToElement(arrElements[i]);
	}
}

bsweb.attachValidationEventsToElements = function(container)
{
	bsweb.attachEventsToElements(container);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Indication 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//loading gif function
bsweb.loadingON = function(nolock){
	//nolock = true;
	bsweb.Controls.loading.i++;

    bsweb.$("loading").style.display='block'
	
	//st = document.body.scrollTop || document.documentElement.scrollTop;
	
	//bsweb.$("loading").style.left = (screen.availWidth - bsweb.$("loading").style.offsetWidth) / 2 + 'px';
	//bsweb.$("loading").style.top = (st + (screen.availHeight - bsweb.$("loading").style.offsetHeight) / 2) + 'px';

	//if (!window.loading) window.loading = 0;
	//window.loading += 1;
	var pageSize = bsweb.PopupWindow.getPageSize();
	
	var top =pageSize.windowHeight / 2;
	top += pageSize.yScroll;
	var left = pageSize.windowWidth / 2;

	bsweb.$("loading").style.left = left - 107 + 'px';
	bsweb.$("loading").style.top = top + 'px';

	//alert(bsweb.$("loading").style.left + ";" + bsweb.$("loading").style.top);
	if(!nolock){
        bsweb.PopupWindow.disableScreen();
		bsweb.Controls.loading.isLock = true;
    }
}
bsweb.loadingOFF = function(nolock){
	//nolock = true;
	bsweb.Controls.loading.i--;

	if(nolock && bsweb.Controls.loading.isLock)
			return;
	if(!nolock){
		bsweb.Controls.loading.isLock = false;
        bsweb.PopupWindow.enableScreen();
	}
	
	if(bsweb.Controls.loading.i < 0) bsweb.Controls.loading.i = 0;
	if(!bsweb.Controls.loading.i)
		bsweb.$("loading").style.display='none';
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//select. add option
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bsweb.addOption = function(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);
}

bsweb.CFL = function(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
bsweb.MoveObject = function()
{
}

bsweb.MoveObject.mouseDown = function(evt, id)
{
	var id = id;

	var popup = bsweb.$(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};
	
	bsweb.MoveObject.moveId = id;
	bsweb.MoveObject.startX = evt.clientX;
	bsweb.MoveObject.startY = evt.clientY;
	bsweb.MoveObject.startPX = location.x;
	bsweb.MoveObject.startPY = location.y;
	bsweb.MoveObject.movemode = true;

	$addHandler(document, "mousemove", bsweb.MoveObject.mouseMove);
	$addHandler(document, "mouseup", bsweb.MoveObject.mouseUp);
}

bsweb.MoveObject.mouseMove = function(evt)
{
	if(!bsweb.MoveObject.movemode) return;

	if(document.selection && document.selection.empty) document.selection.empty();
	
	var x = evt.clientX;
	var y = evt.clientY;

	//bsweb.$(bsweb.PopupWindow.moveId + "content").innerHTML = (x) + " " + (y);

	if(x < 0) return;
	if(y < 0) return;
	
	var popup = bsweb.$(bsweb.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 - bsweb.MoveObject.startX;
	var dy = y - bsweb.MoveObject.startY;

	var newX = location.x + dx;
	var newY = location.y + dy;
	//if(newX < 0) newX = 0;
	//if(newY < 0) newY = 0;

	bsweb.MoveObject.startX = x;
	bsweb.MoveObject.startY = y;

	//bsweb.$(bsweb.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);
	
}

bsweb.MoveObject.mouseUp = function(evt, context)
{
	bsweb.MoveObject.movemode = false;
	$removeHandler(document, "mousemove", bsweb.MoveObject.mouseMove);
	$removeHandler(document, "mouseup", bsweb.MoveObject.mouseUp);
}

//Move Monitoring
//Common functions
bsweb.AddEventHandler = function(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;
	}
}
bsweb.RemoveEventHandler = function(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;
	}
}

bsweb.MoveMonitor = function()
{
}

bsweb.MoveMonitor.els = {};
bsweb.MoveMonitor.el = null;

bsweb.MoveMonitor.init = function(el, params)
{
	//var callback = Function.createCallback(bsweb.MoveMonitor.mouseDown, bsweb.$("kb_splitter"));
	bsweb.MoveMonitor.els[el] = params;
	bsweb.AddEventHandler(el, "mousedown", bsweb.MoveMonitor.mouseDown);
	
	//el.onmousedown = bsweb.MoveMonitor.mouseDown;
}

bsweb.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};*/
	
	bsweb.MoveMonitor.el = el;
	bsweb.MoveMonitor.startX = evt.clientX;
	bsweb.MoveMonitor.startY = evt.clientY;
	//bsweb.MoveMonitor.startPX = location.x;
	//bsweb.MoveMonitor.startPY = location.y;
	bsweb.MoveMonitor.movemode = true;

	bsweb.AddEventHandler(document, "mousemove", bsweb.MoveMonitor.mouseMove);
	bsweb.AddEventHandler(document, "mouseup", bsweb.MoveMonitor.mouseUp);

	if(bsweb.MoveMonitor.els[el].down) bsweb.MoveMonitor.els[el].down();
}

bsweb.MoveMonitor.mouseMove = function(evt)
{
	if(!bsweb.MoveMonitor.movemode) return;

	if(document.selection && document.selection.empty) document.selection.empty();
	
	var x = evt.clientX;
	var y = evt.clientY;

	//bsweb.$(bsweb.PopupWindow.moveId + "content").innerHTML = (x) + " " + (y);

	if(x < 0) return;
	if(y < 0) return;
	
	var el = bsweb.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 - bsweb.MoveMonitor.startX;
	var dy = y - bsweb.MoveMonitor.startY;

	//var newX = location.x + dx;
	//var newY = location.y + dy;
	//if(newX < 0) newX = 0;
	//if(newY < 0) newY = 0;

	bsweb.MoveMonitor.startX = x;
	bsweb.MoveMonitor.startY = y;

	//bsweb.$(bsweb.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(bsweb.MoveMonitor.els[el].move) bsweb.MoveMonitor.els[el].move(dx, dy);
}

bsweb.MoveMonitor.mouseUp = function(evt, context)
{
	bsweb.MoveMonitor.movemode = false;
	bsweb.RemoveEventHandler(document, "mousemove", bsweb.MoveMonitor.mouseMove);
	bsweb.RemoveEventHandler(document, "mouseup", bsweb.MoveMonitor.mouseUp);
	var el = bsweb.MoveMonitor.el;
	if(bsweb.MoveMonitor.els[el].up) bsweb.MoveMonitor.els[el].up();
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Remove default value from dropdown
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bsweb.removeDefaultValue = function(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;
			}
		}
	}
}

bsweb.executeScript = function(id)
{
	var cont = id? bsweb.$(id): document;
	
	var scripts = cont.getElementsByTagName("script");
	
	for(var i = 0; i < scripts.length; i++)
	{
		window.eval(scripts[i].innerHTML);
	}
}

bsweb.formatCurrency = function(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
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bsweb.TreeView = function(){}

bsweb.TreeView.events = {};

bsweb.TreeView.selected = {};

bsweb.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 != "")
		bsweb.TreeView._expand(img, ul)
	else
		bsweb.TreeView._collapse(img, ul)
}

bsweb.TreeView._expand = function(img, ul)
{
	img.className = "LibC_o"
	ul.style.display = "";
	ul.style.visibility = "";
}

bsweb.TreeView._collapse = function(img, ul)
{
	img.className = "LibC_c"
	ul.style.display = "none";
	ul.style.visibility = "hidden";
}

bsweb.TreeView.select = function(prefix, name)
{
	if(bsweb.TreeView.selected[prefix])
	{
		var lnks = document.getElementsByName(bsweb.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"
	bsweb.TreeView.selected[prefix] = name;

	// Нужно развернуть родительские секции
	var pUL = bsweb.getObjectParentByTagName(lnk, "ul");
	while(pUL && pUL.getAttribute("name") != prefix + "ul")	// prefix + "ul" - root элемент
	{
		
		var img = bsweb.getObjectPreviousByTagName(pUL, "img");
		bsweb.TreeView._expand(img, pUL)
		pUL = bsweb.getObjectParentByTagName(pUL, "ul");
	}
	
}
/*bsweb.TreeView.regEvent = function(name, eventtype, f)
{
	if(!bsweb.TreeView.events[name])
		bsweb.TreeView.events[name] = {};
	
	bsweb.TreeView.events[name][eventtype] = f;
}

bsweb.TreeView.raiseevent = function(name, eventtype, param)
{
		if(typeof bsweb.TreeView.events[name] != "undefined" && typeof bsweb.TreeView.events[name][eventtype] != "undefined" && bsweb.TreeView.events[name][eventtype]) bsweb.TreeView.events[name][eventtype](param);
}*/

bsweb.TreeView.raiseevent = function(namepfx, eventtype, param)
{
		if(typeof SectionControl.events[eventtype] != "undefined" && SectionControl.events[eventtype]) SectionControl.events[eventtype](namepfx, param);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Search Control
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bsweb.SearchControl = function(){}
bsweb.SearchControl.dURL = "/DesktopModules/BSWeb.Core/controls/SearchDispatcher.aspx"
bsweb.SearchControl.result = {};
bsweb.SearchControl.result.conteiner = "ModuleContent";

bsweb.SearchControl.onSearchClick = function()
{
	var defaultValue = bsweb.trim(bsweb.$("SearchForm_txtSearchQuery").getAttribute('defaultvalue'));
	var query = bsweb.trim(bsweb.$("SearchForm_txtSearchQuery").value);
	
	if(defaultValue.toLowerCase() == query.toLowerCase() || query.length == 0) return;
	
	// Если нет пользовательских обработчиков поиска, то вызываем коровский обработчик
	if(typeof bsweb.SearchControl.events["onSearchClick"] == "undefined" || !bsweb.SearchControl.events["onSearchClick"])
	{
		var pars = "Action=Search";
		pars += "&SearchQuery=" + encodeURIComponent(query);
		loadingON(true);
		new bsweb.Ajax.Request(bsweb.SearchControl.dURL, {method: 'post', onSuccess: bsweb.SearchControl.searched, parameters: pars} );
		return;
	}	
	bsweb.SearchControl.raiseevent("onSearchClick", query);
}

bsweb.SearchControl.searched = function(s)
{
	loadingOFF(true);
	bsweb.SearchControl.showResults(s.get_responseData());
}

bsweb.SearchControl.events = {};

bsweb.SearchControl.raiseevent = function(eventtype, param)
{
		if(typeof bsweb.SearchControl.events[eventtype] != "undefined" && bsweb.SearchControl.events[eventtype]) bsweb.SearchControl.events[eventtype](param);
}

bsweb.SearchControl.showResults = function(html)
{
	// Пытаемся найти контейнер для результатов поиска
	var el = bsweb.$(bsweb.SearchControl.result.conteiner);
	if(el)
		el.innerHTML = html;
}

bsweb.option_default = function(options, pname, def) {
	if (options && typeof options[pname] != "undefined") return options[pname]; else return def;
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Breadcrumb
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bsweb.Breadcrumb = function(){}

bsweb.Breadcrumb.onclick = function(obj)
{
	bsweb.SearchControl.raiseevent("onclick");
}

bsweb.Breadcrumb.set = function(items, options)
{

	var overrideRoot = bsweb.option_default(options,	"overrideRoot", true);

	if(overrideRoot)
	{
		var last = bsweb.$("bswebbreadcrumblast");	// Последняя страница в цепочке страниц
		if (!last) return;
		var popups = last.getElementsByTagName("div");	// Ищем и удаляем попап для послденей страницы
		if(popups.length)
			last.removeChild(popups[0]);
		
		if(items.length)	// Заполняем попап для последней страницы
		{
			var popup = bsweb.Breadcrumb._createPopup(items[0]);
			if(popup) last.appendChild(popup);
			// Link 
			var links = last.getElementsByTagName("a");
			if(links.length) {
				if (items[0].name)
					links[0].innerHTML = items[0].name;
				if (items[0].href)
					links[0].href = items[0].href;
			}
		}
	}
		
	var next = bsweb.$("bswebbreadcrumbentry").nextSibling;	// Удяляем динамическую часть
	while(next)
	{
		var temp = next.nextSibling;
		bsweb.$("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 = "bsweb_stat";
		var separator = document.createElement("span");
		if(bsweb.Breadcrumb.separator)
			separator.innerHTML = bsweb.Breadcrumb.separator;
		else
			separator.innerHTML = "&nbsp;&nbsp;&nbsp;&raquo;&nbsp;&nbsp;&nbsp;";
		div.appendChild(separator);
		var link = document.createElement("a");
		div.appendChild(link);
		link.href = item.href;
		link.innerHTML = item.name;
		link.onmouseover = function(){bsweb.Breadcrumb.showItems(this)};
		link.onclick = item.onclick;

		var popup = bsweb.Breadcrumb._createPopup(items[i]);
		if(popup) div.appendChild(popup);

		bsweb.$("bswebbreadcrumb").appendChild(div);
	}
}

bsweb.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;
}

bsweb.Breadcrumb.showItems = function(el)
{
	clearTimeout(el.breadcrumbtimeout);
	var bounds = bsweb.getBounds(el);
	var div = bsweb.getObjectNexByTagName(el, "div");
	if(div)
	{
		var size = bsweb.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)};
		bsweb.AddEventHandler(div, "mouseout", function(evt){bsweb.Breadcrumb.hideItems(evt, el)});
	}
	if(typeof el.breadcrumbtimeout == "undefined")
	{
		el.breadcrumbtimeout = null;
		bsweb.AddEventHandler(el, "mouseout", function(evt){bsweb.Breadcrumb.hideItems(evt, el)});
	}
}

bsweb.Breadcrumb.hideItems = function(evt, el)
{
	clearTimeout(el.breadcrumbtimeout);
	
	if(isIE)
	{
		var eventSubj=document.createEventObject();
		el.breadcrumbtimeout = setTimeout(function(){bsweb.Breadcrumb.hideItemsNow(eventSubj, el)}, 200);
	}
	else
		el.breadcrumbtimeout = setTimeout(function(){bsweb.Breadcrumb.hideItemsNow(evt, el)}, 200);
}

bsweb.Breadcrumb.hideItemsNow = function(evt, el)
{
	var div = bsweb.getObjectNexByTagName(el, "div");
	if(div)
	{
		var bounds = bsweb.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";
		}
	}
}

bsweb.Breadcrumb.events = {};

bsweb.Breadcrumb.raiseevent = function(eventtype, param)
{
		if(typeof bsweb.Breadcrumb.events[eventtype] != "undefined" && bsweb.Breadcrumb.events[eventtype]) bsweb.Breadcrumb.events[eventtype](param);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Pager Control
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bsweb.PagerControl = function(id, options)
{
	var me = this;
	this.id = id;
	this.options = options;
	this.events = {};
	bsweb.PagerControl.instances[id] = me;
}

bsweb.PagerControl.instances = {};

bsweb.PagerControl.find = function(id){
	var x = bsweb.PagerControl.instances[id];
	if(x){
		return x;
	}
}
	
bsweb.PagerControl.prototype.raiseevent = function(eventtype, param)
{
		if(typeof this.events[eventtype] != "undefined" && this.events[eventtype]) this.events[eventtype](param);
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DataGrid Control
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


bsweb.DataGridControl = function(id, options)
{
	this.id = id;
	if(bsweb.$(id))
		this.table = bsweb.$(id).getElementsByTagName("table")[0];
	this.handles = {};
	this.options = options;
	bsweb.DataGridControl.instances[id] = this;
}

bsweb.DataGridControl.instances = {};

bsweb.DataGridControl.find = function(divId){
	var x = bsweb.DataGridControl.instances[divId];
	if(x){
		return x;
	}
}

bsweb.DataGridControl.events = {};
bsweb.DataGridControl.raiseevent = function(eventtype, param)
{
		Sys.Debug.traceDump(param);
		if(typeof bsweb.DataGridControl.events[eventtype] != "undefined" && bsweb.DataGridControl.events[eventtype]) bsweb.DataGridControl.events[eventtype](param);
}

bsweb.DataGridControl.pageIndexChangedHandler = function(p)
{
		Sys.Debug.traceDump(p);
}

bsweb.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 = bsweb.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;
		}
}

bsweb.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;
		}
}

bsweb.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;
}

bsweb.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;
}

bsweb.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;
}

bsweb.DataGridControl.dURL = "/DesktopModules/BSWeb.Core/Controls/DG_SetCheckMark.aspx";

bsweb.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 bsweb.Ajax.Request(bsweb.DataGridControl.dURL, {method: 'post', onSuccess: function(e){}, parameters: pars} );
	this.options.selCnt += ind;
	this.updateSelectedCount();
}

bsweb.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 bsweb.Ajax.Request(bsweb.DataGridControl.dURL, {method: 'post', onSuccess: function(e){}, parameters: pars} );
	this.options.selCnt += ind;
	this.updateSelectedCount();
}

bsweb.DataGridControl.prototype.updateSelectedCount = function()
{
	if(this.options.selCnt < 0)
		this.options.selCnt = 0;
	this.options.lblSelectCount.innerHTML = this.options.selCnt;
}

bsweb.DataGridControl.prototype.update = function(s)
{
	var parentNode = bsweb.$(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);
	bsweb.executeScript(this.id);
}

bsweb.DataGridControl.currentItem = null;

bsweb.DataGridControl.OnItemClick = function(el, divItemPopupMenuClientId, dgItemPopupMenuIdClientId) {
    bsweb.DataGridControl.hideItemSelection();
    bsweb.DataGridControl.currentItem = el;
    bsweb.DataGridControl.selectCurrentItem();

    var strXml = '';
	if(bsweb.$('xmldgmenu' + el.getAttribute('itemid'))){
		strXml = bsweb.$('xmldgmenu' + el.getAttribute('itemid')).innerHTML.replace('&nbsp;', '');
	}
    if (strXml != '') {
        var objDoc = bsweb.loadXml(strXml);
        for (var i = 0; i < objDoc.documentElement.childNodes.length; i++) {
            var node = objDoc.documentElement.childNodes[i];
            var id = node.getAttribute('id');
            if (id == 'hideids') {
                var nodetext = '';
                if (node.text) nodetext = node.text;
                else nodetext = node.textContent;
                var strIds = ',' + nodetext + ',';
                var els = document.getElementsByTagName('tr');
                for (var j = 0; j < els.length; j++) {
                    var elTr = els[j];
                    if (elTr.id.indexOf('trActionID') != -1) {
                        var elID = elTr.id.substring(elTr.id.indexOf('trActionID'));
                        elID = elID.replace('trActionID', '');
                        if (strIds.indexOf(',' + elID + ',') != -1) elTr.style.display = 'none';
                        else elTr.style.display = '';
                    }
                }
            } else if (id == 'counters') {
                var els1 = document.getElementsByTagName('td');
                for (var x = 0; x < els1.length; x++) {
                    var elTd = els1[x];
                    if (elTd.id.indexOf('tdPopupItemCounter') != -1) elTd.innerHTML = "";
                }
                for (var j = 0; j < node.childNodes[0].childNodes.length; j++) {
                    var child = node.childNodes[0].childNodes[j];
                    var id = child.getAttribute('id');
                    var newCount = child.getAttribute('new');
                    var totalCount = child.getAttribute('total');
                    var els = document.getElementsByTagName('td');
                    for (var x = 0; x < els.length; x++) {
                        var elTd = els[x];
                        if (elTd.id.indexOf('tdPopupItemCounter') != -1) {
                            var elID = elTd.id.substring(elTd.id.indexOf('tdPopupItemCounter'));
                            elID = elID.replace('tdPopupItemCounter', '');
                            if (elID == id) {
                                elTd.innerHTML = "[New:&nbsp;" + newCount + ",&nbsp;Total:&nbsp;" + totalCount + "]";
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    bsweb.$(dgItemPopupMenuIdClientId).value = el.getAttribute('itemid');
    var bounds = bsweb.getBounds(el)
    bsweb.$(divItemPopupMenuClientId).style.left = bounds.x;
    bsweb.$(divItemPopupMenuClientId).style.top = bounds.y + bounds.height;
    bsweb.showPopupMenu(divItemPopupMenuClientId, el.id);
}

bsweb.DataGridControl.OnItemOver = function(el) {
    if (!bsweb.DataGridControl.currentItem) {
        bsweb.DataGridControl.currentItem = el;
        bsweb.DataGridControl.selectCurrentItem();
        bsweb.DataGridControl.currentItem = null;
    }
}

bsweb.DataGridControl.OnItemOut = function(el) {
    if (!bsweb.DataGridControl.currentItem) {
        bsweb.DataGridControl.currentItem = el;
        bsweb.DataGridControl.hideItemSelection();
    }
}

bsweb.DataGridControl.selectCurrentItem = function() {
    if (bsweb.DataGridControl.currentItem) {
        bsweb.DataGridControl.currentItem.className = 'dgmenutblsel';
        /*bsweb.DataGridControl.currentItem.parentNode.className = 'bsweb_DataGridTdSel';*/
        /*alert(bsweb.getBounds(bsweb.DataGridControl.currentItem.parentNode).height);*/
        bsweb.DataGridControl.currentItem.style.height = bsweb.getBounds(bsweb.DataGridControl.currentItem.parentNode).height - 4 + "px";
        bsweb.$('divdgmenuarrow' + bsweb.DataGridControl.currentItem.getAttribute('itemid')).style.visibility = '';
    }
}

bsweb.DataGridControl.hideItemSelection = function() {
    if (bsweb.DataGridControl.currentItem) {
        bsweb.DataGridControl.currentItem.className = 'dgmenutbl';
        /*bsweb.DataGridControl.currentItem.parentNode.className = '';*/
        bsweb.DataGridControl.currentItem.style.height = "0px";
        
        var div = bsweb.$('divdgmenuarrow' + bsweb.DataGridControl.currentItem.getAttribute('itemid'));
        if (div.getAttribute('invert') == '1') {
            div.style.visibility = 'hidden';
        }
        bsweb.DataGridControl.currentItem = null;
    }
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MEGAhint
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bsweb.stripNode = function(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
		bsweb.doMegaHint (node,field, force)
    }else if(node.getAttribute("field")){
		bsweb.doMegaHint (node,field, force)
    }
	else
	{
		bsweb.clearMegaHint(node)
	}
}

bsweb.doMegaHint = function(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)
	bsweb.AddEventHandler(node, "mousemove", function(event) { megahint(this.getAttribute("megahint"),event)});
	bsweb.AddEventHandler(node, "mouseover", function(event) { megahint(this.getAttribute("megahint"),event)});
	bsweb.AddEventHandler(node, "mouseout", function () { bsweb.megahintoff() });
}

bsweb.clearMegaHint = function(node)
{
    node.onmousemove = node.onmouseover = null;
    node.onmouseout = null;
}

bsweb.megahintDiv = null;

bsweb.megahint = function(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(!bsweb.megahintDiv){
		div = document.createElement("DIV")
		div.id = "bswebmegahint";
		div.className = "bsweb_megahint";
		if(isIE)
			div.className += " bsweb_select-free";
		div.style.position = "absolute";
		div.innerHTML = '<div id="bswebmegahint_c"></div><!--[if lte IE 6.5]><iframe></iframe><![endif]-->';
		//document.getElementsByTagName("body")[0].appendChild(div);
		document.getElementsByTagName("form")[0].appendChild(div);
		bsweb.megahintDiv = div;
    }
	if(text.length < 100)
		bsweb.megahintDiv.style.whiteSpace = 'nowrap';
	else
		bsweb.megahintDiv.style.whiteSpace = 'normal';
    bsweb.$("bswebmegahint_c").innerHTML = text;
    bsweb.megahintDiv.style.display = "block";
    bsweb.megahintDiv.style.left = (x + 10) + 'px'
	if(bsweb.megahintDiv.offsetLeft + bsweb.megahintDiv.offsetWidth + 30 > document.documentElement.offsetWidth){
	    bsweb.megahintDiv.style.left = parseInt(bsweb.megahintDiv.style.left) - (bsweb.megahintDiv.offsetLeft+bsweb.megahintDiv.offsetWidth + 30 - document.documentElement.offsetWidth)
	}
    bsweb.megahintDiv.style.top = y + document.documentElement.scrollTop + 2  + 'px';
}

bsweb.megahintoff = function(){
	if(bsweb.megahintDiv){
		bsweb.megahintDiv.style.display = "none";
	}
}

bsweb.getInputElements = function(container)
{
	var container = container? bsweb.$(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

bsweb.scrollToElement = function(elId)
{
	var el = document.getElementById(elId);
	
	if(!el) return;
	
	var parEl = el.parentNode;
	
	var mark = bsweb.scrollToElement.mark;
	if(!mark)
	{
		mark = document.createElement("a");
		bsweb.scrollToElement.mark = mark;
	}

	mark.name = "elId";
	
	parEl.appendChild(mark);
	
	location.href = "#" + elId;
}

bsweb.scrollToElement.mark = null;


// location href

bsweb.locationHref = function(targetUrl)
{
	if(document.all)
	{
		if(bsweb.Controls.links.hidden)
		{
			bsweb.Controls.links.hidden.href = targetUrl;
			setTimeout(function(){bsweb.Controls.links.hidden.click()}, 1);
		}
	}
	else
		document.location.href = targetUrl;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Show Tool Tip
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bsweb.showTooltip = function(obj)
{
	if(!obj.title) return;
	bsweb.doMegaHint (obj, bsweb.setTooltip(obj.title));
	obj.title = "";
}

bsweb.setTooltip = function(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
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bsweb.setClassFliping = function(obj, class1, class2, t)
{
	if(typeof obj == "string") obj = bsweb.$(obj);
	if(obj.classfliptimeout) clearTimeout(obj.classfliptimeout);
	obj.className = class1;
	obj.classfliptimeout = setTimeout(function(){bsweb.setClassFliping(obj, class2, class1, t)}, t);
}

bsweb.setClassOver = function(obj)
{
	if(typeof obj == "string") obj = bsweb.$(obj);
	obj.setAttribute("outclass", obj.className)
	obj.onmouseover = bsweb._setClassOver;
	obj.onmouseout = bsweb._setClassOut;
}

bsweb._setClassOut = function(){
	this.className = this.getAttribute("outclass")
}

bsweb._setClassOver = function(){
	this.className = this.getAttribute("overclass")
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Drop down functions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bsweb.getSelectedValue = function(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;
}


bsweb.getObjectParentByTagName = function(obj,tName)
{
	while (obj) {
		obj = obj.parentNode;
		if (obj.tagName.toLowerCase() == tName.toLowerCase()) return obj;
	}
	return;
}

bsweb.getObjectPreviousByTagName = function(obj,tName)
{
	obj = obj.previousSibling;
	while (obj) {
		if (obj.nodeType == 1 && obj.tagName.toLowerCase() == tName.toLowerCase()) return obj;
		obj = obj.previousSibling;
	}
	return;
}

bsweb.getObjectNexByTagName = function(obj,tName)
{
	obj = obj.nextSibling;
	while (obj) {
		if (obj.nodeType == 1 && obj.tagName.toLowerCase() == tName.toLowerCase()) return obj;
		obj = obj.nextSibling;
	}
	return;
}

bsweb.hasParent = function(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 = bsweb.$("div" + id);
	var objImgMin = bsweb.$("imgMin" + id);
	objDiv.style.display = "";
	objImgMin.className = "ImgArrowsIn";
	if(bsweb.$("imgMin" + id + "S"))
		bsweb.$("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 && bsweb.$("divViewControlScroll"))
		bsweb.$("divViewControlScroll").scrollTop = bsweb.$("gotoViewControl" + id).offsetTop;

}

ViewCard.hideSection = function(id, noScroll)
{
	var objDiv = bsweb.$("div" + id);
	var objImgMin = bsweb.$("imgMin" + id);
	objDiv.style.display = "none";
	objImgMin.className = "ImgArrowsOut";
	if(bsweb.$("imgMin" + id + "S"))
		bsweb.$("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 && bsweb.$("divViewControlScroll"))
		bsweb.$("divViewControlScroll").scrollTop = bsweb.$("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 */
bsweb.Visibility = function(){};

bsweb.Visibility.initOnMouseOverVisibility = function (el, layer)
{
	el = (typeof el == 'string')? bsweb.$(el): el;
	layer = (typeof layer == 'string')? bsweb.$(layer): layer;
	el.onmouseover = function(){bsweb.Visibility.show(el, layer)};
}

bsweb.Visibility.show = function(el, layer)
{
	clearTimeout(el.vistimeout);
	var bounds = Sys.UI.DomElement.getBounds(el);
	var div = layer? layer: bsweb.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){bsweb.Visibility.hide(evt, el, layer)});
			$addHandler(div, "mouseout", function(evt){bsweb.Visibility.hide(evt, el, layer)});
			div.onmouseover = function(){clearTimeout(el.vistimeout)};
		}
	}
}

bsweb.Visibility.hide = function(evt, el, layer)
{
	clearTimeout(el.vistimeout);
	el.vistimeout = setTimeout(function(){bsweb.Visibility.hideNow(evt, el, layer)}, 200);
}

bsweb.Visibility.hideNow = function(evt, el, layer)
{
	var div = layer? layer: bsweb.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";
		}
	}
}

bsweb.Visibility.initOnClickVisibility = function (el, layer)
{
	el = (typeof el == 'string')? bsweb.$(el): el;
	layer = (typeof layer == 'string')? bsweb.$(layer): layer;
	el.onclick = function(){
		if(layer.style.display != 'none')
			layer.style.display = 'none';
		else 
			layer.style.display = '';
	};
}

//PopupMenu
bsweb.popupMenuArray = new Array();
bsweb.popupMenuData = {};

bsweb.visibilityPopupMenu = function(id)
{
	var el = bsweb.$(id);
	
	if(el.style.display != "none")
		bsweb.hidePopupMenu();
	else
	{
		bsweb.hidePopupMenu();
		bsweb.showPopupMenu(id);
	}
}

bsweb.timeoutPopupMenu = null;

bsweb.initPopupMenu = function(id, btnId)
{
	var btn = bsweb.$(btnId);
	var div = bsweb.$(id);
	btn.onmouseover = function(){bsweb.showPopupMenu(id, btnId)};
}

bsweb.showPopupMenu = function(id, btnId)
{
	//if(hidePopupMenuTimer) clearTimeout(hidePopupMenuTimer);
	if(bsweb.timeoutPopupMenu != null)
	{
		clearTimeout(bsweb.timeoutPopupMenu);
		bsweb.timeoutPopupMenu = null;
	}
	
	if(bsweb.popupMenuArray.length > 0 && bsweb.popupMenuArray[bsweb.popupMenuArray.length - 1] != id)
	{
		bsweb.hidePopupMenuNow();
	}

	var el = bsweb.$(id);
	
	if(!el)
		return;

	if(bsweb.popupMenuArray.length == 0 || bsweb.popupMenuArray[bsweb.popupMenuArray.length - 1] != id)
	{
		el.style.display = "";
		
		if(el.getAttribute("popuptype") == "menu")
		{
			if(btnId)
			{
				var btn = bsweb.$(btnId);

				if(!btn.popupactivated)
				{
					btn.popupactivated = true;
					$addHandler(btn, "mouseout", function(evt){bsweb.hidePopupMenu(evt, id)});
					$addHandler(el, "mouseout", function(evt){bsweb.hidePopupMenu(evt, id)});
					el.onmouseover = function(){clearTimeout(bsweb.timeoutPopupMenu)};
				}

				/*btn.onmouseout = function(e)
				{
					hidePopupMenu();
				}*/
				bsweb.popupMenuData[id] = {btnId: btnId};
				if (btn.className.indexOf(" popupitemactive") == -1)
				    btn.className = btn.className + " popupitemactive";
			}
			//bsweb.$("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;
				//bsweb.$("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)
			{
				bsweb.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;
										//bsweb.$("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
		{
			bsweb.setDivPosition(id);
		}
	
		bsweb.popupMenuArray.push(id);
	}
}

//var hidePopupMenuTimer = null;

bsweb.hidePopupMenu = function(evt, id)
{
	var el = bsweb.$(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(bsweb.timeoutPopupMenu);
			bsweb.timeoutPopupMenu = setTimeout("bsweb.hidePopupMenuNow()", 500);
		}
	}
}

bsweb.hidePopupMenuNow = function() {

    /*if(delay)
    {
    hidePopupMenuTimer = setTimeout("hidePopupMenu()", 500);
    return;
    }*/

    while (bsweb.popupMenuArray.length) {
        var elID = bsweb.popupMenuArray.pop();
        bsweb.$(elID).style.display = "none";
        if (bsweb.popupMenuData[elID]) {
            var btn = bsweb.$(bsweb.popupMenuData[elID].btnId);
            btn.className = btn.className.replace(" popupitemactive", "");
            bsweb.popupMenuData[elID] = null;
        }
    }
    bsweb.DataGridControl.hideItemSelection();
}


bsweb.get_ww = function()
{
	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;
}

bsweb.get_wh = function()
{
	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
/********************************************************************************************************************/

bsweb.doViewImage = function(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 + (bsweb.get_ww() - oImg.offsetWidth)/2) + "px";
	oImg.style.top = (st + (bsweb.get_wh() - oImg.offsetHeight)/2) + "px";
}


/* Get Bounds */

bsweb.getBounds = function(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};
}


//////////////////////////////////////////////////////////////////////////////////////
//Copy to clipboard
///////////////////////////////////////////////////////////////////////////////////////

bsweb.copyToClipboard = function(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 */
bsweb.deleteCookie = function(name, path, domain) {
        if (bsweb.getCookie(name)) {
                document.cookie = name + "=" + 
                ((path) ? "; path=" + path : "; path=/") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
}

bsweb.getCookie = function(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));
}

bsweb.setCookie = function(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;
}



bsweb.disableForm = function(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";
	}
}


bsweb.enableForm = function(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 = "";
	}
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//showContextMenu
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bsweb.hideContextMenuTimeout = null;

bsweb.showContextMenu = function(e, params, className, options) {
	clearTimeout(bsweb.hideContextMenuTimeout);

	var header = bsweb.option_default(options, "title", "");
	className = className? className: "popupShowContextMenu";
	
	if(!e) e = event; 
	var x;
	var y;
	var st;
	
	if(options.el) {
		var bounds = bsweb.getBounds(options.el);
		x = bounds.x + Math.round((bounds.width/2));
		y = bounds.y + Math.round((bounds.height/2));
		st = 0;
	} else {
		x = e.clientX;
		y = e.clientY;
		st = document.body.scrollTop || document.documentElement.scrollTop;
	}
	

	var popupDiv = bsweb.$("popupShowContextMenu");
	var imgDiv = bsweb.$("popupShowContextMenuArrow");
	if(!popupDiv) 
	{
		popupDiv = document.createElement("div");
		popupDiv.id = "popupShowContextMenu"
		popupDiv.className = className;
		popupDiv.style.position = "absolute";
		popupDiv.onmouseout = bsweb.hideContextMenu;
		document.getElementsByTagName("form")[0].appendChild(popupDiv);
		
		imgDiv = document.createElement("div");
		imgDiv.className = className + "arrow";
		imgDiv.id = "popupShowContextMenuArrow"
		imgDiv.style.position = "absolute";
		imgDiv.onmouseout = bsweb.hideContextMenu;
		imgDiv.onmouseover = function(){clearTimeout(bsweb.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;
		div.onmouseout = bsweb.hideContextMenu;
		div.onmouseover = function(){clearTimeout(bsweb.hideContextMenuTimeout)};
		popupDiv.appendChild(div);
	}
	
    for(var i = 0; i < params.length; i++)
    {
        var item = params[i];
	    var element = bsweb.CreateLink(item.name, item.icon);
	    element.onclick = tempF(item);
		element.onmouseout = bsweb.hideContextMenu;
		element.onmouseover = function(){clearTimeout(bsweb.hideContextMenuTimeout)};
       	popupDiv.appendChild(element);
		element = document.createElement("br");
		popupDiv.appendChild(element);
    }
	popupDiv.style.top = (st+y + 19) + 'px';
	popupDiv.style.display = "block";

	imgDiv.style.top = (st+y) + 'px';//parseInt(imgDiv.currentStyle.height.replace("px", ""));
	imgDiv.style.display = "block";
	
	// Left/Right direction
	var wndBounds = bsweb.PopupWindow.getPageSize();
	var elBounds = bsweb.getBounds(popupDiv);
	var dir = 0; // right
	
	if(x + elBounds.width > wndBounds.windowWidth)
		dir = 1;	// left
	
	//setTimeout(function(){	
	if(dir) {
		// left
		imgDiv.className = className + "arrowleft"
		popupDiv.style.left = (x - elBounds.width) + 'px';
		imgDiv.style.left = (x - 18) + 'px';
		//bsweb.$('lblDebug2').innerHTML = 'left';
	}
	else {
		// right
		imgDiv.className = className + "arrow";
		popupDiv.style.left = x + 'px';
		imgDiv.style.left = x + 'px';
		//bsweb.$('lblDebug2').innerHTML = 'right';
	}
	//}, 1000);
		
	//bsweb.$('lblDebug1').innerHTML = bsweb.getBounds(popupDiv).width;
}

bsweb.hideContextMenu = function()
{
	clearTimeout(bsweb.hideContextMenuTimeout);
	bsweb.hideContextMenuTimeout = setTimeout("bsweb.hideNowContextMenu()", 500);
}

bsweb.hideNowContextMenu = function()
{
	var popupDiv = bsweb.$("popupShowContextMenu");
	var imgDiv = bsweb.$("popupShowContextMenuArrow");
	if(popupDiv) 
	{
		popupDiv.style.display = "none";
		imgDiv.style.display = "none";
	}
}

bsweb.CreateLink = function(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;
}

bsweb.hightlight = function(el) {
	el = (typeof el == 'string')? bsweb.$(el): el;

	el.focus();
	el.select();
	if (document.all) {
		therange = el.createTextRange();
		therange.execCommand("Copy");
		window.status = "Contents copied to clipboard";
		setTimeout("window.status=''", 1800);
	}
}

/* Formating */
bsweb.formatCurrency = function(num, currency) 
{
	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;
	cents = "." + 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 currency + (((sign)?'':'-') + num + (cents != ".00"? cents: ''));
}

bsweb.formatPercent = function(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 + '.' + cents) + "%";
}

bsweb.formatPercent4digits = function(num) 
{
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*10000+0.50000000001);
	cents = (num%10000) + "";
	num = Math.floor(num/10000).toString();
	while (cents.length < 4)
	{
	        cents = "0" + cents;
	}
	//alert("cents_ = "+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 + '.' + cents);
}

bsweb.formatNumber = function(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);
}

bsweb.minimizeHeight = function(divId, elId) {
	var div = bsweb.$(divId);
	var el = bsweb.$(elId);
	
	//debugger;
	var height = parseInt(div.style.height.replace('px', ''));
	height = isNaN(height)? 9999999: height;
	
	if (height > el.offsetHeight)
		div.style.height = (el.offsetHeight + 4) + 'px';
}