Function.prototype.bind = function(object) {
  var __method = this;
  return function() {
    __method.apply(object, arguments);
  }
}
AjaxForm = function() {};

AjaxForm.prototype = {
replaceContent: function() {

      if (this.http_request.readyState == 4) {
         if (this.http_request.status == 200) {
            result = this.http_request.responseText;
			this.replaced.parentNode.innerHTML = result;            
         } else {
            alert('There was a problem with the request. '+this.http_request.status);
         }
      }
      
   },
makePOSTRequest: function() {
      this.http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         this.http_request = new XMLHttpRequest();
		 if (this.http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            this.http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            this.http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               this.http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!this.http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }

      this.http_request.onreadystatechange = this.replaceContent.bind(this);
      this.http_request.open('POST', this.url, true);
      this.http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      this.http_request.setRequestHeader("Content-length", this.parameters.length);
      this.http_request.setRequestHeader("Connection", "close");
      this.http_request.send(this.parameters);

   },

   
   
   reset: function (obj) {
   var poststr="";
	for (i=0; i< obj.elements.length; i++){
      if (obj.elements[i].type!="button" && obj.elements[i].type!="submit")
      {
		        if (obj.elements[i].type=="select" || obj.elements[i].type=="select-multiple")
      {
						  for (j=0; j<obj.elements[i].options.length ; j++ )
						  {
							if (obj.elements[i].options[j].selected)
							{
					      poststr += obj.elements[i].name + "=" +encodeURI( obj.elements[i].options[j].value ) +"&";								
							}
						  } 
	  } else{
      poststr += obj.elements[i].name + "=" +encodeURI( obj.elements[i].value ) +"&";
	  }
	  }
	}
	  this.parameters = poststr;
	  this.url = obj.action;
	  this.replaced = obj;
      this.makePOSTRequest();
	  return false;
	  },

    submit: function (obj, param) {
    var poststr="";
	 for (i=0; i< obj.elements.length; i++){
      if (obj.elements[i].type!="button" && obj.elements[i].type!="submit" && obj.elements[i].type!="reset")
      {

		        if (obj.elements[i].type=="select" || obj.elements[i].type=="select-multiple")
      {
						  for (j=0; j<obj.elements[i].options.length ; j++ )
						  {
							if (obj.elements[i].options[j].selected)
							{
					      poststr += obj.elements[i].name + "=" +encodeURI( obj.elements[i].options[j].value ) +"&";								
							}
						  } 
	  } else{
      poststr += obj.elements[i].name + "=" +encodeURI( obj.elements[i].value ) +"&";
	  }
	  }
	}

      this.parameters = poststr+param;
	  this.url = obj.action;
	  this.replaced = obj;
      this.makePOSTRequest();
	  return false;
	  }

}
                
var valid = true;
    function hideLoad(Sender){
    document.getElementById("l_"+Sender).style.display='block';
    labelShow(document.getElementById("l_"+Sender));
    }

function copyToClipboard(copyText) {
     if (window.clipboardData) { // IE send-to-clipboard method.
          window.clipboardData.setData('Text', copyText);
          
     } else if (navigator.product == "Gecko") {

          // 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);
          try {
          netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
          } catch (e){
              alert("Please type 'about:config' in the address bar and enable the the following preference:\n signed.applets.codebase_principal_support");
          }

          // Store support string in an object.
          var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
          if (!str) return false;
          
          str.data=copyText;
          
          // Make transferable.
          var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
          if (!trans) return false;
          
          // Specify what datatypes we want to obtain, which is text in this case.
          trans.addDataFlavor("text/unicode");
          trans.setTransferData("text/unicode",str,copyText.length*2);
          
          var clipid=Components.interfaces.nsIClipboard;
          var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
          if (!clip) return false;
          
          clip.setData(trans,null,clipid.kGlobalClipboard);
     }
}

function changeClass(SourceId){
var Link = document.getElementById("contentLink"+SourceId);
var Place = document.getElementById("contentPlace"+SourceId);
var Frm = document.getElementById("msgForm"+SourceId);
if (Link.style.display=='inline') {
    Link.style.display='none';
    Place.style.display='inline';
    Frm.style.display='block';
    }
else {
    Link.style.display='inline';
    Place.style.display='none';
    Frm.style.display='none';
}
}

function labelShow(Sender){
document.getElementById(Sender.htmlFor).style.display='block';
Sender.className = "expandable opened";
}

function messageShow(Sender) {
    document.getElementById(Sender.htmlFor).style.display = 'block';
    var trs = Sender.getElementsByTagName("a");
    if (trs.length >= 2) {
        trs[0].style.display = 'none';
        trs[1].style.display = 'inline';
    }
    var tr = Sender.parentNode.parentNode;
    tr.className = 'vis';
    var trs2 = tr.getElementsByTagName("td")[0].getElementsByTagName("div");
    if (trs.length >= 2) {
        trs2[0].style.display = 'none';
        trs2[1].style.display = 'block';
    }
}
function propertyShow(Sender){

document.getElementById(Sender.htmlFor).style.display='block';
var trs = Sender.getElementsByTagName("a");
trs[0].style.display='none';
trs[1].style.display='inline';
var tr = Sender.parentNode.parentNode;
tr.className='vis';

    var trs2 = tr.getElementsByTagName("td");
    for(i=0; i< trs2.length; i++){
            var span = trs2[i].getElementsByTagName("em");
	if (span.length>0){
  	      span[0].className="mopened";
            if (span.length>1){
                span[1].className="mclosed";
            }
}
        }
}

function messageHide(Sender){
document.getElementById(Sender.htmlFor).style.display='none';
    var trs = Sender.getElementsByTagName("a");
    trs[0].style.display='inline';
    trs[1].style.display='none';
var tr = Sender.parentNode.parentNode;
tr.className='';
var trs2 = tr.getElementsByTagName("td")[0].getElementsByTagName("div");
trs2[0].style.display='block';
trs2[1].style.display='none';
}
function propertyHide(Sender){
document.getElementById(Sender.htmlFor).style.display='none';
    var trs = Sender.getElementsByTagName("a");
    trs[0].style.display='inline';
    trs[1].style.display='none';
var tr = Sender.parentNode.parentNode;
tr.className='';
var trs2 = tr.getElementsByTagName("td");
for(i=0; i< trs2.length; i++){
var span = trs2[i].getElementsByTagName("em");
if (span.length>0){
span[0].className="mclosed";
    if (span.length>1){
        span[1].className="mopened";
    }
}
    }
}

function labelHide(Sender){
if(Sender.htmlFor!="")
document.getElementById(Sender.htmlFor).style.display='none';
Sender.className = "expandable closed";
}

function showHide(Sender){
	var i;
	if (document.getElementById(Sender.htmlFor).style.display=='none'){
	var trs = Sender.parentNode.getElementsByTagName("label");
	for(i=0; i< trs.length; i++)
	{
			labelHide(trs[i]);
	}
	labelShow(Sender);
	setTabCookie(top.document.title, Sender.htmlFor, null, null, null, null);

	} else {

	labelHide(Sender);
	if (getTabCookie(escape(top.document.title))==Sender.htmlFor)
	{

	                setTabCookie(top.document.title, "none", null, null, null, null);
	}

	};

}

function switchPanel(Sender){
      if (document.getElementById(Sender.htmlFor).style.display=='none'){
	document.getElementById(Sender.htmlFor).style.display='block';
	        setTabCookie(Sender.htmlFor, Sender.htmlFor, null, null, null, null);

	} else {

	document.getElementById(Sender.htmlFor).style.display='none';
	                setTabCookie(Sender.htmlFor, "false", null, null, null, null);
		};
}
function showHideProperty(Sender){

	if (document.getElementById(Sender.htmlFor).style.display=='none'){
	propertyShow(Sender);
	        setTabCookie(Sender.htmlFor, Sender.htmlFor, null, null, null, null);

	} else {

	propertyHide(Sender);
	//if (getCookie(escape(Sender.htmlFor))==Sender.htmlFor)
	//{

	                setTabCookie(Sender.htmlFor, "false", null, null, null, null);
	//}
	};

}
function openMessage(Sender){
   if (Sender!=null){ if (Sender.htmlFor==""){
         var trs = Sender.getElementsByTagName("a");
    if (trs[0].style.display=='none'){
        trs[0].style.display='inline';
        trs[1].style.display='none';
        var labels = Sender.parentNode.parentNode.parentNode.getElementsByTagName("label");
           for(r=0; r< labels.length; r++)
	        {
			if (labels[r].className.indexOf("openMessage")>-1) messageHide(labels[r]);
	        }
    } else {
        trs[0].style.display='none';
        trs[1].style.display='inline';
        var labels =Sender.parentNode.parentNode.parentNode.getElementsByTagName("label");
           for(r=0; r< labels.length; r++)
	        {
			if (labels[r].className.indexOf("openMessage")>-1) messageShow(labels[r]);
	        }
    };

        }
    else {
    if (document.getElementById(Sender.htmlFor).style.display=='none'){
	messageShow(Sender);
	} else {
	messageHide(Sender);
	};
    };
}
}
function openProperty(Sender){
    if (Sender.htmlFor==""){
         var trs = Sender.getElementsByTagName("a");
    if (trs[0].style.display=='none'){
        trs[0].style.display='inline';
        trs[1].style.display='none';
        var labels = Sender.parentNode.parentNode.getElementsByTagName("label");

           for(var e=0; e< labels.length; e++)
	        {
			if (labels[e].className.indexOf("openProperty")>-1) {
                propertyHide(labels[e]);

                setTabCookie(labels[e].htmlFor, "false", null, null, null, null);
            }
	        }
    } else {
        trs[0].style.display='none';
        trs[1].style.display='inline';
        var labels =Sender.parentNode.parentNode.getElementsByTagName("label");

           for(var e=0; e< labels.length; e++)
	        {
			if (labels[e].className.indexOf("openProperty")>-1) {
                propertyShow(labels[e]);

                setTabCookie(labels[e].htmlFor, labels[e].htmlFor, null, null, null, null);
            }
	        }
    };

        }
    else {
    if (document.getElementById(Sender.htmlFor).style.display=='none'){
	propertyShow(Sender);
	} else {
	propertyHide(Sender);
	};
    };

}
function openClose(Sender){
	if (document.getElementById(Sender.htmlFor).style.display=='none'){
	labelShow(Sender);
	} else {
	labelHide(Sender);
	};

}

function setTabCookie(name, value, expires, path, domain, secure) {
    
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=/" : "; path=/") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;

}


/*
  name - name of the desired cookie
  return string containing value of specified cookie or null
  if cookie does not exist
*/

function getLabelsByClassName(className) {
  var children = document.getElementsByTagName('label');
  var elements = new Array();
  for (var i = 0; i < children.length; i++) {
    var child = children[i];

          if (child.className.indexOf(className)>0) {
        elements.push(child);
      }
    
  }
  return elements;
}

function getTabCookie(name) {
  var dc = parent.window.document.cookie;

  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);

  if (begin == -1) {
    begin = dc.indexOf(prefix);

    if (begin != 0) return null;
  } else
    begin += 2;
  var end = dc.indexOf(";", begin);
  if (end == -1)
    end = dc.length;

  return unescape(dc.substring(begin + prefix.length, end));
}


/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/

function deleteTabCookie(name, path, domain) {

  //if (getTabCookie(name)) {
    setTabCookie(name, "none", null, path, domain);
      /*
    document.cookie = name + "=none" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    */
  //}

}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"

function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

function trim_spaces() {
    var temp_string  = this;
    while(temp_string.substring(0, 1) == " ")
        temp_string = temp_string.substring(1);
    while(temp_string.substring(temp_string.length - 1) == " ")
        temp_string = temp_string.substring(0, temp_string.length - 2);
    return temp_string;
}
String.prototype.trim=trim_spaces;

function isEmail(who) {
	function isEmpty(who) {
		var testArr=who.split("");
		if(testArr.length==0)
			return true;
		var toggle=0;
		for(var i=0; i<testArr.length; i++) {
			if(testArr[i]==" ") {
				toggle=1;
				break;
			}
		}
		if(toggle)
			return true;
		return false;
	}

	function isValid(who) {
		var invalidChars=new Array("~","!","@","#","$","%","^","&","*","(",")","+","=","[","]",":",";",",","\"","'","|","{","}","\\","/","<",">","?");
		var testArr=who.split("");
		for(var i=0; i<testArr.length; i++) {
			for(var j=0; j<invalidChars.length; j++) {
				if(testArr[i]==invalidChars[j]) {
					return false;
				}
			}
		}
		return true;
	}

	function isfl(who) {
		var invalidChars=new Array("-","_",".");
		var testArr=who.split("");
		which=0;
		for(var i=0; i<2; i++) {
			for(var j=0; j<invalidChars.length; j++) {
				if(testArr[which]==invalidChars[j]) {
					return false;
				}
			}
			which=testArr.length-1;
		}
		return true;
	}

	function isDomain(who) {
		var invalidChars=new Array("-","_",".");
		var testArr=who.split("");
		if(testArr.length<2||testArr.length>4) {
			return false;
		}
		for(var i=0; i<testArr.length; i++) {
			for(var j=0; j<invalidChars.length; j++) {
				if(testArr[i]==invalidChars[j]) {
					return false;
				}
			}
		}
		return true;
	}


	var testArr=who.split("@"); 
	if(testArr.length<=1||testArr.length>2) {
		return false;
	}
	else {
		if(isValid(testArr[0])&&isfl(testArr[0])&&isValid(testArr[1])) {
			if(!isEmpty(testArr[testArr.length-1])&&!isEmpty(testArr[0])) {
				var testArr2=testArr[testArr.length-1].split(".");
				if(testArr2.length>=2) {
					var toggle=1;
					for(var i=0; i<testArr2.length; i++) {
						if(isEmpty(testArr2[i])||!isfl(testArr2[i])) {
							toggle=0;
							break;
						}
					}
					if(toggle&&isDomain(testArr2[testArr2.length-1]))
						return true;
					return false;
				}
				return false;
			}
		}
	}
}

/* With RegExp */
function isEmail2(who) {
	//var email=/^[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*\.([A-Za-z]){2,4}$/i;
	var email=/^[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*$/i;
    email=/^[A-Za-z0-9]+([_\.\-A-Za-z0-9]+)*@[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*$/i;
	return(email.test(who));
}

function URL(url){
	if(url.length==0) eval('throw "Invalid URL ['+url+'];');
	this.url=url;
	this.port=-1;
	this.query=(this.url.indexOf('?')>=0)?this.url.substring(this.url.indexOf('?')+1):'';
	if(this.query.indexOf('#')>=0) this.query=this.query.substring(0,this.query.indexOf('#'));
	this.protocol='';
	this.host='';
	if(url.indexOf("//") == 0)		// network share like '//HOST/SHARE'
		this.url = "file:" + url;
	var protocolSepIndex=this.url.indexOf('://');
	if(protocolSepIndex>=0){
		this.protocol=this.url.substring(0,protocolSepIndex).toLowerCase();
		this.host=this.url.substring(protocolSepIndex+3);
		while (this.host.indexOf('/')==0)
		{
			this.host=this.host.substring(1);
		}
		if(this.host.indexOf('/')>=0) this.host=this.host.substring(0,this.host.indexOf('/'));
		var atIndex=this.host.indexOf('@');
		if(atIndex>=0){
			var credentials=this.host.substring(0,atIndex);
			var colonIndex=credentials.indexOf(':');
			if(colonIndex>=0){
				this.username=credentials.substring(0,colonIndex);
				this.password=credentials.substring(colonIndex);
			}else{
				this.username=credentials;
			}
			this.host=this.host.substring(atIndex+1);
		}
		var portColonIndex=this.host.indexOf(':');
		if(portColonIndex>=0){
			this.port=this.host.substring(portColonIndex);
			this.host=this.host.substring(0,portColonIndex);
		}
		this.file=this.url.substring(protocolSepIndex+3);
		this.file=this.file.substring(this.file.indexOf('/'));
	}else{
		this.file=this.url;
	}
	if(this.file.indexOf('?')>=0) this.file=this.file.substring(0, this.file.indexOf('?'));
	var refSepIndex=url.indexOf('#');
	if(refSepIndex>=0){
		this.file=this.file.substring(0,refSepIndex);
		this.reference=this.url.substring(this.url.indexOf('#'));
	}else{
		this.reference='';
	}
	this.path=this.file;
	if(this.query.length>0) this.file+='?'+this.query;
	if(this.reference.length>0) this.file+='#'+this.reference;

	this.getPort=getPort;
	this.getQuery=getQuery;
	this.getProtocol=getProtocol;
	this.getHost=getHost;
	this.getUserName=getUserName;
	this.getPassword=getPassword;
	this.getFile=getFile;
	this.getReference=getReference;
	this.getPath=getPath;
	this.getArgumentValue=getArgumentValue;
	this.getArgumentValues=getArgumentValues;
	this.toString=toString;

	/* Returns the port part of this URL, i.e. '8080' in the url 'http://server:8080/' */
	function getPort(){
		return this.port;
	}

	/* Returns the query part of this URL, i.e. 'Open' in the url 'http://server/?Open' */
	function getQuery(){
		return this.query;
	}

	/* Returns the protocol of this URL, i.e. 'http' in the url 'http://server/' */
	function getProtocol(){
		return this.protocol;
	}

	/* Returns the host name of this URL, i.e. 'server.com' in the url 'http://server.com/' */
	function getHost(){
		return this.host;
	}

	/* Returns the user name part of this URL, i.e. 'joe' in the url 'http://joe@server.com/' */
	function getUserName(){
		return this.username;
	}

	/* Returns the password part of this url, i.e. 'secret' in the url 'http://joe:secret@server.com/' */
	function getPassword(){
		return this.password;
	}

	/* Returns the file part of this url, i.e. everything after the host name. */
	function getFile(){
		return this.file;
	}

	/* Returns the reference of this url, i.e. 'bookmark' in the url 'http://server/file.html#bookmark' */
	function getReference(){
		return this.reference;
	}

	/* Returns the file path of this url, i.e. '/dir/file.html' in the url 'http://server/dir/file.html' */
	function getPath(){
		return this.path;
	}

	/* Returns the FIRST matching value to the specified key in the query.
	   If the url has a non-value argument, like 'Open' in '?Open&bla=12', this method
	   returns the same as the key: 'Open'...
	   The url must be correctly encoded, ampersands must encoded as &amp;
	   I.e. returns 'value' if the key is 'key' in the url 'http://server/?Open&amp;key=value' */
	function getArgumentValue(key){
		var a=this.getArgumentValues();
		if(a.length<1) return '';
		for(var i=0;i<a.length;i++){
			if(a[i][0]==key) return a[i][1];
		}
		return '';
	}

	/* Returns all key / value pairs in the query as a two dimensional array */
	function getArgumentValues(){
		var a=new Array();
		var b=this.query.split('&amp;');
		var c='';
		if(b.length<1) return a;
		for(var i=0;i<b.length;i++){
			c=b[i].split('=');
			a[i]=new Array(c[0],((c.length==1)?c[0]:c[1]));
		}
		return a;
	}

	/* Returns a String representation of this url */
	function toString(){
		return this.url;
	}
}

function disValid(el, title) {
    //dnikitin здесь подсвечиваем task/user udf-ы.
	;

    if (el.type=="hidden") {
		
        var icon = document.getElementById("IMG"+el.id);
        icon.style.backgroundColor="#FFA090";
        icon.style.padding="2px 2px 2px 2px";
		
		;
    }
	
    el.style.backgroundColor="#FFA090";
    el.title += title;
    valid = false;
	
}

function validate_URL(el) {

    valid = true;
    if(el.disabled)
        return true;
    var type = el.type;
    var value = el.value;
    if (value.length > 0) {
        var url;
        if (value.indexOf("http://") == 0)
            url = value.substring(7, value.length);
        else
            url = value;
        if (new URL("http://" + url).getHost().length==0 ||	!url.match("[a-zA-Z_0-9\\.\\-]{"+url.length+"}")) {
            disValid(el, "URL не корректен.");
        }
    } else {
        disValid(el, "Значение URL не может быть пустой строкой");
    }
    if (!valid) {
//        alert("Please correct highlighted field data and fill in all required (*) custom fields.");
        alert("Пожалуйста исправьте выделенные цветом поля.");
        return false;
    } else {
        return true; //return allow(Sender);
    }
}

var MSG_NOT_CHOOSEN = "Not Chosen";
var decSep = "\\.\\,";

function validate(Sender) {
    valid = true;
    var gOps = true;
    var gOp = false;
	var di = false;
	var dis = true;
    var di2 = false;
    var dis2 = true;
	for (var i = 0; i < Sender.elements.length; i++) {
        var el = Sender.elements[i];
        if(el.disabled)
            continue;
        var type = el.type;
        var alt = el.getAttribute("alt");
        var value = el.value;
        var pwd;

        if (type != "checkbox" && type != "radio" && type != "submit" && type != "image" ) {
            el.style.backgroundColor="";
            el.title = "";
            if (alt != null && value != null && alt.indexOf("mustChoose") > -1 && value.length > 0) {
                var noEmpty = null;
                if (alt.indexOf("ifNoEmpty") > -1) {
                    var noEmptyName = alt.substring(alt.indexOf("ifNoEmpty(") + 10, alt.indexOf(")", alt.indexOf("ifNoEmpty(") + 10));
                    noEmpty = Sender.elements[noEmptyName];
                }
                if (value == "0" && (!noEmpty || noEmpty.value.length > 0))
                    disValid(el, alt.substring(alt.indexOf("mustChoose(") + 11, alt.indexOf(")", alt.indexOf("mustChoose(") + 11)))
            }
            if (alt != null && value != null && alt.indexOf("email") > -1 && value.length > 0) {
                if (!isEmail2(value))
                    disValid(el, "E-mail не корректен. ");
            }
            if (alt != null && value != null && alt.indexOf("url") > -1 && value.length > 0) {
                var url;
                if (value.indexOf("http://") == 0)
                    url = value.substring(7, value.length);
                else
                    url = value;
				if (new URL("http://" + url).getHost().length==0 ||	!url.match("[a-zA-Z0-9\\.\\-\\/_]{"+url.length+"}") || url.indexOf("//") != -1) {
                    disValid(el, "URL не корректен.");
				}
            }
            if (alt != null && value != null && alt.indexOf("UrlComponent") > -1 && value.length > 0) {
                if (encodeURIComponent(value) != value)
                    disValid(el, "Компонент URL не корректен.");
            }

			if (alt != null && value != null && alt.indexOf("path") > -1 && value.length > 0) {
				var path = value;
				if (path.indexOf("//") != 0){
					if (path != null && path.indexOf("/") == 0)
                    	path = path.substring(1, path.length);
                	if (path != null && path.lastIndexOf("/") == 0)
						path = path.substring(0, path.length - 1);
				}
				if (path.length == 0 || path.indexOf("//")!=-1 || !path.match("[a-zA-Z_0-9/%+-.,]{"+path.length+"}")) {
					disValid(el, "Путь не корректен.");
				}
			}

            if (alt != null && value != null && alt.indexOf("a_float") > -1 && value.length > 0) {
                var re1 = new RegExp("[^\\d\\-" + decSep + "]");
                var re2 = new RegExp("-?\\d*[" + decSep + "]?\\d*");
                if (value.search(re1) > -1 || value.match(re2) != value)
                    disValid(el, "Должно быть вещественное число. ");
//                    disValid(el, "Must be a float number. ");
            }
            if (alt != null && value != null && alt.indexOf("p_xfloat") > -1 && value.length > 0) {
                var re1 = new RegExp("[^\\d\\-" + decSep + "]");
                var re2 = new RegExp("\\d*[" + decSep + "]?\\d*$");
                if (value.search(re1) > -1 || value.match(re2) != value)
                    disValid(el, "Должно быть неотрицательное вещественное число. ");
//                    disValid(el, "Must be a non negative float number. ");
            }
            if (alt != null && value != null && alt.indexOf("p_float") > -1 && value.length > 0) {
                var re1 = new RegExp("[^\\d\\-" + decSep + "]");
                var re2 = new RegExp("\\d*[" + decSep + "]?\\d?\\d?$");
                if (value.search(re1) > -1 || value.match(re2) != value)
                    disValid(el, "Должно быть неотрицательное вещественное число. ");
//                    disValid(el, "Must be a non negative float number. ");
            }
            if (alt != null && value != null && alt.indexOf("p_3float") > -1 && value.length > 0) {
                var re1 = new RegExp("[^\\d\\-" + decSep + "]");
                var re2 = new RegExp("\\d*[" + decSep + "]?\\d?\\d?\\d?$");
                if (value.search(re1) > -1 || value.match(re2) != value)
                    disValid(el, "Должно быть неотрицательное вещественное число. ");
//                    disValid(el, "Must be a non negative float number. ");
            }
            if (alt != null && value != null && alt.indexOf("a_integer") > -1 && value.length > 0) {
                var re1 = new RegExp("[^\\d\\-]");
                var re2 = new RegExp("-?\\d*");
                if (value.search(re1) > -1 || value.match(re2) != value)
                    disValid(el, "Должно быть целое число. ");
//                    disValid(el, "Must be a integer number. ");
            }
            if (alt != null && value != null && alt.indexOf("p_integer") > -1 && value.length > 0) {
                var re1 = new RegExp("[^\\d\\-]");
                var re2 = new RegExp("\\d*");
                if (value.search(re1) > -1 || value.match(re2) != value)
                    disValid(el, "Должно быть неотрицательное целое число. ");
//                    disValid(el, "Must be a non negative integer number. ");
            }
            if (alt != null && value != null && alt.indexOf("seconds") > -1 && value.length > 0) {
                var re1 = new RegExp("[^\\d\\-]");
                var re2 = new RegExp("-?\\d*");
                if (value.search(re1) > -1 || value.match(re2) != value || value <0 || value >59)
                    disValid(el, "Должно быть целое число из диапазона 0-59. ");
//                    disValid(el, "Must be a integer number 0-59. ");
            }
			if (alt != null && value != null && alt.indexOf("minute") > -1 && value.length > 0) {
				var re1 = new RegExp("[^\\d\\-]");
				var re2 = new RegExp("-?\\d*");
				if (value.search(re1) > -1 || value.match(re2) != value || value <0 || value >59)
					disValid(el, "Должно быть целое число из диапазона 0-59. ");
//                    disValid(el, "Must be a integer number 0-59. ");
			}
			if (alt != null && value != null && alt.indexOf("hour") > -1 && value.length > 0) {
				var re1 = new RegExp("[^\\d\\-]");
				var re2 = new RegExp("-?\\d*");
				if (value.search(re1) > -1 || value.match(re2) != value || value <0 || value >23)
					disValid(el, "Должно быть целое число из диапазона 0-23. ");
//                    disValid(el, "Must be a integer number 0-59. ");
			}
            if (alt != null && value != null && alt.indexOf("natural") > -1 && value.length > 0) {
                var re1 = new RegExp("\\D");

                for(var j=0; j < value.length; ++j){
                    var ch = value.charAt(j);
                    if(ch == ' ' || ch == ';' || ch == ',' || ch == '-')
                    {
                        if(j==value.length-1) disValid(el, "Должен быть список натуральных чисел. ");
                        if(j > 0)
                        {
                            ch = value.charAt(j-1);
                            if(ch == ' ' || ch == ';' || ch == ',' || ch == '-')
                                disValid(el, "Должен быть список натуральных чисел. ");
                        }
                        else
                            disValid(el, "Должен быть список натуральных чисел. ");
                    }
                    else if ( ch < '0' || ch > '9')
                        disValid(el, "Должен быть список натуральных чисел. ");
//                        disValid(el, "Must be a list of natural numbers. ");
                }
            }
//            if (alt != null && value != null && alt.indexOf("color") > -1 && value.length > 0) {
//                if (!colorValid(value))
//                    disValid(el, "Must be a color value in format \"#dddddd\". ");
//            }
            if (alt != null && value != null && alt.indexOf("date") > -1 && value.length > 0) {
                var pattern = "%d.%m.%Y";
                var mStart =  alt.indexOf('date(');
                if (mStart > -1) {
                    var mFinish = alt.indexOf(')', mStart + 1);
                    if (mFinish == -1) {
                        pattern = alt.substring(mStart + 5, alt.length);
                    } else {
                        pattern = alt.substring(mStart + 5, mFinish);
                    }
                }
//                var calendar  = new Calendar(1, null, false, false);
//                suffix = el.id.substring(2, el.id.length);
                if (el.id.indexOf("d_") > -1) {
					if (value.indexOf("0")>-1)
						dd = value;
					else
						dd = (value < 10) ? ("0" + value) : value;
					el_dd = el;
                }
                if (el.id.indexOf("m_") > -1) {
					if (value.indexOf("0")>-1)
						mm = value;
					else
						mm = (value < 10) ? ("0" + value) : value;
                    el_mm = el;
                }
                if (el.id.indexOf("y_") > -1) {
                    var yy = value;
                    var res2 = Date.parseDate(dd + "." + mm + "." + yy, pattern);
                    if (res2.print('%d.%m.%Y') != dd + "." + mm + "." + yy) { // function toDate defined in calendar.js
                        disValid(el_dd, "Должна быть дата в формате '" + pattern + "'. ");
                        disValid(el_mm, "Должна быть дата в формате '" + pattern + "'. ");
                        disValid(el,    "Должна быть дата в формате '" + pattern + "'. ");
//                        disValid(el, "Must be a date in format '" + pattern + "'. ");
                    }
                }
            }

            var minLength = null;
            var maxLength = null;
            if (alt != null) {
                var re = /[^,\d]+\d+/g;
                var rd = /\d+/;
                var bound;
                do {
                    bound = re.exec(alt);
                    if (bound!=null) {
                        var pre = bound[0];
                        if (pre.indexOf('>')>-1 || pre.indexOf('&gt;')>-1)
                        {
                            var dig = rd.exec(pre);
                            minLength = dig[0];
                        }
                        if (pre.indexOf('<')>-1 || pre.indexOf('&lt;')>-1)
                        {
                            var dig = rd.exec(pre);
                            maxLength= dig[0];
                        }

                    }
                } while (bound!=null);

            }
            if (maxLength == null) maxLength = el.getAttribute("maxlength");
            if ((maxLength != null && maxLength < value.trim().length) || (minLength != null && minLength >= value.trim().length))
                disValid(el, "Поле имеет длину " + value.length + " символов, максимальная длина " + maxLength + ((minLength!=null) ? (" и минимальная длина " + ++minLength + ". " ): ""));
//                disValid(el, "This field has length of " + value.length + " chars, but it's maximum length is " + maxLength + ((minLength!=null) ? (" and minimum length is " + minLength + ". " ): ""));
            if (alt != null && alt.indexOf("pwd1") > -1) {
                pwd = value;
            }
            if (alt != null && alt.indexOf("pwd2") > -1) {
                if (pwd != value)
//                    disValid(el, "Password does not matches to confirmation");
                    disValid(el, "Введенные вами пароли не совпадают");
            }

        }
        if (type == "checkbox" && el.name == "ids" || el.name == "idGroups" || el.name == "checkId" || el.name == "oids") {
            if (el.checked)
                gOp = el.checked;
            else
                gOps = false;
        }
		if (type == "radio" && el.name == "defaultInterface")
			if (el.checked)
				di = true;
			else
				dis = false;

        if (type == "radio" && el.name == "type")
            if (el.checked)
                di2 = true;
            else
                dis2 = false;

		if (alt != null && alt.indexOf("template") != -1){
			if (value.toLowerCase().indexOf("[liex]") == -1){
				alert("Вы должны вставить маркер [LIEX] в то место шаблона, где будут вставляться тексты статей");
				return false;
			}
		}

		if (type == "checkbox")
			if (alt != null && alt.indexOf("mustCheck") > -1)
				if (!el.checked){
					alert("Для регистрации необходимо принять пользовательское соглашение\n и заполнить все необходимые поля!");
					return false;
				}

        if (alt != null && alt.indexOf("parkingSubjectsMultiple") > -1) {
            var sFrom = parseInt(alt.substring(alt.indexOf('-')+1, alt.lastIndexOf('-')));
            var sTo = parseInt(alt.substring(alt.lastIndexOf('-')+1));
            var __count = 0;
            for(var __i=0; __i<el.length; __i++){
                if (el.options[__i].selected){
                    __count++;
                }
            }
            if (__count < sFrom || __count > sTo){
                disValid(el, "Необходимо выбрать от " + sFrom + " до " + sTo + " тематик. Выбрано: " + __count);
            }
        }

        if (alt != null && alt.indexOf("subjectsMultiple") > -1) {
            var _count = 0;
            for(var _i=0; _i<el.length; _i++){
                if (el.options[_i].selected){
                    _count++;
                }
            }
            if (_count <= 0){
                disValid(el, "Необходимо выбрать хотя бы одну тематику");
            }
            if (_count > 3){
                disValid(el, "Можно выбрать не более 3-х тематик (Выбрано " + _count + ")");
            }
        }
	}
    if (!valid) {
//        alert("Please correct highlighted field data and fill in all required (*) custom fields.");
        alert("Пожалуйста исправьте выделенные цветом поля.");
        return false;
    } else if (!gOps && !gOp) {
        alert("Выберите по крайней мере один Флажок");
        return false;
	} else if (!di && !dis) {
		alert("Не выбран интерфес по умолчанию!");
		return false;
    } else if (!di2 && !dis2) {
        alert("Необходимо выбрать тип вопроса!");
        return false;
    } else {
        return true; //return allow(Sender);
    }
}


// color falue validaiting
function colorValid(val) {
    var re = new RegExp("#[abcdef\\d]{6}", "i");
    return val.match(re) == val;
}


// "CLOSE_MSG" block begin
var isSubmitting = false;
var is_new = false;

function allow(sender) {
    isSubmitting = true;
    sender.onsubmit = function() {return false;};
    return true;
}

window.onbeforeunload = function() {
    if (!isSubmitting)
        for (var j=0;j < document.forms.length; j++)
            if ((document.forms[j].alt=='checkunload' || document.forms[j].id=='checkunload') && isDirty(document.forms[j]))
                return "WIN_CLOSE_MSG";
}

function isDirty(form) {
    if (is_new) {
        return true;
    }
    if (form.elements)
        for (var i = 0; i < form.elements.length; i++) {
            var control = form.elements[i];
            if (control.type != 'submit' && control.type != 'hidden' && control.type != 'button' && !control.disabled && control.getAttribute("ignoreModified") == null && getControlValue(control) != getControlDefaultValue(control))
                return true;
        }
    return false;
}

function getControlValue(control) {
    switch (control.type) {
        case 'checkbox':
            return control.checked;
        case 'select-one':
            for (var i=0; i < control.options.length; i++)
                if (control.options[i].selected)
                     return control.options[i].value;
        case 'select-multiple':
            var val = '';
            for (var i=0; i < control.options.length; i++)
                if (control.options[i].selected)
                     val += control.options[i].value + '\n';
            return val;
        default:
            return control.value;
    }        
}

function getControlDefaultValue(control) {
    switch (control.type) {
        case 'checkbox':
            return control.defaultChecked;
        case 'select-one':
            for (var i=0; i < control.options.length; i++)
                if (control.options[i].defaultSelected)
                     return control.options[i].value;
            if (control.options[0])
                return control.options[0].value;
            else
                return null;
        case 'select-multiple':
            var val = '';
            for (var i=0; i < control.options.length; i++)
                if (control.options[i].defaultSelected)
                     val += control.options[i].value + '\n';
            return val;
        default:
            return control.defaultValue;
    }
}
// "CLOSE_MSG" block end

function CheckTemplate(article){
    var temp = article.value.replace(/\[/g, "{").replace(/\]/g, "}")
    var open = 0, close = 0, links = [[{pos:0, links:0}]]
    for (var i = 0; i < temp.length; i++) {
        if (temp[i] == '{') {
            open++
            links[links.length - 1][open - close] = [{pos:i, links:0}]
        } else if(temp[i] == '}') {
            close++
            if (open < close) break
            if (open == close) {
                links[links.length] = []
            }
        } else if (temp[i] == '|') {
            links[links.length - 1][open - close][links[links.length - 1][open - close].length] = {pos:i, links:0}
        } else if (open > close && i < temp.length - 1 && temp[i] == '<' && (temp[i + 1] == 'a' || temp[i + 1] == 'A')) {
            links[links.length - 1][open - close][links[links.length - 1][open - close].length - 1].links =
                links[links.length - 1][open - close][links[links.length - 1][open - close].length - 1].links + 1;
        }
    }
    if (open > close) {
        alert("В вашем шаблоне нечетное количество фигурных скобок - лишний знак {. Это означает, что Вы допустили ошибку в шаблоне.");
        return false;
    }
    if (open < close) {
        alert("В вашем шаблоне нечетное количество фигурных скобок - лишний знак }. Это означает, что Вы допустили ошибку в шаблоне.");
        return false;
    }
    for (i = 0; i < links.length; i++) {
        for (var i1 = 1; i1 < links[i].length; i1++) {
            for (var i2 = 1; i2 < links[i][i1].length; i2++) {
                if (links[i][i1][i2].links != links[i][i1][i2 - 1].links) {
                    alert("В вашем шаблоне найдены \"исчезающие\" ссылки. В конструкции подстановки, в позиции " +
                        links[i][i1][i2 - 1].pos + " найдено " + links[i][i1][i2 - 1].links + " ссылок, а в позиции " + links[i][i1][i2].pos + " найдено " + links[i][i1][i2].links + " ссылок. Это означает, что Вы допустили ошибку в шаблоне.");
                    return false;
                }
            }
        }
    }

    return true;
}
