/**
title: 
		WFX Main Client Functions

pack:
		WFX-Client Library
		
version:
		1.2.0
		
date:
		17.09.2009

author: 
		Zhirnov Dmitriy aka N0RtAn

org:
		Mental Image Studio

depends: 
		
**/

/*

    WFX-Client Functions

*/



function insertAfter(parent, node, referenceNode) 
{
    
    if (referenceNode.nextSibling)
    {
        parent.insertBefore(node, referenceNode.nextSibling);
    }
    else
    {
        parent.appendChild(node);
    }
}


function SetCheckBox(o, val)
{
    if (!o)
    {
        return;
    }

	if (parseInt(val) == 1)
	{
		o.setAttribute("checked", "checked");
	}
	else
	{
		o.setAttribute("checked", "");
		o.removeAttribute("checked");
	}
}

function SetAvatar(o, imgpath, imgname)
{
    if (!o)
    {
        return;
    }
    
	if (imgname != 0)
	{
		o.src = imgpath+imgname;
	}
	else
	{
		o.src = "/sysimages/default.gif";
	}
}

function _SubmitForm(formname, action)
{
    document.forms[formname].action = action;
    document.forms[formname].submit();
}


function maxelem(v)
{ 
    var m= v[0];
    
    for (var i=1; i <= v.length-1; i++)
    { 
        if (v[i] > m )
        {
            m= v[i];
        }
    }
    
    
    return m;
} 
  



/*

    WFX-Client Inheritance

*/

function Derive(parent, prop) 
{
	var self = function() 
	{
		if (self.preparing) 
		{	
			return delete(self.preparing);
		}

		if (self.constr) 
		{
			this.constructor = self;
			self.constr.apply(this, arguments);
		}
	};
	  
	self.prototype = {};
	  
	if (parent) 
	{
		parent.preparing = true;
		self.prototype = new parent;
		self.prototype.constructor = parent;
		self.constr = parent;
	}
	  
	if (prop) 
	{
		var cname = "constructor";
		for (var k in prop) 
		{
			if (k != cname) self.prototype[k] = prop[k];
		}
		
		if (prop[cname] && prop[cname] != Object)
		{
			self.constr = prop[cname];
		}
	}
	  
	return self;
}

// ----------------------------------------------

/*

    WFX-Client Structures

*/

var Browsers = 
{
    Opera:"Opera",
    IE:"IE",
    Firefox:"Firefox",
    Safari:"Safari",
    Chrome:"Chrome",
    Unknown:"unknown"
};

var Display =
{
    Inline:"inline",
    Block:"block",
    None:"none"
        
};

var Anchor = 
{
    X:1,
    Y:2,
    Both:3
};

/*

    WFX-Client Core

*/

WFX = new function()
{
    this.Version = "1.0.1";
    this.Browser = 
    {
        Name: function()
        {
            if (navigator.appName == "Opera")
            {
                return Browsers.Opera;
            }
            else if (navigator.appName == "Microsoft Internet Explorer")
            {
                return Browsers.IE;
            }
            else if (navigator.userAgent.indexOf('Chrome/') > -1)
            {
                return Browsers.Chrome;
            }
            else if (navigator.userAgent.indexOf('AppleWebKit/') > -1)
            {
                return Browsers.Safari;
            }
            else if (navigator.appName == "Netscape")
            {
                return Browsers.Firefox;
            }
            else
            {
                return Browsers.Unknown;
            }
        }(),
        
        Version: null,
        FullVersion: null
    };
    
    switch(this.Browser.Name)
    {
        case Browsers.Opera:
        {
            this.Browser.Version = navigator.appVersion.match(/(\d{1,2}.\d{1,2})/)[1];
            this.Browser.FullVersion = navigator.appVersion.match(/([\d.]+)/)[1];
            break;
        }
        case Browsers.IE:
        {
            this.Browser.Version = navigator.appVersion.match(/MSIE (\d{1,2}.\d{1,2});/)[1];
            this.Browser.FullVersion = navigator.appVersion.match(/MSIE ([\d.]+);/)[1];
            break;
        }
        case Browsers.Chrome:
        {
            this.Browser.Version = navigator.appVersion.match(/Chrome\/(\d{1,2}.\d{1,2})/)[1];
            this.Browser.FullVersion = navigator.appVersion.match(/Chrome\/([\d.]+)/)[1];
            break;
        }
        case Browsers.Safari:
        {
            this.Browser.Version = navigator.appVersion.match(/Version\/(\d{1,2}.\d{1,2})/)[1];
            this.Browser.FullVersion = navigator.appVersion.match(/Version\/([\d.]+)/)[1];
            break;
        }
        case Browsers.Firefox:
        {
            this.Browser.Version = navigator.userAgent.match(/Firefox\/(\d{1,2}.\d{1,2})/)[1];
            this.Browser.FullVersion = navigator.userAgent.match(/Firefox\/([\d.]+)/)[1];
            break;
        }
        default: 
        {
            this.Browser.Version = "undefined";
        }
    }
    
    
};


/*

    WFX Standard Function & Structure Library

*/

WFX.KeyCodes = 
{
    Enter:13,
    Tab:9,
    Esc:27,
    Up:38,
    Down:40,
    Left:37,
    Right:39,
    Space:32,
    Backspace:8
};

WFX.LoadIndicator = {};

WFX.LoadIndicator.Push = function()
{
    var indicator = WFX.GetElement("indicator");
    var img = document.createElement("img");
    img.setAttribute("src", "/sysimages/loader.gif");
    indicator.appendChild(img);
};

WFX.LoadIndicator.Pop = function()
{
    var indicator = WFX.GetElement("indicator");
    
    var ind = indicator.firstChild;
    
    if (ind)
    {
        indicator.removeChild(ind);
    }
};


WFX.GetElement = function(element)
{
    if (typeof(element) == "string" && element.Length != 0)
    {
        element = document.getElementById(element);
    }
    else if ( typeof(element) != "object")
    {
        alert("WFX.GetElement: Указанный элемент не существует ("+element+")");
        return null;
    }
    
    return element;
};

WFX.DisableElement = function(element) 
{
	var elm = WFX.GetElement(element);
	if (elm)
	{
		elm.disabled = true;
	}
};

WFX.EnableElement = function(element) 
{
	var elm = WFX.GetElement(element);
	if (elm) 
	{
		elm.disabled = false;
	}
};

WFX.HideElement = function(element) 
{
	var elm = WFX.GetElement(element);
	
	if (elm)
	{
		elm.style.display = Display.None;
	}
};

WFX.ShowElement = function(element, display) 
{    
	var elm = WFX.GetElement(element);
	
	if (elm) 
	{
		elm.style.display = display || Display.Block;
	}
};

WFX.SetVisible = function(el)
{
    var elm = WFX.GetElement(el);
	
	if (elm) 
	{
		elm.style.visibility = 'visible';
	}
}

WFX.SetHidden = function(el)
{
    var elm = WFX.GetElement(el);
	
	if (elm) 
	{
		elm.style.visibility = 'hidden';
	}
}

WFX.IsVisible = function(element)
{
    var elm = WFX.GetElement(element);
	
	if (elm && elm.style.display == Display.None)
	{
	    return false;
	}
	
	return true;
};

WFX.ShowHideElement = function(element, display)
{
    var elm = WFX.GetElement(element);
    
    if (!elm)
    {
        return;
    }

    if ((elm.style.display == Display.Inline) || (elm.style.display == Display.Block))
    {
        elm.style.display = Display.None;
    }
    else
    {
        elm.style.display = display || Display.Block;
    }
};

/*

    WFX-Client JSON

*/

WFX.JSON = new function()
{
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var meta = 
    {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"' : '\\"',
        '\\': '\\\\'
    };
    
    var quote = function(string) 
    {
        escapable.lastIndex = 0;
        
        return escapable.test(string) ? '"' + string.replace
        (
            escapable, 
            function (a) 
            {
                var c = meta[a];
                return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }
        ) + '"' : '"' + string + '"';
    };
    
    var str = function(key, holder) 
    {
        var i, k, v, length, partial, value = holder[key];

        switch (typeof value) 
        {
            case 'string':
            {
                return quote(value);
            }
            
            case 'number':
            {
                return isFinite(value) ? String(value) : 'null';
            }
            
            case 'boolean':
            case 'null':
            {
                return String(value);
            }
            
            case 'object':
            {
                if (!value) 
                {
                    return 'null';
                }

                partial = [];

                if (Object.prototype.toString.apply(value) === '[object Array]') 
                {
                    length = value.length;
                    for (i = 0; i < length; i += 1) 
                    {
                        partial[i] = str(i, value) || 'null';
                    }

                    v = partial.length===0?'[]':''?'['+partial.join(',')+']':'['+partial.join(',')+']';
                    return v;
                }

                for (k in value) 
                {
                    if (Object.hasOwnProperty.call(value, k)) 
                    {
                        v = str(k, value);
                        if (v) 
                        {
                            partial.push(quote(k)+(''?':':':')+v);
                        }
                    }
                }

                v = partial.length===0?'{}':''?'{'+partial.join(',')+'}':'{'+partial.join(',')+'}';
                return v;
            }
        }
    };
    
    this.GetString = function(obj)
    {
        return str('', {'': obj});
    };
    
    this.GetObject = function(string)
    {
        cx.lastIndex = 0;
        if (cx.test(string)) 
        {
            string = text.replace
            (
                cx, 
                function (a) 
                {
                    return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                }
            );
        }
        
        if (/^[\],:{}\s]*$/.
            test(string.
            replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
            replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) 
        {
            return eval('(' + string + ')');
        }
             
        throw new WFX.Exception.JSONSyntaxException("Syntax error in '"+string+"'");
    };
};    



/*

    WFX-Client Forms

*/

WFX.Forms = new function()
{
    this.SubmitForm = function(formname, action)
    {
        if (action)
        {
            document.forms[formname].action = action;
        }
        document.forms[formname].submit();
    };
};

/*

    WFX-Client Exception
    
    try
    {
	    if(1)
	    {
	        WFX.Assertion.AssertNull(null, "msg");
	    }
    }
    catch (e)
    {
	    if (e instanceof WFX.Exception.AssertionNullException) 
	    {
	        alert(e);
	    }
    }

*/

WFX.Exception = new function()
{
    
};

WFX.Exception.AssertionException = function(message)
{
    this.message = message;
    
    this.toString = function()
    {
        return 'WFX.Exception.AssertionException: ' + this.message;
    };
};

WFX.Exception.AssertionNullException = function(message)
{
    this.message = message;
    
    this.toString = function()
    {
        return 'WFX.Exception.AssertionNullException: ' + this.message;
    };
};

WFX.Exception.JSONSyntaxException = function(message)
{
    this.message = message;
    
    this.toString = function()
    {
        return 'WFX.Exception.JSONSyntaxException: ' + this.message;
    };
};

/*

    WFX-Client Assertion
    
    try
    {
	    if(1)
	    {
	        WFX.Assertion.AssertNull(null, "msg");
	    }
    }
    catch (e)
    {
	    if (e instanceof WFX.Exception.AssertionNullException) 
	    {
	        alert(e);
	    }
    } 

*/



WFX.Assertion = new function()
{
    this.Assert = function(exp, message)
    {
        if (!exp) 
        {
            throw new WFX.Exception.AssertionException(message);
        }
    };
    
    this.AssertNull = function(exp, message)
    {
        if (exp == null) 
        {
            throw new WFX.Exception.AssertionNullException(message);
        }
    };
};



/*

    WFX-Client Threads

*/

WFX.Threads = new function()
{
    var handlers = [];
    var variables = [];
    var threads = [];
        
    this.Register = function(thread_name, handler, delay)
    {
        handlers[thread_name] = new Array();
        handlers[thread_name]["handler"] = handler;
        handlers[thread_name]["delay"] = delay;
        variables[thread_name] = new Array();
    };
    
    this.UnregisterThread = function(thread_name)
    {
        if (thread_name != null && thread_name != "")
        {
            clearTimeout(threads[thread_name]);
            delete threads[thread_name];
            delete handlers[thread_name];
            delete variables[thread_name];
        }
    };
    
    this.Attach = function(thread_name, varname, value)
    {
        if (variables[thread_name])
        {
            variables[thread_name][varname] = value;
        }
    };
    
    
    this.GetValue = function(thread_name, varname)
    {
        return variables[thread_name][varname];
    };
    
    
    this.StopInterval = function(thread_name)
    {
        if (thread_name != null && thread_name != "" && threads[thread_name] != null)
        {
            clearInterval(threads[thread_name]);
            //delete threads[thread_name];
        }
    };
    
        
    this.StartInterval = function(thread_name, force_start)
    {
        this.StopInterval(thread_name);
        threads[thread_name] = setInterval(handlers[thread_name]["handler"], handlers[thread_name]["delay"]);
        
        if (force_start == true)
        {
            handlers[thread_name]["handler"]();
        }
    };
    
    this.StopTimer = function(thread_name)
    {
        if (thread_name != null && thread_name != "" && threads[thread_name] != null)
        {
            clearTimeout(threads[thread_name]);
            delete threads[thread_name];
        }
    };
    
    this.StartTimer = function(thread_name)
    {
        this.StopTimer(thread_name);
        threads[thread_name] = setTimeout(handlers[thread_name]["handler"], handlers[thread_name]["delay"]);
    };
    
};

					
/*

    WFX-Client Globals

*/

WFX.Globals = new function()
{
    var objects = [];
        
    this.Attach = function(html_id, obj)
    {
        objects[html_id] = obj;
    };
    
    this.GetObject = function(html_id)
    {
        return objects[html_id];
    };
};


WFX.Images = new function()
{
    WFX.Globals.Attach('wfx_preloader', new Array());

    this.Preload = function(img)
    {
        var pr = WFX.Globals.GetObject('wfx_preloader');
        var image = new Image();
        image.src = img;
        pr.push(image);
    };
    
    this.Length = function()
    {
        var pr = WFX.Globals.GetObject('wfx_preloader');
        return pr.length;
    };
};


/*

    WFX-Client Strings

*/

WFX.Strings = new function()
{
    this.CheckForEmail = function(string)
    {
        var filter=/^(\w+(?:\.\w+)*)@((?:\w+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        
        if (filter.test(string) == false)
        {
            alert("Пожалуйста, введите правильный адрес электронной почты.");
            return false;
        }
        return true;
    };
    
    this.CheckForFullMobile = function(string)
    {
        var filter=/^(\+[1-9]{1})?\s\d{3}\s\d{7}$/i;
        
        if (filter.test(string) == false)
        {
            alert("Пожалуйста, введите правильный номер телефона.");
            return false;
        }
        return true;
    };
    
    this.CheckForLogin = function(string)
    {
        var filter=/^[a-zA-Z0-9_\-]{2,10}$/i;
        
        if (filter.test(string) == false)
        {
            alert("Пожалуйста, введите логин в соответствии с правилами. (латинские буквы, цифры, знак \"-\" и \"_\", длинной от 2х до 10ти символов)");
            return false;
        }
        return true;
    };
    
    this.CheckForPass = function(string)
    {
        var filter=/^[^\sа-яА-Я]{6,14}$/i;
        
        if (filter.test(string) == false)
        {
            alert("Пожалуйста, введите пароль в соответствии с правилами. (русские символы исключены, длинна от 6ти до 14ти символов)");
            return false;
        }
        return true;
    };
    
    this.Format = function(val, before, after)
    {
        if (val == null)
        {
            return "0";
        }
        
        var str = val.toString();
        var temp=[];
        var rez = "";
        for (var i=0; i<str.length; i++)
        {
            if (str.charAt(i) == '.')
            {
                temp = str.split(".");
            }
        }
        
        if (temp.length > 1)
        {
            if ((temp[0].toString()).length < before)     
            {
                for (var i=0; i<(before - (temp[0].toString()).length); i++)
                    rez += "0";
                rez += (temp[0].toString());
            }
            else
            {
                rez += (temp[0].toString());    
            }
            if ((temp[1].toString()).length > after && after != 0)
            {
                rez+=".";
                for (var i=0; i< after; i++)
                    rez += (temp[1].toString()).charAt(i);
            }
            else 
            if ((temp[1].toString()).length < after && after != 0)
            {
                rez+=".";
                for (var i=0; i< (temp[1].toString()).length; i++)
                    rez += (temp[1].toString()).charAt(i);
                for (var i=0; i< (after - (temp[1].toString()).length); i++)
                    rez += "0";    
            }
        }
        else
        {
            if (str.length < 2)
            {
                for (var i=1; i< before; i++)
                    rez += "0";
            }
            rez += str;
            if (after > 0)
            {
                rez += ".";
                for (var i=0; i< after; i++)
                    rez += "0";
            }
        }  
        
        return rez;
    };
    
    this.Translit = function(str, space, _case)
    {
        var caseSize = _case;
        var lat=new Array("jo","zh","i'","ch","sh","xh","je","ju","ja","a","b","v","g","d","e","z","i","k","l","m","n","o","p","r","s","t","u","f","x","c","'","  y","`","j","h"); 
        var cyr=new Array("ё","ж","й","ч","ш","щ","э","ю","я","а","б","в","г","д","е","з","и","к","л","м","н","о","п","р","с","т","у","ф","х","ц","ь","ы","ъ","ж" ,"х"); 

        var latcap=new Array("JO","Jo","ZH","Zh","I'","Ch","CH","Sh","SH","Xh","XH","Je","JE","Ju","JU","Ja","JA","A","B","V","G","D","E","Z","I","K","L","M","N","  O","P","R","S","T","U","F","X","C","Y","J","H"); 
        var cyrcap=new Array("Ё","Ё","Ж","Ж","Й","Ч","Ч","Ш","Ш","Щ","Щ","Э","Э","Ю","Ю","Я","Я","А","Б","В","Г","Д","Е","З","И","К","Л","М","Н","О","П","Р","С","Т  ","У","Ф","Х","Ц","Ы","Ж","Х"); 
        
        var tex = str;
        var buf=tex; 
        var i;
        if (caseSize) 
        {
            for (i=0;i<latcap.length;i++) 
            { 
                buf=replace(buf,latcap[i],cyrcap[i],caseSize,0); 
            } 
        }
        for (i=0;i<lat.length;i++) 
        { 
            buf=replace(buf,lat[i],cyr[i],caseSize,0); 
        } 
        tex=buf; 
        return tex; 

        function replace(target,oldTerm,newTerm,caseSens,wordOnly) 
        { 
            var work = target; 
            var ind = 0; 
            var next = 0; 

            if (!caseSens) 
            { 
                oldTerm = oldTerm.toLowerCase(); 
                work = target.toLowerCase(); 
            } 
            
            while ((ind = work.indexOf(oldTerm,next)) >= 0) 
            { 
                if (wordOnly) 
                { 
                    var before = ind - 1; 
                    var after = ind + oldTerm.length; 
                    if (!(space(work.charAt(before)) && space(work.charAt(after)))) 
                    { 
                        next = ind + oldTerm.length; 
                        continue; 
                    }
                } 
                target = target.substring(0,ind) + newTerm + 
                target.substring(ind+oldTerm.length,target.length); 
                work = work.substring(0,ind) + newTerm + 
                work.substring(ind+oldTerm.length,work.length); 
                next = ind + newTerm.length; 
                if (next >= work.length)
                    break;
            }
            return target; 
        } 
    };
    
    this.Trim = function(str)
    {
        str = str.replace(/ /g,' ');
        return str.replace(/(^\s+)|(\s+$)/g, "");
    };
};  

/*

    WFX-Client Encoders

*/

WFX.Encoders = new function()
{
  
};

WFX.Encoders.UTF8 = new function() 
{
    this.Encode = function(string)
    {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) 
        {
            var c = string.charCodeAt(n);

            if (c < 128) 
            {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) 
            {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else 
            {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }

        return utftext;
    };
    
    this.Decode = function(utftext)
    {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) 
        {
            c = utftext.charCodeAt(i);

            if (c < 128) 
            {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) 
            {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else 
            {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    };
};

WFX.Encoders.Base64 = new function()
{
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
    this.Encode = function(input) 
    {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = WFX.Encoders.UTF8.Encode(input);

        while (i < input.length) 
        {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) 
            {
                enc3 = enc4 = 64;
            } 
            else if (isNaN(chr3)) 
            {
                enc4 = 64;
            }

            output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }

        return output;
    };
    
    this.Decode = function(input) 
    {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) 
        {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) 
            {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) 
            {
                output = output + String.fromCharCode(chr3);
            }
        }

        return WFX.Encoders.UTF8.Decode(output);

    };
};


/*

    WFX-Client Ajax
    
*/

/*

    TODO: перекодировать все данные "encodeURIComponent"

*/

WFX.Ajax = new function()
{
	this.Version = "1.4.1";
	this.MaxRetries = 100;
	this.EncType =
    {
    	FormData: "multipart/form-data",
    	FormUrlencoded: "application/x-www-form-urlencoded",
    	Text: "text/plain"
    };

	this.Request = function(onSendCallback, onSuccesCallback, onFailCallBack, onFinallyCallBack/*, caching*/)
	{
		var req = null;
		var onsend = onSendCallback;
		var onsucc = onSuccesCallback;
		var onfail = onFailCallBack;
		var onfinally = onFinallyCallBack;
		var lock = false;

		if (WFX.Browser.Name == Browsers.IE)
		{
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else
		{
			req = new XMLHttpRequest();
		}

		this.Get = function(url)
		{
			if (lock == true)
			{
				return;
			}

			req.open('GET', url, true);

			req.onreadystatechange = function()
			{
				if (req.readyState == 4)
				{
					if (req.status == 200)
					{
						var msg = req.responseText.split("::");
                        
		                if (msg.length > 1) 
		                {
			                msg = msg[1];
		                }
                	
		                switch (parseInt(req.responseText))
		                {
			                case 200:
			                {
				                onsucc(req.responseText.substr(5));
				                break;
			                }

			                case 501:
			                {
				                alert("Ошибка базы данных.\n" + msg);
				                if (onfail)
						        {
							        onfail(501);
						        }
						        else
						        {
							        alert("Серер сообщает об ошибке №" + req.status);
						        }
				                break;
			                }

			                case 800:
			                {
				                alert("Ошибка ввода данных.\n" + msg);

				                if (onfail)
						        {
							        onfail(800);
						        }
						        else
						        {
							        alert("Серер сообщает об ошибке №" + req.status);
						        }
						
				                break;
			                }
                			
			                case 900:
			                {
			                    alert("Сообщение безопасности.\n"+msg);
			                    if (onfail)
						        {
							        onfail(900);
						        }
						        else
						        {
							        alert("Серер сообщает об ошибке №" + req.status);
						        }
			                    break;
			                }

			                default:
			                {
			                    alert("Неопознанная ошибка сервера\r\n"+req.responseText);
				                //alert(msg);
			                }
		                }
					}
					else
					{
						if (onfail)
						{
							onfail(req.status);
						}
						else
						{
						    if (req.status == 0)
						    {
						        //
						    }
						    else
						    {
							    alert("Серер сообщает об ошибке №" + req.status);
							}
						}
					}

					lock = false;
					
					if (onfinally)
			        {
				        onfinally();
			        }
				}
			};

			if (onsend)
			{
				onsend();
			}

			lock = true;
			req.send(null);
		};

		this.Post = function(url, enctype, params)
		{
			params = params || new Array();
			if (lock == true)
			{
				return;
			}

			req.open("POST", url, true);

			req.onreadystatechange = function()
			{
				if (req.readyState == 4)
				{
					if (req.status == 200)
					{
						var msg = req.responseText.split("::");

		                if (msg.length > 1) 
		                {
			                msg = msg[1];
		                }
                	
		                switch (parseInt(req.responseText))
		                {
			                case 200:
			                {
				                onsucc(req.responseText.substr(5));
				                break;
			                }

			                case 501:
			                {
				                alert("Ошибка базы данных.\n" + msg);
				                if (onfail)
						        {
							        onfail(501);
						        }
						        else
						        {
							        alert("Серер сообщает об ошибке №" + req.status);
						        }
				                break;
			                }

			                case 800:
			                {
				                alert("Ошибка ввода данных.\n" + msg);
                                
				                if (onfail)
						        {
							        onfail(800);
						        }
						        else
						        {
							        alert("Серер сообщает об ошибке №" + req.status);
						        }
				                break;
			                }
                			
			                case 900:
			                {
			                    alert("Сообщение безопасности.\n"+msg);
			                    if (onfail)
						        {
							        onfail(900);
						        }
						        else
						        {
							        alert("Серер сообщает об ошибке №" + req.status);
						        }
			                    break;
			                }

			                default:
			                {
				                 alert("Неопознанная ошибка сервера\r\n"+req.responseText);
			                }
		                }
					}
					else
					{
						if (onfail)
						{
							onfail(req.status);
						}
						else
						{
							alert("Серер сообщает об ошибке №" + req.status);
						}
					}

					lock = false;
					
					if (onfinally)
			        {
				        onfinally();
			        }
				}
			};

			if (onsend)
			{
				onsend();
			}

			req.setRequestHeader("Content-Type", enctype);

			var pairs = new Array(params.length);
			for (var i = 0; i < params.length; i++)
			{
				pairs[i] = params[i].join("=");
			}

			lock = true;

			req.send(pairs.join("&"));
		};

	};

};

/*

    WFX-Client Cookie

*/

WFX.Cookie = new function()
{
	this.set = function(name, val, expir)
	{
		var data = name + "=" + escape(val) + ";";
		if (expir != 0)
		{
			var d = new Date();
			d.setMonth(d.getMonth() + expir);
			data += "expires=" + d.toUTCString() + ";";
			document.cookie = data;
		}	
	};
	
	this.get = function(name)
	{
		var cv = document.cookie;
		var r = new RegExp("\\b" + name + "\\b");
		var iStart = cv.search(r);
		if (iStart == -1)
		{
			cv=null;
		}
		else
		{
			iStart = cv.indexOf("=", iStart) + 1;
			var iEnd = cv.indexOf(";", iStart);
			if (iEnd == -1)
				iEnd = cv.length;
			
			cv = unescape(cv.substring(iStart, iEnd));
		}
		return cv;
	};
	
};



/*

    WFX-Client Events

*/

WFX.Events = new function()
{
	this.AddEventHandler = function(evt, element, handler)
	{
		var intv = setInterval
        (
            function()
            {
            	element = WFX.GetElement(element);

            	if (element)
            	{
            		clearInterval(intv);
            	}
            	else
            	{
            		return;
            	}

            	if (WFX.Browser.Name == Browsers.IE)
            	{
            		element.attachEvent('on' + evt, handler);
            	}
            	else
            	{
            		element.addEventListener(evt, handler, false);
            	}
            },
            100
        );
	};

	this.RemoveEventHandler = function(evt, element, handler)
	{
		element = WFX.GetElement(element);
		if (WFX.Browser.Name == Browsers.IE)
		{
			element.detachEvent('on' + evt, handler);
		}
		else
		{
			element.removeEventListener(evt, handler, false);
		}
	};

	this.SrcElement = function(event)
	{
		if (WFX.Browser.Name == Browsers.IE)
		{
			return event.srcElement;
		}
		else
		{
			return event.target;
		}

	};
	
	this.GetElement = function(event)
	{
	    return this.SrcElement(event);
	};

	this.KeyCode = function(event)
	{
		var key;

		if (WFX.Browser.Name == Browsers.IE)
		{
			key = event.keyCode;
		}
		else
		{
			key = event.which;
		}
		
		return key;
	};

	this.Stop = function(event)
	{
		if (WFX.Browser.Name == Browsers.IE)
		{
			event.cancelBubble = true;
			event.returnValue = false;
		}
		else
		{
			event.stopPropagation();
			event.preventDefault();
		}
	};
};

/*

    WFX-Client Opacity

*/

WFX.Opacity = new function()
{
    var property = "undefined";
    var fadeids = [];
    var cycles = [];
    
    var fps = 30;

    if (WFX.Browser.Name == Browsers.Firefox)
	{
	    property =  'MozOpacity';
    }
	else if (WFX.Browser.Name == Browsers.Safari)
	{
	    property =  'KhtmlOpacity';
    }
	else if (WFX.Browser.Name == Browsers.IE  && WFX.Browser.Version >= 5.5 )
	{
	    property =  'filter';   
    }
    else
    {
        property = "opacity";
    }
    
    this.SetFPS = function(frame_count)
    {
        fps = 1000/frame_count;
    };
    
    this.Pulse = function(element, max_opacity, min_opacity, time, delay, oncomplete)
    {
        if (max_opacity > min_opacity)
        {
            this.FadeOut(element, max_opacity, min_opacity, time/2, delay, function(el)
            {
                WFX.Opacity.FadeIn(element, min_opacity, max_opacity, time/2, 0, oncomplete);
            });
        }
        else
        {
            this.FadeIn(element, max_opacity, min_opacity, time/2, delay, function(el)
            {
                WFX.Opacity.FadeOut(element, min_opacity, max_opacity, time/2, 0, oncomplete);
            });
        }
    };
    
    this.FadeOut = function(element, start_opacity, end_opacity, time, delay, oncomplete)
    {
        var el = WFX.GetElement(element);
        
        if (!el)
        {
            return;
        }
        
        if(fadeids && fadeids[el.id])
        {
            return;
        }

        if (el.id == null)
        {
            var rnd = (Math.round((Math.random()*999999999999999999)+1));
            el.id = "fadeout"+rnd;
        }

        fadeids[el.id] = {start:start_opacity, end:end_opacity, cur:start_opacity, d:start_opacity/(time/fps), id:el.id, remain:time};
        
        WFX.Threads.Register(el.id, function()
        {
            fadeids[el.id].cur -= fadeids[el.id].d;
            
            if (fadeids[el.id].cur <= fadeids[el.id].end)
            {
                fadeids[el.id].cur = fadeids[el.id].end;
            }
            
            WFX.Opacity.SetOpacity(element, fadeids[el.id].cur);
            fadeids[el.id].remain -+ fps;
            
            if (fadeids[el.id].cur == fadeids[el.id].end)
            {
                WFX.Threads.StopInterval(el.id);
                WFX.Threads.UnregisterThread(el.id);
                
                if(fadeids)
                {
                    delete fadeids[el.id];
                }
                
                if (oncomplete) oncomplete(el);
                
            }
            
        }, fps);
        
        setTimeout
        (
            function()
            {
                WFX.Threads.StartInterval(el.id);
            }, 
            delay || 0
        );
    };
    
    this.Cycle = function(element, max_opacity, min_opacity, time, delay, onstop)
    {
        var el = WFX.GetElement(element);
        
        if (!el)
        {
            return;
        }
        
        if (el.id == null)
        {
            var rnd = (Math.round((Math.random()*999999999999999999)+1));
            el.id = "cycle"+rnd;
        }
        
        if(cycles && cycles[el.id])
        {
            return;
        }
        
        cycles[el.id] = {stop:0, intv:null};

        cycles[el.id].intv = setInterval(function()
        {
            if(cycles && cycles[el.id] && cycles[el.id].stop == 1)
            {
                clearInterval(cycles[el.id].intv);
                delete cycles[el.id];
                if (onstop) setTimeout(function(){onstop(el);}, fadeids[el.id].remain+300);
                return;
            }
            WFX.Opacity.Pulse(element, max_opacity, min_opacity, time, delay);
        }, time/50);
    };
    
    this.Pause = function(element)
    {
        var el = WFX.GetElement(element);
        
        if (!el)
        {
            return;
        }
        
        if(!fadeids || !fadeids[el.id])
        {
            return;
        }
        
        WFX.Threads.StopInterval(el.id);
    };
    
    this.InvokeStop = function(element)
    {
        var el = WFX.GetElement(element);
        
        if (!el)
        {
            return;
        }
        
        if(!cycles || !cycles[el.id])
        {
            return;
        }
        
        cycles[el.id].stop = 1;
    };
    
    this.Resume = function(element)
    {
        var el = WFX.GetElement(element);
        
        if (!el)
        {
            return;
        }
        
        if(!fadeids || !fadeids[el.id])
        {
            return;
        }
        
        WFX.Threads.StartInterval(el.id);
    };
    
    this.FadeIn = function(element, start_opacity, end_opacity, time, delay, oncomplete)
    {
        var el = WFX.GetElement(element);
        
        if (!el)
        {
            return;
        }
        
        if(fadeids && fadeids[el.id])
        {
            return;
        }
        
        var rnd = (Math.round((Math.random()*999999999999999999)+1));
        
        if (el.id == null)
        {
            el.id = "fadein"+rnd;
        }

        fadeids[el.id] = {start:start_opacity, end:end_opacity, cur:start_opacity, d:end_opacity/(time/fps), id:el.id, remain:time};
        
        WFX.Threads.Register(el.id, function()
        {
            fadeids[el.id].cur += fadeids[el.id].d;
            
            if (fadeids[el.id].cur >= fadeids[el.id].end)
            {
                fadeids[el.id].cur = fadeids[el.id].end;
            }
            
            WFX.Opacity.SetOpacity(element, fadeids[el.id].cur);
            fadeids[el.id].remain -+ fps;
            
            if (fadeids[el.id].cur == fadeids[el.id].end)
            {
                WFX.Threads.StopInterval(el.id);
                WFX.Threads.UnregisterThread(el.id);
                
                if(fadeids)
                {
                    delete fadeids[el.id];
                }
                
                if (oncomplete) oncomplete(el);
            }
            
        }, fps);
        
        setTimeout
        (
            function()
            {
                WFX.Threads.StartInterval(el.id);
            }, 
            delay || 0
        );
    };
    
    this.SetOpacity = function(element, value)
    {
        var intv = setInterval
        ( 
            function()
            {
                element = WFX.GetElement(element);
                 
                if (element)
                {
                    clearInterval(intv);
                }
                else
                {
                    return;
                }
                
                if (WFX.Browser.Name == Browsers.IE)
                {
                    value *= 100;
                }

                if (property == "filter")  
                {
                    var alpha = element.filters['DXImageTransform.Microsoft.alpha'] || element.filters.alpha;
                    
                    if (alpha)
                    {
                        alpha.opacity = value;
                    }
                    else
                    { 
                        element.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity="+value+")"; // Для того чтобы не затереть другие фильтры используем "+="
                    }
                }
                else 
                {
                    element.style[property] = value;
                }
        
            }, 
            100
        );
    };
	
};


/*

    WFX-Client Positioning

*/
function isBody(element)
{
	return (/^(?:body|html)$/i).test(element.tagName);
};

WFX.Position = new function()
{
    this.GetTopPosition = function(element)
    {
        element = WFX.GetElement(element);
        var y = 0;
        while (element && !isBody(element))
        {
			y += element.offsetTop;
			y += parseInt(element.borderTopWidth) || 0;

			element = element.offsetParent;
		}

        return y;
    };

    this.GetLeftPosition = function(element)
    {
        element = WFX.GetElement(element);
        var x = 0;
        while (element && !isBody(element))
        {
			x += element.offsetLeft;
			x += parseInt(element.borderLeftWidth) || 0;

			element = element.offsetParent;
		}

        return x;
    
      
    };
    
    this.GetWidth = function(element)
    {
        element = WFX.GetElement(element);
        
        return element.offsetWidth;
    };
    
    this.GetHeight = function(element)
    {
        element = WFX.GetElement(element);
        
        return element.offsetHeight;
    };
    // нужно переименовать в SetPositionUnder
    this.SetPosition = function(element, near, leftmargin, topmargin)
    {
        leftmargin = leftmargin || 0;
        topmargin = topmargin || 0;
        
        element = WFX.GetElement(element);
        near = WFX.GetElement(near);
       
	    element.style.left = (this.GetLeftPosition(near) + leftmargin) + 'px';
	    element.style.top = (this.GetTopPosition(near) + topmargin) + 'px';
    };
    
    this.Move = function(element, x, y)
    {
        if (isNaN(x) || isNaN(y))
        {
            return;
        }
        
        var element = WFX.GetElement(element);
        
        element.style.left = x + 'px';
        element.style.top = y + 'px';
    };
    
    this.MoveToCenter = function(element)
    {
        var element = WFX.GetElement(element);
        
        
        if (WFX.Browser.Name == Browsers.Chrome)
        {
            var y = document.documentElement.clientHeight / 2 - WFX.Sizes.GetHeight(element) / 2 + document.body.scrollTop;
		    var x = document.documentElement.clientWidth / 2 - WFX.Sizes.GetWidth(element) / 2 + document.body.scrollLeft;
        }
        else
        {
            var y = document.documentElement.clientHeight / 2 - WFX.Sizes.GetHeight(element) / 2 + document.documentElement.scrollTop;
		    var x = document.documentElement.clientWidth / 2 - WFX.Sizes.GetWidth(element) / 2 + document.documentElement.scrollLeft;
		}
		
		this.Move(element, x,y);
    };
    
    this.WatchForCenter = function(element)
    {
        var element = WFX.GetElement(element);
        this.MoveToCenter(element);
        WFX.Events.AddEventHandler("resize", window, function(e)
        {
            WFX.Position.MoveToCenter(element);    
        });  
    };

    var intervals = new Array();
    this.WatchForClientBegin= function(element)
    {
        var element = WFX.GetElement(element);
        
        if (WFX.Browser.Name == Browsers.Chrome)
        {
            this.Move(element, document.body.scrollLeft, document.body.scrollTop);
        }
        else
        {
            this.Move(element, document.documentElement.scrollLeft, document.documentElement.scrollTop);
        }
        
        intervals[element] = setInterval
        (
            function()
            {
                if (WFX.Browser.Name == Browsers.Chrome)
                {
                    WFX.Position.Move(element, document.body.scrollLeft, document.body.scrollTop);
                }
                else
                {
                    WFX.Position.Move(element, document.documentElement.scrollLeft, document.documentElement.scrollTop);
                }
                
            }, 100    
        );
    };
    
    this.StopWatchForClientBegin = function(element)
    {
        clearInterval(intervals[element]);
        intervals[element] = null;    
    };    
    
    this.MoveToCursor = function(element, e)
    {
        element = WFX.GetElement(element);
        
        if (WFX.Browser.Name == Browsers.Chrome)
        {
            element.style.top = (e.clientY + document.body.scrollTop) + "px";
            element.style.left = (e.clientX + document.body.scrollLeft) + "px";
        }
        else
        {
            element.style.top = (e.clientY + document.documentElement.scrollTop) + "px";
            element.style.left = (e.clientX + document.documentElement.scrollLeft) + "px";
        }
    
    }; 
};


WFX.Sizes = new function()
{
    this.GetWidth = function(element)
    {
        element = WFX.GetElement(element);
        
        return element.offsetWidth;
    };
    
    this.GetHeight = function(element)
    {
        element = WFX.GetElement(element);
        
        return element.offsetHeight;
    };
    
    this.SetWidth = function(element, value)
    {
        element = WFX.GetElement(element);
        if (WFX.Browser.Name == Browsers.Firefox)
		{
            element.style.width = value + "px";      
        }
        else
        {
            element.style.pixelWidth = value;  
        }      
    };
    
    this.SetHeight = function(element, value)
    {
        element = WFX.GetElement(element);  
        if (WFX.Browser.Name == Browsers.Firefox)
		{      
            element.style.height = value + "px";
        }
        else
        {
            element.style.pixelHeight = value;
        }
    };
     
    this.Expand = function(element)
    {
        element = WFX.GetElement(element);
        if (WFX.Browser.Name == Browsers.Chrome)
        {
            WFX.Position.Move(element,document.documentElement.scrollLeft,document.body.scrollTop);
        }
        else
        {
		    WFX.Position.Move(element,document.documentElement.scrollLeft,document.documentElement.scrollTop);
		}
		
		if (WFX.Browser.Name == Browsers.Firefox)
		{
		    element.style.width = (document.documentElement.clientWidth) + "px";
		    element.style.height = (document.documentElement.clientHeight) + "px"; 
		}
		else
		{
		    element.style.pixelWidth = (document.documentElement.clientWidth) ;
	        element.style.pixelHeight = (document.documentElement.clientHeight);
		}
    };
    
    var intervals = new Array();
    this.WatchForProportion = function(element, anchor, _min_height, _min_width)
    {
        element = WFX.GetElement(element);
        var clientWidth = document.documentElement.clientWidth;
        var clientHeight = document.documentElement.clientHeight;
        var elmHeight = parseInt(element.style.height);
        var elmWidth = parseInt(element.style.width);
        var pw = (elmWidth/clientWidth);
        var ph = (elmHeight/clientHeight);
        intervals[element] = setInterval
        (
            function()
            {
                var w = document.documentElement.clientWidth * pw;
                var h = document.documentElement.clientHeight * ph;
                WFX.Sizes.SetWidth(element, w);
                WFX.Sizes.SetHeight(element, h);
            }, 
            100
        ); 
    };
    
    this.StopWatchForProportion = function(element)
    {
        clearInterval(intervals[element]);
        intervals[element] = null;                
    };   
 
};


/*

    WFX-Client Controls Library

*/

WFX.Controls = new function()
{

};

/* AutoSuggestTextField */

WFX.Controls.AutoSuggestTextField = function(name, url, ableTypeNewString)
{
    this.Version = "2.0.0";
    
    var items = [];
    var id = name;
    this.WithoutClearButton = false;
	var list_height;
	var list_width;
    var able_to_type_new_string = ableTypeNewString || false;
        
    var req = new WFX.Ajax.Request(null, function(response)
    {
        items = response.split("|");
    });
    
    req.Get(url);
    
    var list_focused = false;
    
    var selected_id = null;
       
    var Fill = function(list, all)
    {
        list.innerHTML = "";
       
        var textbox = WFX.GetElement(id);
        
        for (var i=0; i<items.length; ++i)
        {
            if (!((items[i].toLowerCase()).indexOf((textbox.value).toLowerCase())) || all == true)
            {
                list.innerHTML += "<div id='li_"+id+"_"+i+"' style='padding:1px;' onmouseover=\"style.color='#ffffff'; style.background='#316ac5';\" onmouseout=\"style.color='#000000'; style.background='';\">"+items[i].replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'")+"</div>";
                
                WFX.Events.AddEventHandler('click', 'li_'+id+"_"+i, function(e)
                {
                    var lielm = WFX.Events.SrcElement(e);
                    var textlist = WFX.GetElement(id);
                    textlist.value = lielm.firstChild.nodeValue.replace(/\s+$/, ""); ;
                    list_focused = false;
                    WFX.HideElement('list_'+id);
                });
                
                WFX.Events.AddEventHandler('mouseover', 'li_'+id+"_"+i, function(e)
                {
                    var lielm = WFX.Events.SrcElement(e);
                    SelectListItem(lielm);
                });
            }
        }
    };
    
    var SelectListItem = function(element)
    {
        if (selected_id != null)
        {
            var selected = WFX.GetElement(selected_id);
            selected.style.color = "#000000";
            selected.style.background = "#ffffff";
        }  
        
        if (element != null)
        {
            var to_select = WFX.GetElement(element);
            
            to_select.style.color = "#ffffff";
            to_select.style.background = "#316ac5"; 
            
            selected_id = element.id;
        }  
        else
        {
            selected_id = null;
        } 
    };

    var ShiftUp = function(selected)
    {
        var list = WFX.GetElement('list_'+id);
        var summ = 0;
        
        var s = selected;
        
        while(s.previousSibling)
        {
            summ += s.previousSibling.offsetHeight;
            s = s.previousSibling;
        }

        if ( summ < list.scrollTop )
        {
            list.scrollTop = summ;
        }
    };
    
    var ShiftDown = function(selected)
    {
        var list = WFX.GetElement('list_'+id);
        var summ = 0;
        
        while(selected.previousSibling)
        {
            summ += selected.previousSibling.offsetHeight;
            selected = selected.previousSibling;
        }

        if ( ((parseInt(summ)-parseInt(list.scrollTop)) + selected.offsetHeight) > list.clientHeight )
        {
            list.scrollTop += (((parseInt(summ)-parseInt(list.scrollTop)) + selected.offsetHeight)-parseInt(list.clientHeight));
        }
    };
        
    var onKeyDown = function(e)
    {
        var key = WFX.Events.KeyCode(e);
        var list = WFX.GetElement('list_'+id);
        
        switch(key)
        {
            case WFX.KeyCodes.Enter:
            {
                if (WFX.IsVisible(list) == true)
                {
                    if (WFX.Browser.Name != Browsers.Opera)
                    {
                        if (selected_id != null)
                        {
                            var selected = WFX.GetElement(selected_id);
                            var textbox = WFX.Events.SrcElement(e);
                            textbox.value = selected.firstChild.nodeValue.replace(/\s+$/, ""); ;
                            list_focused = false;
                        }
                        WFX.HideElement(list);
                    }
                    else
                    {
                        alert("ИСПОЛЬЗУЙТЕ КЛАВИШУ TAB ДЛЯ ВЫБОРА ЭЛЕМЕНТА.");
                    }
                }
                WFX.Events.Stop(e);
                break;
            }
            case WFX.KeyCodes.Tab:
            {
                if (WFX.IsVisible(list) == true && selected_id != null)
                {
                    var selected = WFX.GetElement(selected_id);
                    var textbox = WFX.Events.SrcElement(e);
                    textbox.value = selected.firstChild.nodeValue;
                    list_focused = false;
                    WFX.HideElement(list);
                }
                WFX.Events.Stop(e);
                break;
            }
            case WFX.KeyCodes.Up:
            {
                if (WFX.IsVisible(list) == true)
                {
                    if (selected_id != null)
                    {
                        var selected = WFX.GetElement(selected_id);
                        if (selected.previousSibling != null)
                        {
                            SelectListItem(selected.previousSibling);
                            selected = WFX.GetElement(selected_id);
                            ShiftUp(selected);
                        }
                    }
                }
                WFX.Events.Stop(e);
                break;
            }
            case WFX.KeyCodes.Down:
            {
                if (WFX.IsVisible(list) == true)
                {
                    if (selected_id != null)
                    {
                        var selected = WFX.GetElement(selected_id);
                        if (selected.nextSibling != null)
                        {
                            SelectListItem(selected.nextSibling);
                            selected = WFX.GetElement(selected_id);
                            
                            ShiftDown(selected);
                        }
                    }
                    else
                    {
                        SelectListItem(list.firstChild);
                    }
                }
                else
                {
                    onBtnClick(e);
                }
                
                WFX.Events.Stop(e);
                break;
            }
            case WFX.KeyCodes.Esc:
            {
                WFX.HideElement(list);
                break;
            }
        }
    };
    
    var onKeyUp = function(e)
    {
        var key = WFX.Events.KeyCode(e);
        switch(key)
        {
            case WFX.KeyCodes.Esc:
            case WFX.KeyCodes.Tab:
            case WFX.KeyCodes.Enter:
            case WFX.KeyCodes.Up:
            case WFX.KeyCodes.Down:
            {
                return;
            }
            default:
            {
                var elm = WFX.Events.SrcElement(e);
                if (!able_to_type_new_string)
                {
                    var empty = false;
                    for (var i=0; i<items.length; ++i)
                    {
                        if (((items[i].toLowerCase()).indexOf((elm.value).toLowerCase())) >= 0)
                        {
                           empty = false;
                           break;
                        }
                        empty = true;
                    }
                    if (empty)
                    {
                        elm.value = elm.value.substr(0,(elm.value.length-1));
                    }
                }
                SelectListItem(null);
                
                var list = WFX.GetElement("list_"+id); 
                var elm1 = WFX.GetElement(id);
                
                var elm_y = WFX.Position.GetTopPosition(elm);

                if (document.documentElement.clientHeight - (elm_y - document.documentElement.scrollTop) > (list_height+WFX.Position.GetHeight(elm1)) )
                {
                    WFX.Position.SetPosition(list, elm1, ((WFX.Browser.Name == Browsers.IE)?1:0), WFX.Position.GetHeight(elm1)+1);
                }   
                else
                {
                    if (elm_y < list_height)
                    {
                        WFX.Position.SetPosition(list, elm1, ((WFX.Browser.Name == Browsers.IE)?1:0), WFX.Position.GetHeight(elm1)+1);
                    }
                    else
                    {
                        WFX.Position.SetPosition(list, elm1, ((WFX.Browser.Name == Browsers.IE)?1:0), -(list_height)); 
                    }
                }
                    
                if (elm.value.length >= 1)
                {
                    Fill(list, false);
                }
                else
                {
                    Fill(list, true);
                }               
                
                WFX.ShowElement(list);
            }
        }
    };
        
    var onBtnClick = function(e)
    {
    	SelectListItem(null);
        
        var elm = WFX.GetElement(id);
        var list = WFX.GetElement("list_" + id); 
        
        var elm_y = WFX.Position.GetTopPosition(elm);

        if (document.documentElement.clientHeight - (elm_y - document.documentElement.scrollTop) > (list_height+WFX.Position.GetHeight(elm)) )
        {
            WFX.Position.SetPosition(list, elm, ((WFX.Browser.Name == Browsers.IE)?1:0), WFX.Position.GetHeight(elm)+1);
        }   
        else
        {
            if (elm_y < list_height)
            {
                WFX.Position.SetPosition(list, elm, ((WFX.Browser.Name == Browsers.IE)?1:0), WFX.Position.GetHeight(elm)+1);
            }
            else
            {
                WFX.Position.SetPosition(list, elm, ((WFX.Browser.Name == Browsers.IE)?1:0), -(list_height)); 
            }
        }
        
        Fill(list, true);
        list_focused = false;
        WFX.ShowHideElement(list);
    };
    
    var onBlur = function(e)
    {
        var intv = setInterval
        ( 
            function()
            {
                clearInterval(intv);
                if (list_focused == false)
                {
                    WFX.HideElement("list_"+id);
                }
            },
            100
        );
    }; 
    
    var onBtnBlur = function(e)
    {
        onBlur(e);
    }; 
    
    var onFocus = function(e)
    {
        var elm = WFX.Events.SrcElement(e);
		var list = WFX.GetElement("list_"+id); 
        if (elm.value.length > 1)
        { 
            var elm_y = WFX.Position.GetTopPosition(elm);

			if (document.documentElement.clientHeight - (elm_y - document.documentElement.scrollTop) > (list_height+WFX.Position.GetHeight(elm)) )
            {
                WFX.Position.SetPosition(list, elm, ((WFX.Browser.Name == Browsers.IE)?0:0), WFX.Position.GetHeight(elm));
            }   
            else
            {
                if (elm_y < list_height)
                {
                    WFX.Position.SetPosition(list, elm, ((WFX.Browser.Name == Browsers.IE)?0:0), WFX.Position.GetHeight(elm));
                }
                else
                {
                    WFX.Position.SetPosition(list, elm, ((WFX.Browser.Name == Browsers.IE)?0:0), -(list_height)); 
                }
            }
            Fill(list, true);

            WFX.ShowElement(list);
        }
        list_focused = false;
    }; 
    
    var onListMouseDown = function(e)
    {
        list_focused = true;
    };
    
    var onListMouseUp = function(e)
    {
        list_focused = false;
    };
    
    var onClearClick = function(e)
    {
        var field = WFX.GetElement(id);
        field.value = "";
        field.focus();
    };
    
    WFX.Events.AddEventHandler('keyup', id, onKeyUp);
    WFX.Events.AddEventHandler('keydown', id, onKeyDown);
    WFX.Events.AddEventHandler('blur', id, onBlur);
    WFX.Events.AddEventHandler('focus', id, onFocus);
    WFX.Events.AddEventHandler('click', 'btn_'+id, onBtnClick);
    WFX.Events.AddEventHandler('blur', 'btn_'+id, onBtnBlur);
    
    WFX.Events.AddEventHandler('mousedown', 'list_'+id, onListMouseDown);
    WFX.Events.AddEventHandler('mouseup', 'list_'+id, onListMouseUp);
    
    WFX.Events.AddEventHandler('click', 'clear_'+id, onClearClick);
     
    this.Build = function(width, height)
    {
        var out = "";
		list_height = height || 100;
		list_width = width || 200;
        out += "<div style='width:"+list_width+"px; display:inline; '><table border='0' cellpadding='0' cellspacing='0' style='border-collapse:collapse;'><tr>";
        out += "<td><input autocomplete='off' style='margin-bottom:1px; border-width:1px; border-color:#898c95; border-style:solid;width:"+(list_width-((this.WithoutClearButton == true)?19:38))+"px;' type='text' id='"+id+"' name='"+id+"' /></td>";
        if (this.WithoutClearButton == true)
        {
           out += "<td><input id='btn_"+id+"' type='button' style='width:19px; font-size:9px; margin-bottom:1px; padding-left:1px;' value='V' /></td>";
        }
        else
        {
           out += "<td><input id='btn_"+id+"' type='button' style='width:19px; font-size:9px; margin-bottom:1px; padding-left:1px;' value='V' /></td>";
           out += "<td><input id='clear_"+id+"' type='button' style='width:19px; font-size:9px; margin-bottom:1px; padding-left:2px;' value='X' /></td>";
        }
        out += '</tr></table><div id="list_'+id+'" style="z-index:1000; cursor:default; overflow:auto; display:none; width:'+((WFX.Browser.Name == Browsers.Opera)?(list_width+6):((WFX.Browser.Name == Browsers.Firefox)?(list_width+2):(list_width+1)))+'px; height:'+list_height+'px; background-color:#FFFFFF; border-style:solid; border-width:1px; border-color:#7f9db9; position:absolute;"></div>';
        out += "</div>";
    
        return out;
    }; 
        
    this.Show = function(width, height)
    {  
        document.write(this.Build(width, height));
    };
    
    this.SetValue = function(value)
    {
          var field = WFX.GetElement(id);
          field.value = value.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'");
    };
    
    this.GetValue = function()
    {
        var hidden = WFX.GetElement(id);
        return hidden.value;  
    };
    
    this.GetName = function()
    {
        return id;  
    };
    
};

/* CheckBox */

WFX.Controls.CheckBox = function(name, label) 
{ 
	this.Version = "1.0.0";
	var id = name;
	
	var label = label;
	var value = value;
	
	this.Build = function() 
	{
		var out = "";
		out += "<input style='margin-bottom:1px;' type='checkbox' value='1' id='" + id + "' name='" + id + "' /><label for='"+id+"'>"+label+"</label>";
		return out;
	};
    
	this.Show = function() 
	{
		document.write(this.Build());
	};

	this.SetValue = function(value) 
	{
		var check = WFX.GetElement(id);
		
		if (value == 1 || value == "1")
		{
		    check.checked = 1;
		}
		else
		{
		    check.checked = 0;
		}
	};

	this.GetValue = function() 
	{
		var check = WFX.GetElement(id);
		return (check.checked)?1:0;
	};
	
	this.Disable = function()
	{
	    var check = WFX.GetElement(id);
	    check.setAttribute("disabled", "disabled");
	};
	
	this.Enable = function()
	{
	    var check = WFX.GetElement(id);
	    check.removeAttribute("disabled");
	};
	
	this.SetTitle = function(title)
	{
	    var check = WFX.GetElement(id);
	    check.setAttribute("title", title);
	};

	this.GetName = function() 
	{
		return id;
	};

};

/* TextField */

WFX.Controls.TextField = function(name, password, digitonly) 
{
	this.Version = "1.0.0";
	var id = name;
	
	password = password || false;
	digitonly = digitonly || false;
	
	this.Build = function(width) 
	{
	    width = width || 100;
		var out = "";
		out =  "<table border='0' cellspacing='0' cellpadding='0' style='border-collapse:collapse;' width='" + (width) + "'><tr><td width='"+(width - 19)+"px'>";
		out += "<input autocomplete='off' style='margin-bottom:1px; border-width:1px; border-color:#898c95; border-style:solid; width:" + (width - 19) + "px;' type='"+((password == true)?("password"):("text"))+"' id='" + id + "' name='" + id + "' /></td><td><input id='btn_" + id + "' type='button' style='width:19px; font-size:9px; margin-bottom:1px; padding-left:2px;' value='X' />";
		out += "</td></tr></table>";
        
        if (digitonly)
        {
            WFX.Events.AddEventHandler("keypress", id, function(e)
		    {
			    var key = WFX.Events.KeyCode(e);
			    var keychar = String.fromCharCode(key);

			    if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27))
			    {
				    return true;
			    } 
			    else if ( ("0123456789.").indexOf(keychar) > -1)
			    {
				    return true;
			    }
			    else if (e && (keychar == ".")) 
			    {
				    WFX.Events.SrcElement(e).focus();
				    WFX.Events.Stop(e);
				    return false;
			    }
			    else
			    {
				    WFX.Events.Stop(e);
				    return false;
			    }
		    });
		}
		
		return out;
	};
    
	this.Show = function(width) 
	{
		document.write(this.Build(width));
	};

	this.SetValue = function(value) 
	{
		var field = WFX.GetElement(id);
		field.value = value.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'");
	};

	var onBtnClick = function(e) 
	{
		var field = WFX.GetElement(id);
		field.value = "";
		field.focus();
	};

	WFX.Events.AddEventHandler('click', 'btn_' + id, onBtnClick);

	this.GetValue = function() 
	{
		var hidden = WFX.GetElement(id);
		return hidden.value;
	};

	this.GetName = function() 
	{
		return id;
	};

};

WFX.Controls.StaticMenu = function(name, select_ind)
{

    this.Version = "1.0.0";
    this.select_ind = select_ind;
    var id = name;
    var items = new Array();
    
    this.AddItem = function(title, icon, url)
    {
        var arr = new Array();
        arr["title"] = title;
        arr["url"] = url || null;
        arr["icon"] = icon || null;
        items[items.length] = arr;
    };
    
    var usecookie = true;
    this.DisableCookie = function()
    {
        usecookie = false;
    };
    
    this.Build = function()
    {
        var item_divs = "";
        var selid = null;
        if (select_ind > -1)
        {
            selid = "item_"+id+"_"+(select_ind);
        }
        else if (usecookie == true)
        {
            selid = WFX.Cookie.get(id + "_selected_item");
        }
        for (var i=0; i<items.length; i++)
        {
            var curid = "item_"+id+"_"+(i);
            var img = ((items[i]["icon"] != null)?("<img style='float:left; position:relative; bottom:2px;' src='"+items[i]["icon"]+"' />"):("&nbsp;"));
            
            item_divs += "<div  id='item_"+id+"_"+(i)+"' style='cursor:default; margin-right:5px; padding:5px; white-space:nowrap; margin-left:1px; margin-right:1px; margin-top:2px; "+ ((curid == selid)?("background-color:"+"#316ac5;"+" color:"+"#FFFFFF;"+" "):("")) +" '"+  ((curid != selid)?(" onmouseover=\"this.style.background='"+"#316ac5"+"'; this.style.color='"+"#FFFFFF"+"'; WFX.Opacity.Cycle('"+(curid)+"', 1, 0.5, 6500, 0);\" onmouseout=\"WFX.Opacity.InvokeStop('"+(curid)+"');this.style.background=''; this.style.color='"+"#000000"+"';\""):("")) +"'>";
            item_divs += img + "&nbsp;" + items[i]["title"];
            item_divs += "</div>";
        }
        
        return "<div>" + item_divs + "</div>";
    }; 
        
    this.Show = function()
    { 
    var c = this.Build();
    
        document.write(c);
        
        for (var i=0; i<items.length; i++)
        {
            WFX.Events.AddEventHandler('click', 'item_'+id+'_'+(i), items[i]["url"]);
        }
        
    };

   
	
	
};

/* RollUpMenu */

WFX.Controls.RollupMenu = function(name, nocollapse, select_ind)
{
    var nocollapse = nocollapse;

    this.Version = "1.0.0";
    this.select_ind = select_ind;
    var id = name;
    var items = new Array();
    
    this.AddItem = function(title, icon, url)
    {
        var arr = new Array();
        arr["title"] = title;
        arr["url"] = url || null;
        arr["icon"] = icon || null;
        items[items.length] = arr;
    };
    
    var usecookie = true;
    this.DisableCookie = function()
    {
        usecookie = false;
    };
    
    this.Build = function()
    {
        var item_divs = "";
        var selid = null;
        if (select_ind != null)
        {
            selid = "item_"+id+"_"+(select_ind);
        }
        else if (usecookie == true)
        {
            selid = WFX.Cookie.get(id + "_selected_item");
        }
        for (var i=0; i<items.length; i++)
        {
            var curid = "item_"+id+"_"+(i+1);
            item_divs += "<div  id='item_"+id+"_"+(i+1)+"' style='cursor:default; font-size:12px; margin:2px; "+ ((curid == selid)?("font-weight:bold; background-color:"+"#316ac5;"+" color:"+"#FFFFFF;"+" "):("")) +" '"+  ((curid != selid)?(" onmouseover=\"this.style.background='"+"#316ac5"+"'; this.style.color='"+"#FFFFFF"+"'; WFX.Opacity.Cycle('"+curid+"', 1, 0.3, 2000, 0);\" onmouseout=\"WFX.Opacity.InvokeStop('"+curid+"');this.style.background=''; this.style.color='"+"#000000"+"';\""):("")) +"'>";         
            item_divs += "<table border='0' cellpadding='0' cellspacing='0' style='border-collapse:collapse;'>";
	        item_divs +=     "<tr>";
	        var img = ((items[i]["icon"] != null)?("<img src='"+items[i]["icon"]+"' />"):("&nbsp;"));
    	    item_divs +=         ("<td rowspan='3' "+((items[i]["icon"] != null)?(""):("width='22px'"))+">&nbsp;"+img+"&nbsp;"+"</td>");
            item_divs +=         "<td height='5px'></td>";
            item_divs +=     "</tr>";
            item_divs +=     "<tr>";
    	    item_divs +=         "<td height='12px'>"+items[i]["title"]+"</td>";
            item_divs +=     "</tr>";
            item_divs +=     "<tr>";
    	    item_divs +=         "<td height='5px'></td>";
            item_divs +=     "</tr>";
            item_divs += "</table>";
            item_divs += "</div>";
            
            item_divs += "<div style='height:2px;'></div>";
        }
        var out = "";
        out += "<table border='0' cellpadding='0' cellspacing='0' id='main_"+id+"' style='width:11px; display:inline;'>";
            out += "<tr>";
                out += "<td valign='top' id='content_"+id+"'>";
                out +=  rollupmenu_main_template.replace(/#items#/, item_divs);
                out += "</td>";
                out += "<td id='"+id+"' valign='top' style='width:10px;' >";
                out +=  rollupmenu_collapser_template;
                out += "</td>";
            out += "</tr>";
        out += "</table>";
    
        return out;
    }; 
        
    this.Show = function()
    { 
        document.write(this.Build());
        
        for (var i=0; i<items.length; i++)
        {
            WFX.Events.AddEventHandler('click', 'item_'+id+'_'+(i+1), items[i]["url"]);
        }
        
        var content = WFX.GetElement("content_"+id);

        if (WFX.Cookie.get("collapser_"+id) == 1 || WFX.Cookie.get("collapser_"+id) == null)
        {
            WFX.ShowElement(content);
        }
        else
        {
            WFX.HideElement(content);
        }  
        
    };

    var onColapserClick = function(e)
    {
        var content = WFX.GetElement("content_"+id);
        
        if (WFX.Cookie.get("collapser_"+id) == 1 || WFX.Cookie.get("collapser_"+id) == null)
        {
            WFX.Cookie.set("collapser_"+id, "0", 1);
            WFX.HideElement(content);
        }
        else
        {
            WFX.Cookie.set("collapser_"+id, "1", 1);
            WFX.ShowElement(content);
        }  
    };
	
	this.Close = function()
    {
    	var content = WFX.GetElement("content_" + id);

		WFX.Cookie.set("collapser_" + id, "0", 1);
		WFX.HideElement(content);
    	
    };

    this.Open = function() {
    	var content = WFX.GetElement("content_" + id);
    	
		WFX.Cookie.set("collapser_" + id, "1", 1);
		WFX.ShowElement(content);
    };
	
    if (nocollapse == false)
    {
        WFX.Events.AddEventHandler('click', id, onColapserClick);
    }
};

/* Toolbar */
WFX.Controls.Toolbar = function(name, background, color, bgcolor, select_ind)
{
    var bg = background;
    var color = color;
    var b_color = bgcolor;
    this.Version = "1.0.0";
    this.select_ind = select_ind;
    var id = name;
    var items = new Array();
    
    this.AddItem = function(title, image, disabled_image, showtitle, handler)
    {
        var arr = new Array();
        arr["title"] = title;
        arr["image"] = image;
        arr["image2"] = disabled_image;
        arr["showtitle"] = showtitle;
        arr["handler"] = handler;
        arr['disabled'] = 0;
        arr['allow'] = 1;
        items[items.length] = arr;
    };
    
    this.AllowEnable = function(index, val)
    {
        if (index==0) index = 1;
        items[index-1]['allow'] = val;
    };
    
    this.DisableItem = function(index)
    {
        if (index==0) index = 1;
        
        var intv = setInterval(function()
        {
            var it = WFX.GetElement("item_"+id+"_"+(index-1));
            
            if (it == null)
            {
                return;
            }
            else
            {
                clearInterval(intv);
            }
            
            it.firstChild.firstChild.nextSibling.firstChild.nextSibling.firstChild.src = items[index-1]['image2'];
            items[index-1]['disabled'] = 1;
        },
        100);
        
        
        
    };
    
    this.EnableItem = function(index)
    {
        if (index==0) index = 1;

        if (items[index-1]['allow'] == 1)
        {
            var it = WFX.GetElement("item_"+id+"_"+(index-1));
            it.firstChild.firstChild.nextSibling.firstChild.nextSibling.firstChild.src = items[index-1]['image'];
            items[index-1]['disabled'] = 0;
        }
    };
    
    this.AddOnRun = function(title, image, disabled_image, showtitle, handler)
    {
        var arr = new Array();
        arr["title"] = title;
        arr["image"] = image;
        arr["image2"] = disabled_image;
        arr["showtitle"] = showtitle;
        arr["handler"] = handler;
        arr['disabled'] = 0;
        arr['allow'] = 1;
        items[items.length] = arr;
        
        var i = (items.length-1);
        
        var chmid = WFX.GetElement('chm'+id);
        
        var curid = "item_"+id+"_"+i;
        
        var td = document.createElement("td");
        td.setAttribute("width", "1px");
        var cols = ((items[i]["showtitle"]==1)?5:3);
	    var out = "<table title='"+items[i]["title"]+"' id='item_"+id+"_"+i+"' border='0' cellpadding='0' cellspacing='0' style='cursor:default;' onmouseover=\"this.style.background='"+b_color+"';\"";
	        out += "onmouseout=\"this.style.background=''; \">";
	            out += "<tr>";
                    out +="<td colspan='5' height='2px'></td>";
                out += "</tr>";
                out += "<tr>";
                    out += "<td style='font-size:10px;'>&nbsp;</td>";
                    out += "<td >"+ ((items[i]["image"].length!=0)?("<img title='"+items[i]["title"]+"' align='middle' src='"+items[i]["image"]+"' />"):("")) +"</td>";
                    if (items[i]["showtitle"]==1)
                    {
                        out += "<td style='font-size:10px;'>&nbsp;</td>";
                        out += "<td valign='middle'>"+ ((items[i]["showtitle"]==1)?("<span style='font-size:12px; white-space:nowrap; color:"+color+";'>"+(items[i]["title"])+"</span>"):(""))     +"</td>";
                    }
                    out += "<td style='font-size:10px;'>&nbsp;</td>";
                out += "</tr>";
                out += "<tr>";
                    out +="<td colspan='5' height='2px'></td>";
                out += "</tr>";
            out += "</table>";
        td.innerHTML = out;
       // chmid.appendChild(td);
        
        chmid.insertBefore(td, chmid.firstChild);
        
        WFX.Events.AddEventHandler('click', 'item_'+id+'_'+i, items[i]["handler"]);
    };
    
    this.RemoveOnRun = function(i)
    {
        //if (i > items.length-1)
        //{
        //    return;
        //}
        //alert('item_'+id+'_'+i);
        WFX.Events.RemoveEventHandler('click', 'item_'+id+'_'+i, items[i]["handler"]);
        
        var chmid = WFX.GetElement('chm'+id);
        var el = WFX.GetElement('item_'+id+'_'+i);
        chmid.removeChild( el.parentNode );
        
        
        
        var temp = new Array();
        
        for(var ii=0; ii < items.length; ++ii)
        {
            if (ii != i)
            {
                temp[temp.length] = items[ii];
            }
        }
        
        delete items[i];
        
        items = temp;
        
    };
    
    this.GetCount = function()
    {
        return items.length;
    };
    
    this.Clear = function()
    {
        while(this.GetCount() > 0)
        {
            this.RemoveOnRun(this.GetCount()-1);
        }
        var chmid = WFX.GetElement('chm'+id);
    };
    
    this.Build = function()
    {
        var out = "<table border='0' cellpadding='0' cellspacing='4' "+((bg.length!=0)?("style='background-image:url("+bg+"); background-repeat:repeat-x;"):(""));
            out += "background-position:top; background-repeat:repeat-x; width:100%; height:30px;'>";
                out += "<tr id='chm"+id+"'>";
                for (var i =0; i<items.length; i++)
                {
                    var cols = ((items[i]["showtitle"]==1)?5:3);
                	out += "<td width='1px'>";
                	    out += "<table title='"+items[i]["title"]+"' id='item_"+id+"_"+i+"' border='0' cellpadding='0' cellspacing='0' style='cursor:default;' ";
                	    if (items[i]["title"].length > 0)
                	    {
                	        out += "onmouseover=\"this.style.background='"+b_color+"';\" ";
                	        out += "onmouseout=\"this.style.background=''; \">";
                        }
                            out += "<tr>";
                                out +="<td colspan='"+cols+"' height='2px'></td>";
                            out += "</tr>";
                            out += "<tr>";
                                out += "<td style='font-size:10px;'>&nbsp;</td>";
                                out += "<td >"+ ((items[i]["image"].length!=0)?("<img title='"+items[i]["title"]+"' align='middle' src='"+items[i]["image"]+"' />"):("")) +"</td>";
                                if (items[i]["showtitle"]==1)
                                {
                                    out += "<td style='font-size:10px;'>&nbsp;</td>";
                                    out += "<td valign='middle'>"+ ((items[i]["showtitle"]==1)?("<span style='font-size:12px; white-space:nowrap; color:"+color+";'>"+(items[i]["title"])+"</span>"):(""))     +"</td>";
                                }
                                out += "<td style='font-size:10px;'>&nbsp;</td>";
                            out += "</tr>";
                            out += "<tr>";
                                out +="<td colspan='"+cols+"' height='2px'></td>";
                            out += "</tr>";
                        out += "</table>";
                    out += "</td>";
                 }
                 out+="<td>&nbsp;</td>";
                 out += "</tr>";
             out += "</table>";
        return out;
    };
    
    this.Show = function()
    { 
        var mydiv =  WFX.GetElement(id);
        document.write(this.Build());
        for (var i=0; i<items.length; i++)
        {
            WFX.Events.AddEventHandler('click', 'item_'+id+'_'+i, function(e)
            {
                var el = WFX.Events.GetElement(e);

                var id_item = 0;
                if (el.tagName == "IMG")
                {
                    id_item = el.parentNode.parentNode.parentNode.parentNode.id;
                }
                else if (el.tagName == "SPAN")
                {
                    id_item = el.parentNode.parentNode.parentNode.parentNode.id;
                }
                else
                {
                    id_item = el.parentNode.parentNode.parentNode.id;
                }
                
                var index = id_item.split("_")[id_item.split("_").length-1];
                
                if(items[index]['disabled'] == 0)
                {
                    items[index]["handler"](e);
                }
               
            });
        }
    };
   
};

/* HoverMenu */
WFX.Controls.HoverMenu = function(name, color, hcolor, bgcolor, select_ind)
{
    var color = color;
    var b_color = bgcolor;
    var h_color = hcolor;
    var select_ind = select_ind;
    this.Version = "1.0.0";
    var id = name;
    var items = new Array();
    
    var usecookie = true;
    this.DisableCookie = function()
    {
        usecookie = false;
    };
    
    this.AddItem = function(title, url, icon)
    {
        var arr = new Array();
        arr["title"] = title;
        arr["url"] = url;
        arr["icon"] = icon;
        items[items.length] = arr;
    };
    
    this.Build = function()
    {
        var out = "<table border='0' cellpadding='0' cellspacing='2' ";
            out += "style='width:100%; height:22px;'>";
                out += "<tr>";
                
                var selid = null;
                
                if (select_ind != null)
                {
                    var selid = "item_"+id+"_"+(select_ind-1);
                }
                else if (usecookie == true)
                {
                    var selid = WFX.Cookie.get(id+"_selected_item");
                }
                for (var i =0; i<items.length; i++)
                {
                    var curid = "item_"+id+"_"+i;
                	    out += "<td width='1px'>";
                	        out += "<table height='20px' id='"+curid+"' border='0' cellpadding='0' cellspacing='0' style='cursor:default; "+((selid == curid)?("font-weight:bold; background-color:"+bgcolor+";"):(""))+"' "+ ((selid == curid)?(""):(" onmouseover=\"this.style.background='"+b_color+"'; WFX.GetElement('toolbar_"+id+"_itemtext_"+i+"').style.color='"+h_color+"';\""))    +" ";
                	        out += "  "+  ((selid == curid)?(""):("onmouseout=\"this.style.background=''; WFX.GetElement('toolbar_"+id+"_itemtext_"+i+"').style.color='"+color+"'; \""))     +">";
                                out += "<tr>";
                                    out += "<td style='font-size:10px;'>&nbsp;</td>";
                                    
                                    if (items[i]["icon"].length != 0)
                                    {
                                        out += ("<td style='font-size:10px;'><img src='"+(items[i]["icon"])+"' /></td>");
                                        out += "<td style='font-size:10px;'>&nbsp;</td>";
                                    }
                                    out += "<td valign='middle'><span onmouseover=\"WFX.Opacity.Cycle('"+curid+"', 1, 0.2, 1000, 0);\" onmouseout=\"WFX.Opacity.InvokeStop('"+curid+"');\" id='toolbar_"+id+"_itemtext_"+i+"' style='font-size:12px;"+  ((selid == curid)?("color:"+hcolor+";"):("color:"+color+";"))  +"'>"+(items[i]["title"].replace(/ /g, "&nbsp;"))+"&nbsp;</span></td>";
                                    out += "<td style='font-size:10px;'>&nbsp;</td>";
                                out += "</tr>";
                            out += "</table>";
                        out += "</td>";
                 }
                 out+="<td>&nbsp;</td>";
                 out += "</tr>";
             out += "</table>";
        return out;
    };
    
    this.Show = function()
    { 
        var mydiv =  WFX.GetElement(id);
        document.write(this.Build());
       
        for (var i=0; i<items.length; i++)
        {
            WFX.Events.AddEventHandler('click', 'item_'+id+'_'+i, items[i]["url"]);
        }
        
    };
   
};



/* MultiStringField */

WFX.Controls.MultiStringField = function(name, url, withnew)
{
    this.Version = "1.0.1";
    
    var items = [];
    this.WithoutClearButton = false;
    var new_items = [];
    var id = name;
    var chlist_height;
    var chlist_width;
    var selected_id = null;
    var ready = false;
    var withnew = withnew || false;
    var upload_url = url;
    var init_url = null;
    WFX.Globals.Attach(id, this);
    
    
    var _Clear = function() 
    {
		var list = WFX.GetElement("chlist_container_" + id);

		while (list.childNodes.length > 0) 
		{
			list.removeChild(list.firstChild);
		}

		selected_id = null;
	};
    var busy = false;
    var req = new WFX.Ajax.Request
    (
        function()
        {
            ready = false;
            busy = true;
        }, 
        
        function(response) 
        {
            if(ready == true)
            {
                return;
            }
            
            if (WFX.Strings.Trim(response).length == 0)
            {
                ready = true;
                return;
            }
            
		    items = [];
		    new_items = [];
		    new_items[0] = 1;
		    if (response.length > 0) 
		    {
			    var temp_items = response.split("|");
			    for (var i = 0; i < temp_items.length; i++) 
			    {
				    items[i] = new Array();
				    items[i][0] = temp_items[i].split(":")[0];
				    items[i][1] = temp_items[i].split(":")[1];
			    }
		    }
		    ready = true;
	    }
	);
	
    this.Reload = function(url)
    {
        
        req.Get(url);
        
        var intv = setInterval
        ( 
            function()
            {
                if (ready == false)
                {
                    return;
                }
                else
                {
                    clearInterval(intv);
                }
                _Clear();
                _Fill();
            }, 
            100
        );
        
    };
    
    this.Load = function(url)
    {
        var clist = WFX.GetElement("chlist_container_"+id);
        
        if (clist.childNodes.length > 1)
        {
            return;
        }
        init_url = url;
        this.Reload(url);  
        
    };
    
    
     
    var reqst = new WFX.Ajax.Request(null, function(response)
	{
		var msg = response.split("::");

		if (msg.length > 1)
		{
			msg = msg[1];
		}

		switch (parseInt(response))
		{
			case 200:
				{
					var mybtn = WFX.GetElement("btn_ok_" + id);
					
					WFX.HideElement(mybtn);
					var $this = WFX.Globals.GetObject(name);
					$this.Reload(init_url);  
					break;
				}

			case 500:
				{
					alert("Неопознанная ошибка сервера.\n" + msg);
					break;
				}

			case 501:
				{
					alert("Ошибка базы данных.\n" + msg);
					break;
				}

			case 502:
				{
					alert("Ошибка ввода данных.\n" + msg);
					break;
				}

			default:
				{
					alert("Неопознанная ошибка.\n" + msg);
				}
		}


	});  
    
    var _Fill = function()
    {
        var container = WFX.GetElement("chlist_container_"+id);
        
        if (container.childNodes.length > 1)
        {
            return;
        }
        
        if (withnew == true)
        {
           var div = document.createElement("div");
           div.innerHTML = '<input disabled="disabled" type="checkbox"	id="check_new_'+id+'_1" /><input autocomplete="off" type="text" id="title_new_'+id+'_1" style="width:'+(chlist_width-45)+'px;" />';
           container.appendChild(div);
           
           WFX.Events.AddEventHandler('keyup', 'title_new_'+id+"_1", onNewTitleKeyUp);
           WFX.Events.AddEventHandler('keydown', 'title_new_'+id+"_1", onNewTitleKeyDown);
           
           WFX.Events.AddEventHandler('focus', ('title_new_'+id+"_1"), function(e)
            {
                if (selected_id != null)
                {
                    var curcheck = WFX.GetElement(selected_id);
                    curcheck.parentNode.style.color = "#000000";
                    curcheck.parentNode.style.background = "#ffffff";
                    selected_id = null;
                }
              });
        
        }
      
        for (var i=0; i<items.length; ++i)
        {
            if (items[i].length == 0)
            {
                continue;
            }
            
            var div = document.createElement("div");
            div.innerHTML = '<input type="checkbox" id="'+id+"_ch_"+i+'" /><label for="'+id+"_ch_"+i+'" id="'+id+"_title_"+i+'"	>'+items[i][1].replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'")+'</label><input type="hidden" id="' + id + '_' + i + '" value="' + items[i][0] + '"/>';
            
            container.appendChild(div);
                                   
            WFX.Events.AddEventHandler('mousedown', (id+"_ch_"+i), function(e)
            {
                var curchek = WFX.Events.SrcElement(e);
                SelectListItem(curchek.parentNode);
            });
            WFX.Events.AddEventHandler('mousedown', (id+"_title_"+i), function(e)
            {
                var curchek = WFX.Events.SrcElement(e);
                SelectListItem(curchek.parentNode);
            });
            WFX.Events.AddEventHandler('click', (id + "_ch_" + i), function(e) {
				var hidden = WFX.GetElement(id);
				var elstrings = CollectCheckedIds();
				hidden.value = elstrings.join("|");
			});
			
        }
        var hidden = WFX.GetElement(id);
		var temp_arr1 = [];
		if (hidden.value != "")
		    temp_arr1 = hidden.value.split("|");
		var for_check = [];
		for (var i =0; i < temp_arr1.length ;i++)
		{
		    if (temp_arr1[i].substr(0,1) == "#")
		    {
		        for_check[i] = temp_arr1[i].substr(1);
		    }
		}
		
		var cur = container.firstChild;
		while(cur)
		{
            if (cur.firstChild.nextSibling.id.split("_")[1] == "new")
            {
                if (cur.nextSibling == null)
                {
                    break;
                }
                else
                {
                    cur = cur.nextSibling;
                    continue;
                }
            }
            else
            {
                for (var i=0; i< for_check.length; i++)
                {
                    if (cur.firstChild.nextSibling.innerHTML == for_check[i])
                    {
                        var for_new_id = [];
                        for_new_id = hidden.value.split("|");
                        for (var j=0; j< for_new_id.length; j++)
                        {
                            if (("#"+for_check[i]) == for_new_id[j])
                            {
                                for_new_id[j] = cur.firstChild.nextSibling.nextSibling.value;
                            }
                        }
                        hidden.value = for_new_id.join("|");
                    }
                }
                if (cur.nextSibling == null)
                {
                    break;
                }
                else
                {
                    cur = cur.nextSibling;
                }
            }
		}
		
		busy = false;
    };
    
    var ReadSelection = function()
    {
        var hidden = WFX.GetElement(id);
        var container = WFX.GetElement("chlist_container_"+id);
        var cur = container.firstChild.nextSibling;
        var array = hidden.value.split('|');
        
        for (var i=0; i<items.length; ++i)
        {
            var checkbox_of_cur_item = WFX.GetElement(id+'_ch_'+i);
            var check_new_id = cur.firstChild.nextSibling.id.split("_");
		    var title_of_cur_item = WFX.GetElement(id+"_"+i);
            
           // if(check_new_id[1] == "new")
            //{
			//	if (cur.nextSibling != null)
			//	{
			//		cur = cur.nextSibling;
			//	}
			//	continue;
          // }
            if (title_of_cur_item == null)
            {
                continue;
            }
            
            for (var k=0; k<array.length; ++k)
            {
                if (array[k].length == "")
                {
                    continue;
                }
                var parent_of_cur = checkbox_of_cur_item.parentNode;
                var prev_id = checkbox_of_cur_item.id;
                parent_of_cur.removeChild(checkbox_of_cur_item);
                var new_check = document.createElement("input");
                new_check.setAttribute("type", "checkbox");
                new_check.setAttribute("id", prev_id);
                parent_of_cur.insertBefore(new_check, parent_of_cur.firstChild);
                
                if (array[k].toLowerCase() == title_of_cur_item.value)
                {
                    new_check.setAttribute("checked", "checked");
                    break;
                }
                checkbox_of_cur_item = parent_of_cur.firstChild;
            }        
        }
        var new_array = [];
        for (var i=0; i<array.length; i++)
        {
            if (array[i] != "")
            {
                if (array[i].substr(0,1) == "#")
                    new_array[new_array.length] = array[i]; 
            }
        }
        cur = container.firstChild;
        while(cur)
        {
            if (cur.nextSibling == null)
            {
                break;
            }
			check_new_id = cur.nextSibling.firstChild.nextSibling.id.split("_");
			if(check_new_id[1] == "new")
			{
				container.removeChild(cur.nextSibling);
			}
			else
			{
				break;
			}
        }
        var iter = container.firstChild.firstChild.nextSibling.id.split("_")[3];
        var c = new_array.length;
        var cx = 0;
        if (new_array.length < (new_items.length-1))
        {
            cx = new_items.length - new_array.length - 1;
        }
        for (var i=0; i<new_array.length; i++)
        {
            new_items[i+cx]=(iter-c+i);
            var new_el = document.createElement("div");
            new_el.innerHTML = "<input disabled='disabled' type='checkbox' checked='checked' disabled='disabled' id='check_new_"+id+"_"+(iter-c+i)+"' /><input autocomplete='off' type='text' id='title_new_"+id+"_"+(iter-c+i)+"' style='width:"+(chlist_width-45)+"px;' value='"+new_array[i].substr(1,new_array[i].length)+"'/>";    
            insertAfter(container, new_el, container.firstChild);
            
            WFX.Events.AddEventHandler('keyup', 'title_new_'+id+"_"+(iter-c+i), onNewTitleKeyUp);
            WFX.Events.AddEventHandler('keydown', 'title_new_'+id+"_"+(iter-c+i), onNewTitleKeyDown);
            WFX.Events.AddEventHandler('focus', 'title_new_'+id+"_"+(iter-c+i), function(e)
            {
                if (selected_id != null)
                {
                    var curcheck = WFX.GetElement(selected_id);
                    curcheck.parentNode.style.color = "#000000";
                    curcheck.parentNode.style.background = "#ffffff";
                    selected_id = null;
                }
            });
        }
        
        for (k=0; k<cx; k++)
        {
            new_items[k] = 0;
        }
        
    };
    
    var CollectCheckedIds = function() 
    {
		var elstrings = [];
		var container = WFX.GetElement("chlist_container_"+id);
		
		for (var i = 0; i < items.length; i++) 
		{
			var check = WFX.GetElement(id + "_ch_" + i);

			if (check.checked == true) 
			{
				elstrings[elstrings.length] = items[i][0];
			}
		}
		
		var cur = container.firstChild;
		
		while(cur)
		{
			var check_new_id = cur.firstChild.nextSibling.id.split("_");
			if(check_new_id[1] == "new")
			{
				if (cur.firstChild.nextSibling.value == "")
				{
					if (cur.nextSibling != null)
					{
						cur = cur.nextSibling;
					}
					else
					{
						cur = false;
					}
					continue;
				}
				check_new_id = cur.firstChild.nextSibling.id.split("_");
				elstrings[elstrings.length] = ("#"+cur.firstChild.nextSibling.value);
			}
			else
			{
				break;
			}
			
			if (cur.nextSibling != null)
			{
				cur = cur.nextSibling;
			}
			else
			{
				cur = false;
			}
			
		}
		return elstrings;
	};
	
    var SelectListItem = function(element)
    {
        if (selected_id != null)
        {
            var selected_check = WFX.GetElement(selected_id);
            selected_check.parentNode.style.color = "#000000";
            selected_check.parentNode.style.background = "#ffffff";
        }  

        if (element != null)
        {
            var to_select = WFX.GetElement(element);
            
            to_select.style.color = "#ffffff";
            to_select.style.background = "#316ac5"; 
            selected_id = element.firstChild.id;
            element.firstChild.focus();
        }  
        else
        {
            selected_id = null;
        } 
    };
    
    var onNewTitleKeyUp = function(e)
    {
        var container = WFX.GetElement("chlist_container_"+id);
        var curtitle = WFX.Events.SrcElement(e);
        var cur_id_array = curtitle.id.split("_"); 
        var cur_id_num = cur_id_array[cur_id_array.length-1];
        
        if (parseInt(cur_id_num) == maxelem(new_items) && curtitle.value.length > 0)
        {
            new_items[new_items.length] = parseInt(cur_id_num)+1;
            var newx = document.createElement("div");
            newx.innerHTML = "<input disabled='disabled' type='checkbox' id='check_new_"+id+"_"+(parseInt(cur_id_num)+1)+"' /><input autocomplete='off' type='text' id='title_new_"+id+"_"+(parseInt(cur_id_num)+1)+"' style='width:"+(chlist_width-45)+"px;' /></div>";    
            
            var fc = container.firstChild;
            container.insertBefore(newx, fc);
            
            if (withnew == true)
            {
                WFX.Events.AddEventHandler('keyup', 'title_new_'+id+"_"+(parseInt(cur_id_num)+1), onNewTitleKeyUp);
                WFX.Events.AddEventHandler('keydown', 'title_new_'+id+"_"+(parseInt(cur_id_num)+1), onNewTitleKeyDown);
                WFX.Events.AddEventHandler('focus', 'title_new_'+id+"_"+(parseInt(cur_id_num)+1), function(e)
                {
                    if (selected_id != null)
                    {
                        var curcheck = WFX.GetElement(selected_id);
                        curcheck.parentNode.style.color = "#000000";
                        curcheck.parentNode.style.background = "#ffffff";
                        selected_id = null;
                    }
                });
            }

            var curcheck = WFX.GetElement("check_new_"+id+"_"+parseInt(cur_id_num));
            curcheck.setAttribute("checked", "checked");
        }
        else if (curtitle.value.length == 0 && parseInt(cur_id_num) != maxelem(new_items))
        {
            new_items[cur_id_num-1]=0;
            var curitem = curtitle.parentNode;
            container.removeChild(curitem);
            WFX.GetElement('title_new_'+id+'_'+maxelem(new_items)).focus();
        }
    };
    
    var onNewTitleKeyDown = function(e)
    {
        var key = WFX.Events.KeyCode(e);
        
        var curtitle = WFX.Events.SrcElement(e);
        var cur_id_array = curtitle.id.split("_"); 
        var cur_id_num = cur_id_array[cur_id_array.length-1];
        var next_id = null;
        var f_select = null;
        
        switch(key)
        {
            case WFX.KeyCodes.Up:
            {
                for (var i=0; i < new_items.length; i++)
                {
                    if (new_items[i] > cur_id_num)
                    {
                        next_id = new_items[i];
                        break;
                    }
                }
                if (next_id != null)
                {
                    var f_select = WFX.GetElement("title_new_"+id+"_"+next_id);
                    f_select.focus();
                }
                                
                WFX.Events.Stop(e);
                break;
            }
            case WFX.KeyCodes.Down:
            {
                for (var i=new_items.length; i >= 0; i--)
                {
                    if (new_items[i] < cur_id_num)
                    {
                        next_id = new_items[i];
                        break;
                    }
                }
                if (next_id != null)
                {
                    f_select = WFX.GetElement("title_new_"+id+"_"+next_id);
                    f_select.focus();
                }
                else if (next_id == null)
                {
                    
                    f_select = WFX.GetElement("check_new_"+id+"_"+(parseInt(cur_id_num)));
                    var next_check = f_select.parentNode.nextSibling;
                    SelectListItem(next_check);
                    WFX.Events.Stop(e);
                }
                break;
            }
 
            
            
        }
        
        
    };
    
    var onContainerKeyDown = function(e)
    {
        var key = WFX.Events.KeyCode(e);
        
        if (key == WFX.KeyCodes.Enter)
        {
            //onOkClick(e);
            return;
        }
        
        if (key == WFX.KeyCodes.Esc)
        {
           onCancelClick(e);
           return;
        }
        
        if (selected_id == null)
        {
            return;
        }
        
        var curcheck = WFX.GetElement(selected_id);

        switch(key)
        {
            case WFX.KeyCodes.Up:
            {
                                
                var cur_check_id = curcheck.id;
                var prev_check_id = null;
                
                if (curcheck.parentNode.previousSibling)
                {
                    prev_check_id = curcheck.parentNode.previousSibling.firstChild.id;

                    var s_id = prev_check_id.split("_");
                    var  prev_check = WFX.GetElement(prev_check_id);
                    
                    if (s_id[1] != "new")
                    {
                        SelectListItem(prev_check.parentNode);  
                    }
                    else
                    {
                        curcheck.parentNode.style.color = "#000000";
                        curcheck.parentNode.style.background = "#ffffff";
                        prev_check.nextSibling.focus();
                        selected_id = null;
                    }
                }
                WFX.Events.Stop(e);
                break;   
            }
            case WFX.KeyCodes.Down:
            {
                if (curcheck.parentNode.nextSibling != null)
                {
                    SelectListItem(curcheck.parentNode.nextSibling);
                }
                WFX.Events.Stop(e);
                break;
            }
        }
        
    };
    
    var onBtnClick = function(e)
    {
        
        if (busy == true)
        {   
            alert("Элемент управления еще не готов!\r\nПопробуйте позже...\r\n");
            return
        }
        
        var chlist = WFX.GetElement("chlist_"+id);
        var btn = WFX.Events.SrcElement(e);
        var but_height = WFX.Position.GetHeight(btn);
        var elm_y = WFX.Position.GetTopPosition(btn);
        
        if ((document.documentElement.clientHeight - (elm_y - document.documentElement.scrollTop)) >= (chlist_height) )
        {
            WFX.Position.SetPosition(chlist, btn);
        }   
        else
        {
            if (elm_y < chlist_height)
            {
                WFX.Position.SetPosition(chlist, btn);
            }
            else
            {
                WFX.Position.SetPosition(chlist, btn, ((WFX.Browser.Name == Browsers.IE)?2:0), -(chlist_height-but_height)); 
            }
        }
        
        WFX.ShowElement(chlist);
/*С этой фигней глючат новые тайтлы*/        
/**/ReadSelection();
        
        var container = WFX.GetElement("chlist_container_"+id);
        
        if (selected_id == null)
        {
            if (withnew == false)
            {
                SelectListItem(container.firstChild);
            }
            else
            {
				container.firstChild.firstChild.nextSibling.focus();
            }
        }
        else
        {
            var check_for_select = WFX.GetElement(selected_id);
            SelectListItem(check_for_select.parentNode);
        }
    };
    
    var onOkClick = function(e)
    {
        var chlist = WFX.GetElement("chlist_"+id);
        WFX.HideElement(chlist);
        
        var hidden = WFX.GetElement(id);
        
        var rez = WFX.GetElement("result_"+id);
        var temp_rez_value = rez.value;
        rez.value = "";
        
        hidden.value="";
        var arr_rez=[];
		var arr_hidden=[];
        for (var i=0; i<items.length; ++i)
        {
            var chitem = WFX.GetElement(id+'_ch_'+i);
            
            if (chitem && chitem.checked == true)
            {
                arr_rez[arr_rez.length] = WFX.Strings.Trim(items[i][1]);
                
                arr_hidden[arr_hidden.length] = WFX.Strings.Trim(items[i][0]);
            }
        }
        
        if (withnew == true)
        {
            for (var i=0; i<new_items.length; ++i)
            {
            
                if (new_items[i] == 0)
                {
                    continue;
                }
                
                var new_item = WFX.GetElement(("check_new_"+id+"_"+(new_items[i])));
                
                if (new_item.checked) 
                {
                    var new_title = WFX.GetElement(("title_new_"+id+"_"+(new_items[i])));
                    arr_rez[arr_rez.length] = new_title.value;
                    arr_hidden[arr_hidden.length] = "#"+new_title.value;
                }
            }
        }
        
        rez.value = arr_rez.join("; ")+".";
        hidden.value = arr_hidden.join("|");
        
        if (upload_url != "")
        {       
            var btn_ok = WFX.GetElement("btn_ok_"+id);
            if (temp_rez_value != rez.value)
            {
                rez.style.background="#FFCCCC";
                rez.style.border = "1px solid #707070";
			    WFX.ShowElement(btn_ok);
		    }
		} 
    };
    
    var onCancelClick = function()
    {
        WFX.HideElement("chlist_"+id);
    };
       
    WFX.Events.AddEventHandler('click', 'btn_'+id, onBtnClick);
    WFX.Events.AddEventHandler('click', 'ok_'+id, onOkClick);
    WFX.Events.AddEventHandler('click', 'cancel_'+id, onCancelClick);

    this.Build = function(width, height)
    {
        chlist_height = height || 120;
        chlist_width = width || 120;
        width =  width || 120;
        height = height || 100;
        new_items[0]= 1;
        
        var out = "<table border='0' cellpadding='0' cellspacing='0' style='border-collapse:collapse;'><tr>";
        out += "<td width='20px'><button onclick='return false;' id='btn_"+id+"' style='width:20px; margin-left:-1px; margin-right:1px; padding:0px; font-size:9px;'>";
        out += "...</button></td>";
        out += "<td><input style='border-width:1px; border-color:#898c95; border-style:solid; background-color#ffffff; width:"+(width-20)+"px;' id='result_"+id+"' type='text' readonly='readonly' />";
        out += "</td><td><input type='button' id='btn_ok_"+id+"' value='OK' style='display:none;' /></td></tr></table>";
        out += "<input type='hidden' name='"+id+"' id='"+id+"' />";
        
        out += '<div id="chlist_'+id+'" style="padding:1px;background-image:url(/sysicons/controlbkg.gif); background-repeat:repeat-x; background-position:bottom;display:none;background-color:#ffffff;border-style:solid; border-color:#7f9db9; border-width:1px; height:'+height+'px; width:'+(width+1)+'px; position:absolute;">';
            out += '<div id="chlist_container_'+id+'" style="height:'+(height-25)+'px; overflow:auto; background-color:#ffffff;border-style:solid; border-color:#7f9db9; border-width:1px;">';
//                if (withnew == true)
//                {
//                   out += '<div><input disabled="disabled" type="checkbox"	id="check_new_'+id+'_1" /><input autocomplete="off" type="text" id="title_new_'+id+'_1" style="width:'+(width-45)+'px;" /></div>';
//                }
            out += '</div>';
            out += '<div> <input id="ok_'+id+'" type="button" value="OK" style="margin-top:1px;" /> <input id="cancel_'+id+'" type="button" value="Отмена" style="margin-top:1px;" /> </div>';
        out += '</div>';
        
        WFX.Events.AddEventHandler('keydown', ("chlist_container_"+id), onContainerKeyDown);
        
//        if (withnew == true)
//        {
//            WFX.Events.AddEventHandler('keyup', 'title_new_'+id+"_1", onNewTitleKeyUp);
//            WFX.Events.AddEventHandler('keydown', 'title_new_'+id+"_1", onNewTitleKeyDown);
//        }
        
        WFX.Events.AddEventHandler("click", "btn_ok_"+id, function(e)
        {
			
			var res = WFX.GetElement(id);
			var rez = WFX.GetElement("result_"+id);
			rez.style.background="#FFFFFF";
			reqst.Post(upload_url, WFX.Ajax.EncType.FormUrlencoded, [["p", res.value]]);
			
			
        });
        return out;
    };
    
    this.Show = function(width, height)
    {  
        document.write(this.Build(width, height));
    };
    
        
    this.SetValue = function(value)
    { 
        var intv = setInterval(function()
        {
            if (busy == true)
            {
                return;
            }
            else
            {
                clearInterval(intv);
            }
            
            var list = WFX.GetElement("chlist_container_"+id);
            var current = list.firstChild;
            var hidden = WFX.GetElement(id);
                    
            hidden.value = value;
            
            var values = value.split("|");
            var rez=[];
            
            while(current)
            {
                if (current.firstChild.id.split("_")[1] != "new")
                {
                    var c_hidden = current.firstChild.nextSibling.nextSibling;
                    
                    for (var i=0; i<values.length; ++i)
                    {
                        if (c_hidden.value == values[i])
                        {
                            var title = current.firstChild.nextSibling.innerHTML;
                            rez[rez.length] = title;
                        }
                    }
                }
                
                current = current.nextSibling;
            }
              
            var res = WFX.GetElement("result_"+id);
            res.value = rez.join("; ");
            
            if (rez.length > 0)
            {
                res.value += ".";
            }   
        },
        100);
    };
    
    this.GetValue = function()
    {
        var hidden = WFX.GetElement(id);
        return hidden.value;
    };
    
    this.GetName = function()
    {
        return id;  
    };
};






/* 
    
CheckBoxList 
    
*/

WFX.Controls.CheckBoxList = function(name, up_title, down_title, sellall_title, desellall_title) 
{
	this.Version = "1.0.1";
    
    var up_t = up_title || "Переместить вверх";
    var down_t = down_title || "Переместить вниз";
    var sellall_t = sellall_title || "Отметить все";
    var desellall_t = desellall_title || "Снятьотметки";
    
    WFX.Images.Preload("/sysimages/checkboxlist/down_btn_over.png");
    WFX.Images.Preload("/sysimages/checkboxlist/down_btn_down.png");
    
    WFX.Images.Preload("/sysimages/checkboxlist/up_btn_over.png");
    WFX.Images.Preload("/sysimages/checkboxlist/up_btn_down.png");
    
    WFX.Images.Preload("/sysimages/checkboxlist/selectall_btn_over.png");
    WFX.Images.Preload("/sysimages/checkboxlist/selectall_btn_down.png");
    
    WFX.Images.Preload("/sysimages/checkboxlist/deselectall_btn_over.png");
    WFX.Images.Preload("/sysimages/checkboxlist/deselectall_btn_down.png");
    
	var items = [];
	var id = name;
	var list_height;
	var list_width;
	var selected_id = null;
	var ready = false;

	this.Sortable = false;

	this.IsBusy = function() 
	{
		return WFX.IsVisible("busy_" + id);
	};

	var _dep = null;

	this.SetDependent = function(obj) 
	{
		_dep = obj;
	};

	this.SuspendLayout = function() 
	{
		var busy = WFX.GetElement("busy_" + id);
		WFX.Position.Move(busy, WFX.Position.GetLeftPosition(("main_" + id)), WFX.Position.GetTopPosition(("main_" + id)));
		WFX.ShowElement(busy);
	};

	this.ResumeLayout = function() 
	{
		var busy = WFX.GetElement("busy_" + id);
		WFX.HideElement(busy);
	};

	var req = new WFX.Ajax.Request
	(
	    function()
	    {
	        ready = false;
	    }, 
    	
	    function(response) 
	    {
		    items = [];
		    if (response.length > 0) {
			    var temp_items = response.split("|");
			    for (var i = 0; i < temp_items.length; i++) {
				    items[i] = new Array();
				    items[i][0] = temp_items[i].split(":")[0];
				    items[i][1] = temp_items[i].split(":")[1];
			    }
		    }
		    ready = true;
	    }
	);

	var ReadSelection = function() 
	{
		var hidden = WFX.GetElement(id);

		var array = hidden.value.split('|');
		var array2 = [];
		for (var i = 0; i < items.length; ++i) 
		{
			var checkbox_of_cur_item = WFX.GetElement(id + '_ch_' + i);
			var hidden_of_cur_item = WFX.GetElement(id + "_" + i);

			if (hidden_of_cur_item.value == null) 
			{
				continue;
			}

			for (var k = 0; k < array.length; ++k) 
			{
				if (array[k].length == "") 
				{
					continue;
				}

				if (array[k] == hidden_of_cur_item.value) 
				{
					checkbox_of_cur_item.checked = true;
					array2[array2.length] = array[k];
					break;
				}
				else 
				{
					checkbox_of_cur_item.checked = false;
				}
			}
		}
		hidden.value = array2.join("|");
	};

	var _Fill = function() 
	{
		var list = WFX.GetElement("list_" + id);

		for (var i = 0; i < items.length; ++i) 
		{
			if (items[i][1].length == 0) 
			{
				continue;
			}

			var div = document.createElement("div");

			div.innerHTML = '<input type="checkbox" id="' + id + "_ch_" + i + '" /><label style="position:relative; bottom:2px;" id="' + id + "_title_" + i + '"	>' + items[i][1].replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'") + '</label><input type="hidden" id="' + id + '_' + i + '" value="' + items[i][0] + '"/>';
			list.appendChild(div);

			WFX.Events.AddEventHandler('mousedown', (id + "_ch_" + i), function(e) 
			{
				var curchek = WFX.Events.SrcElement(e);
				SelectListItem(curchek.parentNode);
			});

			WFX.Events.AddEventHandler('mouseup', (id + "_title_" + i), function(e) 
			{
				var curchek = WFX.Events.SrcElement(e);
				SelectListItem(curchek.parentNode);
			});

			WFX.Events.AddEventHandler('click', (id + "_ch_" + i), RunCheckChangeHandlers);

			WFX.Events.AddEventHandler('click', (id + "_ch_" + i), function() 
			{
				var hidden = WFX.GetElement(id);
				var elstrings = CollectCheckedIds();
				hidden.value = elstrings.join("|");
			});
		}
	};

	this.Clear = function() 
	{
		WFX.Events.RemoveEventHandler('keydown', ("list_" + id), OnListKeyDown);

		var list = WFX.GetElement("list_" + id);

		while (list.childNodes.length > 0) 
		{
			list.removeChild(list.firstChild);
		}

		//items = [];
		selected_id = null;

		//ready = false;
	};

	this.Reload = function(url) 
	{
		if (this.IsBusy()) 
		{
			return;
		}

		if (_block_busy == false) 
		{
			this.SuspendLayout();
		}

		if (_dep != null) 
		{
			_dep.SuspendLayout();
		}

		this.Clear();
		req.Get(url);

		var intv = setInterval
        (
            function() 
            {
            	if (ready == false) 
            	{
            		return;
            	}
            	else 
            	{
            		clearInterval(intv);
            	}
            	_Fill();
            	ReadSelection();
            	WFX.Events.AddEventHandler('keydown', ("list_" + id), OnListKeyDown);

            	/* ResumeLayout */
            	var busy = WFX.GetElement("busy_" + id);
            	WFX.HideElement(busy);
            	/* ResumeLayout */

            	if (_dep != null) 
            	{
            		setTimeout(_dep.ResumeLayout, 100);
            	}
            	
            	_block_busy = false;
            },
            100
        );
	};

	var _block_busy = false;

	this.Load = function(url) 
	{
		_block_busy = true;

		var list = WFX.GetElement("list_" + id);
		if (list.childNodes.length > 0) 
		{
			return;
		}
//alert("Start Reloading "+url);
		this.Reload(url);

		
	};

	var OnListKeyDown = function(e) 
	{
		var busy = WFX.GetElement("busy_" + id);

		if (WFX.IsVisible(busy) == true) 
		{
			return;
		}

		var list = WFX.Events.SrcElement(e);
		var key = WFX.Events.KeyCode(e);

		switch (key) 
		{
			case WFX.KeyCodes.Down:
			{
				if (selected_id == null) 
				{
					SelectListItem(list.firstChild);
					WFX.Events.Stop(e);
					break;
				}
                
				var curcheck = WFX.GetElement(selected_id);
				if (curcheck.parentNode.nextSibling != null) 
				{
					SelectListItem(curcheck.parentNode.nextSibling);
				}
                
				WFX.Events.Stop(e);
                
				break;
			}

			case WFX.KeyCodes.Up:
			{
				if (selected_id == null) 
				{
					break;
				}

				var curcheck = WFX.GetElement(selected_id);
				if (curcheck.parentNode.previousSibling) 
				{
					SelectListItem(curcheck.parentNode.previousSibling);
				}
                
				WFX.Events.Stop(e);
                
				break;
			}
		}
	};

	var SelectListItem = function(element) 
	{
		if (selected_id != null) 
		{
			var selected_check = WFX.GetElement(selected_id);

			selected_check.parentNode.style.color = "#000000";
			selected_check.parentNode.style.background = "#ffffff";
		}

		if (element != null) 
		{
			var to_select = WFX.GetElement(element);

			to_select.style.color = "#ffffff";
			to_select.style.background = "#316ac5";

			selected_id = element.firstChild.id;
			element.firstChild.focus();
		}
		else 
		{
			selected_id = null;
		}

	};

	var btn_down = new WFX.Controls.ImageButton("opt_" + id + "_sortdown", "/sysimages/checkboxlist/down_btn_normal.png", "/sysimages/checkboxlist/down_btn_over.png", "/sysimages/checkboxlist/down_btn_down.png", down_t);
	var btn_up = new WFX.Controls.ImageButton("opt_" + id + "_sortup", "/sysimages/checkboxlist/up_btn_normal.png", "/sysimages/checkboxlist/up_btn_over.png", "/sysimages/checkboxlist/up_btn_down.png", up_t);

	var btn_selectall = new WFX.Controls.ImageButton("opt_" + id + "_selall", "/sysimages/checkboxlist/selectall_btn_normal.png", "/sysimages/checkboxlist/selectall_btn_over.png", "/sysimages/checkboxlist/selectall_btn_down.png", sellall_t);
	var btn_deselectall = new WFX.Controls.ImageButton("opt_" + id + "_unselall", "/sysimages/checkboxlist/deselectall_btn_normal.png", "/sysimages/checkboxlist/deselectall_btn_over.png", "/sysimages/checkboxlist/deselectall_btn_down.png", desellall_t);

	this.Build = function(width, height) 
	{
		list_height = height || 120;
		list_width = width || 120;

		var out = "<div id='main_" + id + "' style='height:" + (list_height) + "px; width:" + (list_width) + "px;  border-style:solid; border-color:#898c95;  border-width:1px; background-image:url(/sysicons/controlbkg.gif); background-repeat:repeat-x;'>";

		    out += "<div>";

		    out += "<table border='0' cellspacing='3' cellpadding='0' style='background-color:#f7f6f3; '>";
		    out += "<tr>";

		    if (this.Sortable == true) 
		    {
		        out += "<td>" + btn_up.Build(13, 13) + "</td>";
			    out += "<td>" + btn_down.Build(13, 13) + "</td>";
		    }

		    out += "<td>";
		    out += btn_selectall.Build(13, 13);
		    out += "</td>";
		    out += "<td>";
		    out += btn_deselectall.Build(13, 13) + "</td>";
		    out += "</tr>";
		    out += "</table>";

		    out += "</div>";

		    out += "<div id='list_" + id + "' style='height:" + (list_height - 24) + "px; width:" + (list_width - 8) + "px; overflow:auto; background-color:#ffffff;border-style:solid; border-color:#7f9db9; border-width:1px; margin-left:3px;'></div>";
		    out += "<input type='hidden' id='" + id + "' name='" + id + "' />";
		    out += "<div id='busy_" + id + "' style='display:none; background-image:url(/sysimages/transbg.png); position:absolute; width:" + (list_width + 3) + "px; height:" + (list_height + 3) + "px; text-align:center;'><img vspace='" + (list_height / 2 - 8) + "' src='/sysimages/load2.gif' align='middle' /></div>";
		
		out += "</div>";
        
        //////
        btn_down.AddMouseClickHandler(function(e) 
        {
            if (WFX.GetElement(selected_id) == null) return;
			var hidden = WFX.GetElement(id);
			var elm = WFX.GetElement(selected_id).parentNode;
			var container = WFX.GetElement("list_" + id);
			if (elm != null && elm.nextSibling != null) 
			{
			    // копия выбранного
				var temp_ch = [];
				temp_ch["checked"] = elm.firstChild.checked;
				temp_ch["chi"] = elm.firstChild.id.split('_')[2];
				temp_ch["title"] = elm.firstChild.nextSibling.innerHTML;
				temp_ch["id"] = elm.firstChild.nextSibling.nextSibling.value;
				
				var div = document.createElement("div");
			    div.innerHTML = '<input type="checkbox" '+((temp_ch['checked']==true)?'checked="checked"':"")+' id="' + id + "_ch_" + (temp_ch['chi']+1) + '" /><label id="' + id + "_title_" + (temp_ch['chi']+1) + '"	>' + temp_ch["title"] + '</label><input type="hidden" id="' + id + '_' + (temp_ch['chi']+1) + '" value="' + temp_ch["id"] + '"/>';
				
				var sibling = elm.nextSibling;
				sibling.firstChild.id = id+"_ch_"+temp_ch["chi"];
			    sibling.firstChild.nextSibling.id = id+"_title_"+temp_ch["chi"];
			    sibling.firstChild.nextSibling.nextSibling.id = id+"_"+temp_ch["chi"];
			    
			    container.removeChild(elm);
			    insertAfter(container, div, sibling);
			    
			    WFX.Events.AddEventHandler('mousedown', (id + "_ch_" + (temp_ch['chi']+1)), function(e) 
			    {
				    var curchek = WFX.Events.SrcElement(e);
				    SelectListItem(curchek.parentNode);
			    });

			    WFX.Events.AddEventHandler('mouseup', (id + "_title_" + (temp_ch['chi']+1)), function(e) 
			    {
				    var curchek = WFX.Events.SrcElement(e);
				    SelectListItem(curchek.parentNode);
			    });

			    WFX.Events.AddEventHandler('click', (id + "_ch_" + (temp_ch['chi']+1)), RunCheckChangeHandlers);

			    WFX.Events.AddEventHandler('click', (id + "_ch_" + (temp_ch['chi']+1)), function() 
			    {
				    var hidden = WFX.GetElement(id);
				    var elstrings = CollectCheckedIds();
				    hidden.value = elstrings.join("|");
			    });
			    
			    SelectListItem(div);
				
				var temp_arr = [];
				var k = 0;
				for (var i = 0; i < items.length; i++) 
				{
					items[i][0] = container.childNodes.item(i).firstChild.nextSibling.nextSibling.value;
					if(container.childNodes.item(i).firstChild.checked == true)
					{
					    temp_arr[k] = items[i][0];
					    k++;
					}
					items[i][1] = container.childNodes.item(i).firstChild.nextSibling.innerHTML;
				}
				hidden.value = "";
			    hidden.value = temp_arr.join("|");
			}
		});

		btn_up.AddMouseClickHandler(function(e) 
		{
		    if (WFX.GetElement(selected_id) == null) return;
            var hidden = WFX.GetElement(id);
			var elm = WFX.GetElement(selected_id).parentNode;
			var container = WFX.GetElement("list_" + id);
			if (elm != null && elm.previousSibling != null) 
			{
				// копия выбранного
				var temp_ch = [];
				temp_ch["checked"] = elm.firstChild.checked;
				temp_ch["chi"] = elm.firstChild.id.split('_')[2];
				temp_ch["title"] = elm.firstChild.nextSibling.innerHTML;
				temp_ch["id"] = elm.firstChild.nextSibling.nextSibling.value;
				
				var div = document.createElement("div");
			    div.innerHTML = '<input type="checkbox" '+((temp_ch['checked']==true)?'checked="checked"':"")+' id="' + id + "_ch_" + (temp_ch['chi']-1) + '" /><label id="' + id + "_title_" + (temp_ch['chi']-1) + '"	>' + temp_ch["title"] + '</label><input type="hidden" id="' + id + '_' + (temp_ch['chi']-1) + '" value="' + temp_ch["id"] + '"/>';
				
				var sibling = elm.previousSibling;
				sibling.firstChild.id = id+"_ch_"+temp_ch["chi"];
			    sibling.firstChild.nextSibling.id = id+"_title_"+temp_ch["chi"];
			    sibling.firstChild.nextSibling.nextSibling.id = id+"_"+temp_ch["chi"];
				
				container.removeChild(elm);
			    container.insertBefore(div, sibling);
			    
			    WFX.Events.AddEventHandler('mousedown', (id + "_ch_" + (temp_ch['chi']-1)), function(e) 
			    {
				    var curchek = WFX.Events.SrcElement(e);
				    SelectListItem(curchek.parentNode);
			    });

			    WFX.Events.AddEventHandler('mouseup', (id + "_title_" + (temp_ch['chi']-1)), function(e) 
			    {
				    var curchek = WFX.Events.SrcElement(e);
				    SelectListItem(curchek.parentNode);
			    });

			    WFX.Events.AddEventHandler('click', (id + "_ch_" + (temp_ch['chi']-1)), RunCheckChangeHandlers);

			    WFX.Events.AddEventHandler('click', (id + "_ch_" + (temp_ch['chi']-1)), function() 
			    {
				    var hidden = WFX.GetElement(id);
				    var elstrings = CollectCheckedIds();
				    hidden.value = elstrings.join("|");
			    });
			    
			    SelectListItem(div);
				
				var temp_arr = [];
				var k = 0;
				for (var i = 0; i < items.length; i++) 
				{
					items[i][0] = container.childNodes.item(i).firstChild.nextSibling.nextSibling.value;
					if(container.childNodes.item(i).firstChild.checked == true)
					{
					    temp_arr[k] = items[i][0];
					    k++;
					}
					items[i][1] = container.childNodes.item(i).firstChild.nextSibling.innerHTML;
				}
				hidden.value = "";
			    hidden.value = temp_arr.join("|");
			}
		});
		/////
		
		btn_selectall.AddMouseClickHandler(function(e) 
		{
			var container = WFX.GetElement("list_" + id);
			for (var i = 0; i < items.length; i++) 
			{
				container.childNodes.item(i).firstChild.checked = true;
				
			}
			
			var hidden = WFX.GetElement(id);
			var elstrings = CollectCheckedIds();
			hidden.value = elstrings.join("|");
			RunCheckChangeHandlers();
		});


		btn_deselectall.AddMouseClickHandler(function(e) 
		{
			var container = WFX.GetElement("list_" + id);
			for (var i = 0; i < items.length; i++) 
			{
				container.childNodes.item(i).firstChild.checked = false;
			}
			var hidden = WFX.GetElement(id);
			hidden.value = "";
			RunCheckChangeHandlers();
		});

		return out;
	};

	this.Show = function(width, height) 
	{
		document.write(this.Build(width, height));
	};

	this.SetFocus = function() 
	{
		var list = WFX.GetElement("list_" + id);
		list.focus();
	};

	var check_change_handlers = [];

	var CollectCheckedIds = function() {
		var elstrings = [];

		for (var i = 0; i < items.length; i++) {
			var check = WFX.GetElement(id + "_ch_" + i);

			if (check.checked == true) {
				elstrings[elstrings.length] = items[i][0];
			}
		}
		return elstrings;
	};

	var RunCheckChangeHandlers = function(e) {

		var elstrings = CollectCheckedIds();

		for (var i = 0; i < check_change_handlers.length; i++) {
			var list = WFX.GetElement("list_" + id);
			check_change_handlers[i](id, elstrings);
		}
	};

	this.AddCheckChangeEventHandler = function(handler) 
	{
		check_change_handlers[check_change_handlers.length] = handler;
	};

    this.SetValue = function(value)
    { 
        var intv = setInterval(function()
        {
            if (ready == false)
            {
                return;
            }
            else
            {
                clearInterval(intv);
            }
            
            var hidden = WFX.GetElement(id);

		    var array = value.split('|');
		    var array2 = [];
		    for (var i = 0; i < items.length; ++i) 
		    {
			    var checkbox_of_cur_item = WFX.GetElement(id + '_ch_' + i);
			    var hidden_of_cur_item = WFX.GetElement(id + "_" + i);

			    if (hidden_of_cur_item == null || hidden_of_cur_item.value == null) 
			    {
				    continue;
			    }

			    for (var k = 0; k < array.length; ++k) 
			    {
				    if (array[k].length == "") 
				    {
					    continue;
				    }

				    if (array[k] == hidden_of_cur_item.value) 
				    {
					    checkbox_of_cur_item.checked = true;
					    array2[array2.length] = array[k];
					    break;
				    }
				    else 
				    {
					    checkbox_of_cur_item.checked = false;
				    }
			    }
		    }
		    hidden.value = array2.join("|");
		    
        },
        100);
    };
    
	this.GetValue = function() {
		var hidden = WFX.GetElement(id);
		return hidden.value;
	};

	this.GetName = function() {
		return id;
	};
};




/* 

    TreeCheckList 
    
*/

WFX.Controls.TreeCheckList = function(name)
{
    this.Version = "2.0";
    
    var items = [];
    var items2 = [];
    var id = name;
    var tree_height;
    var tree_width;
    var selected_id = null;
    var ready = false;
    var init_url = null;
    
    this.Reload = function(url)
    {
        busy = true;
        this.Clear();
        req.Get(url);
        
        var intv = setInterval
        ( 
            function()
            {
                if (ready == false)
                {
                    return;
                }
                else
                {
                    clearInterval(intv);
                }
                
                FillCheckList();
                //WFX.Events.AddEventHandler('keydown', ("tree_" + id), OnListKeyDown);
            }, 
            100
        );
        
    };
    
    var busy = false;
    this.IsBusy = function()
    {
        return busy;
    }
    
    this.Load = function(url)
    {
        var clist = WFX.GetElement("tree_"+id);
        
        if (clist.childNodes.length > 1)
        {
            return;
        }
        
        
        init_url = url;
        this.Reload(url);
    };
    
    this.Clear = function() 
	{
		WFX.Events.RemoveEventHandler('keydown', ("tree_" + id), OnListKeyDown);

		var list = WFX.GetElement("tree_" + id);

		while (list.childNodes.length > 0) 
		{
			list.removeChild(list.firstChild);
		}

		//items = [];
		selected_id = null;

		//ready = false;
	};
    
    var req = new WFX.Ajax.Request
    (
        function()
        {
            ready = false;
        },
        
        function(response)
        {
            var str = response.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'").split("|");
            for (var i=0; i < str.length; i++)
            {
                items2[i] = new Array();
                var temp =  str[i].split(":");
                var temp2 = temp[0].split("#");
                temp[0] = temp2;
                var names = temp[1].split(";");
                for (var j =0; j<names.length; j++)
                {
                    var ids = names[j].split("#");
                    names[j] = ids;
                }
                temp[1] = names;
                items2[i] = temp;
            }
            ready = true;
        }
    );
    
    
    var check_event1 = function(e)
    {
        var curchek = WFX.Events.SrcElement(e);
        var rez_value = WFX.GetElement(id);

        var elm = WFX.GetElement("user_"+id+"_hidden_"+curchek.id.split("_")[3]);
       
        if (rez_value.value != "")
        {
            var skiped = false;
            var rez_arr = rez_value.value.split("|");
            var temp_arr = [];
            for (var i=0; i< rez_arr.length; i++)
            {
                if (rez_arr[i] == elm.value)
                {
                    skiped = true;
                    continue;
                }
                else
                {
                    temp_arr[temp_arr.length] = rez_arr[i];
                }
            }
            
            if (skiped == false)
            {
                temp_arr[temp_arr.length] = elm.value;
            }
          
            rez_value.value = temp_arr.join("|");
        }
        else
        {
            rez_value.value = elm.value;
        }

        var to_sel_id = "user_"+id+"_"+curchek.id.split("_")[3];
        var to_sel_obj = WFX.GetElement(to_sel_id);
        SelectListItem(to_sel_obj);    
    };
    
    /*var check_event2 = function(e)
    {
        var curchek = WFX.Events.SrcElement(e);
        var to_sel_id = "user_"+id+"_"+curchek.id.split("_")[3];
        var to_sel_obj = WFX.GetElement(to_sel_id);
        SelectListItem(to_sel_obj);
    };*/

        
    var check_all_in_group = function(check)
    {
        var curcheck = check;
        var ch = curcheck.parentNode;
        var temp = [];
        var group_id = [];
        var all = false;
        while (ch.previousSibling != null)
        {
            ch = ch.previousSibling;
            temp = ch.id.split("_");
            if (temp[0] == "group")
            {
                group_id = temp;
                break;
            }
            
        }
        
        var items_checked = 0;
        var all_items = 0;
        
        while(ch.nextSibling != null)
        {
            ch = ch.nextSibling;
            temp = ch.id.split("_");
            if (temp[0] == "group")
            {
                break;
            }
            var elm = WFX.GetElement("user_"+id+"_ch_"+temp[2]);
            if (elm.checked == true)
            {
                items_checked++;       
            }
            all_items++;
        }
        
        if (all_items == items_checked)
        {
            all = true;
        }
        
        var group_check = WFX.GetElement("group_"+id+"_ch_"+group_id[2]);
        
        //if (all == true)
        //{   
            var old_check = WFX.GetElement(group_check);
            var old_check_parent = old_check.parentNode;
            
            var new_check = document.createElement("input");
            new_check.setAttribute("id", old_check.id);
            new_check.setAttribute("type", "checkbox");
            
            var i = group_check.id.split("_")[3];
            var label = WFX.GetElement("group_"+id+"_folder_"+i);
            old_check_parent.removeChild(old_check);
            old_check_parent.insertBefore(new_check, label);
            if (all == true)
            {
                new_check.setAttribute("checked", "checked");
            }
            WFX.Events.AddEventHandler('click', ("group_"+id+"_ch_"+i), CheckChange); 
            WFX.Events.AddEventHandler('mousedown', ("group_"+id+"_ch_"+i), function(e)
            {
                var curchek = WFX.Events.SrcElement(e);
                SelectListItem(curchek.parentNode);
            });
        //}
        //else
        //{
        //    if (WFX.Browser.Name == Browsers.Firefox)
        ///    {
        //        group_check.removeAttribute("checked");
        //    }    
        //    else
        //    {
        ///        group_check.checked = false;
        //    }
        //}   
        
    };
    
    var check_event3 = function(e)
    {
        
        var curcheck = WFX.Events.SrcElement(e);
        check_all_in_group(curcheck);
    };
    
    var CheckGroupIfAll = function(ch_ind)
    {
        WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+ch_ind), check_event3); 
    };
    
    var CheckChange = function(e)
    {
        var curchek = WFX.Events.SrcElement(e);
        var group = curchek.parentNode;
        SelectListItem(curchek.parentNode);
                
        var temp = curchek.parentNode.id.split("_");
        if (temp[0] == "group")
        {
            var c = false;  
            if (curchek.checked == true)
            {
                c = false;
            }
            else
            {
                c = true;
            }

            var iterator = group;
            while (iterator.nextSibling != null)
            {
                t = iterator.nextSibling.id.split("_");
                if (t[0] == "group")
                {
                    break;
                }
                
                var old_check_id = "user_"+id+"_ch_"+iterator.nextSibling.id.split("_")[2];
                var old_check = WFX.GetElement(old_check_id);
                var old_check_parent = old_check.parentNode;
                
                var new_check = document.createElement("input");
                new_check.setAttribute("id", old_check_id);
                new_check.setAttribute("type", "checkbox");
                
                var i = iterator.nextSibling.id.split("_")[2];
                var label = WFX.GetElement("user_"+id+"_title_"+i);
                
                old_check_parent.removeChild(old_check);
                old_check_parent.insertBefore(new_check, label);
                
                if (curchek.checked == true)
                {
                    if (WFX.Browser.Name == Browsers.Firefox)
                    {
                        new_check.setAttribute("checked", "checked");
                    }
                    else
                    {
                        new_check.checked = true;
                    }
                }
                
                /*WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+i), function(e)
                {
                    var curchek = WFX.Events.SrcElement(e);

                    var to_sel_id = "user_"+id+"_"+curchek.id.split("_")[3];
                    var to_sel_obj = WFX.GetElement(to_sel_id);

                    SelectListItem(to_sel_obj);
                });*/
                CheckGroupIfAll(i);
                iterator = iterator.nextSibling;
            }
           
            var hidden = WFX.GetElement(id);
            var elstrings = CollectCheckedIds();
            hidden.value = elstrings.join("|");
        }

    };
    
    var FillCheckList = function()
    {
        WFX.Events.AddEventHandler('keydown', ("tree_"+id), OnListKeyDown);
        var intv = setInterval
        ( 
            function()
            {
                if (ready == false)
                {
                    return;
                }
                else
                {
                    clearInterval(intv);
                }
                
                var tree = WFX.GetElement("tree_"+id);
        
                if (tree.childNodes.length > 1)
                {
                    return;
                }
                var k = 0;
                for (var i=0; i<items2.length; ++i)
                {
                    var div = document.createElement("div");
                                      
                    div.setAttribute("id", "group_"+id+"_"+i);
                    //div.innerHTML = '<table cellpadding="0" cellspacing="0" border="0" style="display:inline;">';
                    //div.innerHTML += '<tr><td width="16px" height="14px">&nbsp;<img id="group_'+id+'_c_'+i+'" src="/sysimages/treechecklist/minus.png" /></td></tr>';
                    div.innerHTML += '<img id="group_'+id+'_c_'+i+'" src="/sysimages/treechecklist/minus.png" />';
                    //div.innerHTML += '</table>';   
                    div.innerHTML += '<input type="checkbox" id="group_'+id+'_ch_'+i+'" />';
                    //div.innerHTML += '<table  cellpadding="0" cellspacing="0" border="0" style="display:inline;">';
                    //div.innerHTML += '<tr><td width="16px" height="14px"><img id="group_'+id+'_folder_'+i+'"src="/sysimages/treechecklist/foldero.png" /></td></tr>';
                    div.innerHTML += '<img id="group_'+id+'_folder_'+i+'"src="/sysimages/treechecklist/foldero.png" />';
                    //div.innerHTML += '</table>&nbsp;';   
                    div.innerHTML += '<label id="group_'+id+"_title_"+i+'">'+items2[i][0][0].replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'")+'</label>';

                    var hidden = document.createElement("input");
                    hidden.setAttribute("type", "hidden");
                    hidden.setAttribute("id", ("group_"+id+"_hidden_"+i));
                    hidden.value = items2[i][0][0][1];
                    //alert(items2[i][1][1]);
                    div.appendChild(hidden);
                                        
                    tree.appendChild(div);
                    
                    for (var j=0; j<items2[i][1].length; j++)
                    {
                        var div1 = document.createElement("div");
                        div1.setAttribute("id", "user_"+id+"_"+k);
                        div1.style.marginLeft = "25px";
                        //div1.innerHTML += '<table  cellpadding="0" cellspacing="0" border="1" style="display:inline;">';
                        //div1.innerHTML += '<tr><td width="16px" height="16px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>';
                        //div1.innerHTML += '</table>';   
                        div1.innerHTML += '<input id="user_'+id+"_ch_"+k+'" type="checkbox" />';
                        div1.innerHTML += '<label id=user_'+id+'_title_'+k+'>'+items2[i][1][j][0].replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'")+'</label>';
                        
                        var hidden1 = document.createElement("input");
                        hidden1.setAttribute("type", "hidden");
                        hidden1.setAttribute("id", ("user_"+id+"_hidden_"+k));
                        hidden1.value = items2[i][1][j][1];
                        div1.appendChild(hidden1);
                        
                        tree.appendChild(div1);
                        
                        //WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+k), check_event2);
                        WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+k), check_event1);
                        //WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+k), check_event3);
                        
                        WFX.Events.AddEventHandler('mouseup', ("user_"+id+"_title_"+k), function(e)
                        {
                            var curchek = WFX.Events.SrcElement(e);
                            SelectListItem(curchek.parentNode);
                        });
                        
                        CheckGroupIfAll(k);
                        WFX.Events.AddEventHandler('mouseover', ("user_"+id+"_"+k), RunMouseOverHandlers);
                        WFX.Events.AddEventHandler('mousemove', ("user_"+id+"_"+k), RunMouseMoveHandlers);
                        WFX.Events.AddEventHandler('mouseout',  ("user_"+id+"_"+k), RunMouseOutHandlers);
                        
                        k++;
                    }
                    
                    WFX.Events.AddEventHandler('keyup', ("group_"+id+"_ch_"+i), function(e)
                    {
                        var key = WFX.Events.KeyCode(e);
                        if (key == WFX.KeyCodes.Space)
                        {
                            CheckChange(e);
                        }
                    });
                    
                    WFX.Events.AddEventHandler('click', ("group_"+id+"_ch_"+i), CheckChange);
                    
                    WFX.Events.AddEventHandler('click', ("group_"+id+"_title_"+i), function(e)
                    {
                        var curchek = WFX.Events.SrcElement(e);
                        SelectListItem(curchek.parentNode);
                    });
                    
                    WFX.Events.AddEventHandler('click', ("group_"+id+"_folder_"+i), function(e)
                    {
                        var curchek = WFX.Events.SrcElement(e);
                        var _id = "group_"+id+"_ch_"+(curchek.id.split("_")[3]);
                        curchek = WFX.GetElement(_id);
                      
                        SelectListItem(curchek.parentNode);
                    });
                                      
                    WFX.Events.AddEventHandler('mousedown', ("group_"+id+"_ch_"+i), function(e)
                    {
                        var curchek = WFX.Events.SrcElement(e);
                        SelectListItem(curchek.parentNode);
                    });
                    
                    WFX.Events.AddEventHandler('mousedown', ("group_"+id+"_c_"+i), function(e)
                    {
                        var imgcheck = WFX.Events.SrcElement(e);
                        var myid = imgcheck.id.split("_"); 
                        var foldcheck = WFX.GetElement("group_"+myid[1]+"_folder_"+myid[3]);
                        var temp = imgcheck.parentNode.id.split("_");
                        var ch = imgcheck.parentNode;
                        if (temp[0] == "group")
                        {
                            while (ch.nextSibling != null)
                            { 
                                ch = ch.nextSibling;
                                temp = ch.id.split("_");
                                if (temp[0] == "group")
                                {
                                    break;
                                }
                                else
                                {
                                    temp = ch.id.split("_");
                                    var elm = WFX.GetElement("user_"+temp[1]+"_ch_"+temp[2]);
                                 
                                    if (WFX.IsVisible(elm.parentNode) == true)
                                    {
                                        foldcheck.src= "/sysimages/treechecklist/folderc.png";
                                        imgcheck.src = "/sysimages/treechecklist/plus.png";
                                        WFX.HideElement(elm.parentNode);
                                    }
                                    else 
                                    {
                                        foldcheck.src= "/sysimages/treechecklist/foldero.png";
                                        imgcheck.src = "/sysimages/treechecklist/minus.png";
                                        WFX.ShowElement(elm.parentNode);
                                    }
                                }
                            } 
                        }
                    });
                    
                    WFX.Events.AddEventHandler('mouseover', ("group_"+id+"_"+i), RunMouseOverHandlers);
                    WFX.Events.AddEventHandler('mousemove', ("group_"+id+"_"+i), RunMouseMoveHandlers);
                    WFX.Events.AddEventHandler('mouseout',  ("group_"+id+"_"+i), RunMouseOutHandlers);
                
                }
                busy = false;
            }, 
            100
        );
    };
    
    this.SetFocus = function()
    {
        var tree = WFX.GetElement("tree_"+id);
        tree.focus();
    }
    
    var OnListKeyDown = function(e)
    {
        var tree = WFX.Events.SrcElement(e);
        var key = WFX.Events.KeyCode(e);          
        switch(key)
        {
            case WFX.KeyCodes.Down:
            {
                if (selected_id == null)
                {
                    SelectListItem(tree.firstChild);
                    WFX.Events.Stop(e);
                    break;
                }
                
                var curcheck = WFX.GetElement(selected_id);
                if (curcheck.nextSibling != null)
                {
                    while(curcheck.nextSibling.style.display == 'none')
                    {
                        curcheck = curcheck.nextSibling;
                        
                        if (curcheck.nextSibling == null)
                        {
                            WFX.Events.Stop(e);
                            return;
                        }
                    }
                    
                    SelectListItem(curcheck.nextSibling);
                }
                
                WFX.Events.Stop(e);
                
                break;
            }
        
            case WFX.KeyCodes.Up:
            {
                if (selected_id == null)
                {
                    break;
                }
                
                var curcheck = WFX.GetElement(selected_id);                
                if (curcheck.previousSibling)
                {
                    while(curcheck.previousSibling.style.display == 'none')
                    {
                        curcheck = curcheck.previousSibling;
                    }
                    
                    SelectListItem(curcheck.previousSibling);
                }
                WFX.Events.Stop(e);
                
                break;   
            }
            case WFX.KeyCodes.Right:
            {   
                if (selected_id == null)
                {
                    break;
                }
                var imgcheck = WFX.Events.SrcElement(e);
                var myid = imgcheck.id.split("_"); 
                var foldcheck = WFX.GetElement("group_"+id+"_folder_"+myid[3]);
                var temp = imgcheck.parentNode.id.split("_");
                var ch = imgcheck.parentNode;
                if (temp[0] == "group")
                {
                    while (ch.nextSibling != null)
                    { 
                        ch = ch.nextSibling;
                        temp = ch.id.split("_");
                        if (temp[0] == "group")
                        {
                            break;
                        }
                        temp = ch.id.split("_");
                        var elm = WFX.GetElement("user_"+id+"_ch_"+temp[2]);
                        foldcheck.src= "/sysimages/treechecklist/foldero.png";
                        var plus = WFX.GetElement("group_"+id+"_c_"+myid[3]);
                        plus.src = "/sysimages/treechecklist/minus.png";
                        WFX.ShowElement(elm.parentNode);
                    } 
                }
                break;   
            }
            case WFX.KeyCodes.Left:
            {
                var imgcheck = WFX.Events.SrcElement(e);
                var myid = imgcheck.id.split("_"); 
                var foldcheck = WFX.GetElement("group_"+id+"_folder_"+myid[3]);
                var temp = imgcheck.parentNode.id.split("_");
                var ch = imgcheck.parentNode;
                if (temp[0] == "group")
                {
                    while (ch.nextSibling != null)
                    { 
                        ch = ch.nextSibling;
                        temp = ch.id.split("_");
                        if (temp[0] == "group")
                        {
                            break;
                        }
                        temp = ch.id.split("_");
                        var elm = WFX.GetElement("user_"+id+"_ch_"+temp[2]);
                        foldcheck.src= "/sysimages/treechecklist/folderc.png";
                        var plus = WFX.GetElement("group_"+id+"_c_"+myid[3]);
                        plus.src = "/sysimages/treechecklist/plus.png";
                        WFX.HideElement(elm.parentNode);
                    } 
                }
                break;
            }
        }
        
    };
    
    var SelectListItem = function(element)
    {
        if (selected_id != null)
        {
            var selected = WFX.GetElement(selected_id);
            selected.style.color = "#000000";
            selected.style.background = "#ffffff";
        }  

        if (element != null)
        {
            var to_select = WFX.GetElement(element);
            to_select.style.color = "#ffffff";
            to_select.style.background = "#316ac5"; 
            selected_id = element.id;
            var temp = selected_id.split("_");
            if (temp[0] == "group")
            {
               var elm = WFX.GetElement("group_"+id+"_ch_"+temp[2]);
               elm.focus();
            }
            else
            {
                var elm = WFX.GetElement("user_"+id+"_ch_"+temp[2]);
                elm.focus();
            }
        }  
        else
        {
            selected_id = null;
        } 
    };

    this.Build = function(width, height)
    {
        tree_height = height || 120;
        tree_width = width || 120;
        
        var out = "<div id='tree_"+id+"' style='height:"+tree_height+"px; width:"+tree_width+"px; overflow:auto; background-color:#ffffff;border-style:solid; border-color:#898c95; border-width:1px;'></div>";
            out +="<input type='hidden' id='"+id+"' name='"+id+"' />";
        return out;
    };
    
    this.Show = function(width, height)
    {  
        document.write(this.Build(width, height));
    };
    
    this.SetFocus = function()
    {
        var tree = WFX.GetElement("tree_"+id);
        tree.focus();
    };
    
    var CollectCheckedIds = function()
    {
        var elstrings = [];
        var k = 0;
        for (var i=0; i<items2.length; i++)
        {
            for (var j=0; j< items2[i][1].length; j++)
            {   
                var check = WFX.GetElement("user_"+id+"_ch_"+k);
                if (check.checked == true)
                {
                    elstrings[elstrings.length] = items2[i][1][j][1];    
                }
                k++;
            }
        }
        return elstrings;
    };
    
    var mousemove_handlers = [];
    
    var RunMouseMoveHandlers = function(e)
    {
        for (var i=0; i<mousemove_handlers.length; i++)
        {
            mousemove_handlers[i](e, id);
        }   
    };
    
    this.AddMouseMoveHandler = function(handler)
    {
        mousemove_handlers[mousemove_handlers.length] = handler;
    };
    
    var mouseover_handlers = [];
    
    var RunMouseOverHandlers = function(e)
    {
        for (var i=0; i < mouseover_handlers.length; i++)
        {
            var tree = WFX.GetElement("tree_"+id);
            var item = WFX.Events.SrcElement(e);
            var index = item.id.split("_");
            var hidden_id = index[0]+"_"+id+"_hidden_"+index[index.length - 1];
            var el = WFX.GetElement(hidden_id);
            var isGroup = false;
            if (index[0] == "group")
            {
                isGroup = true;
            }
            
            mouseover_handlers[i](e, id, el.value, isGroup);
        }   
    };
    
    this.AddMouseOverHandler = function(handler)
    {
        mouseover_handlers[mouseover_handlers.length] = handler;
    };
        
    var mouseout_handlers = [];
    
    var RunMouseOutHandlers = function(e)
    {
        for (var i=0; i<mouseout_handlers.length; i++)
        {
            mouseout_handlers[i](e, id);
        }
    };
    
    this.AddMouseOutHandler = function(handler)
    {
        mouseout_handlers[mouseout_handlers.length] = handler;
    };
    
    var check_change_handlers = [];
    var RunCheckChangeHandlers = function(e)
    {
        var elstrings = CollectCheckedStrings();
        
        for (var i=0; i<check_change_handlers.length; i++)
        {
            var tree = WFX.GetElement("tree_"+id);
            check_change_handlers[i](id, elstrings);
        }   
    };

    this.AddCheckChangeEventHandler = function(handler)
    {
        check_change_handlers[check_change_handlers.length] = handler;
    };
    
    this.GetValue = function()
    {
        var hidden = WFX.GetElement(id);
        return hidden.value;  
    };
    
    this.SetValue = function(val)
    {
        var intv = setInterval(function()
        {
            if (busy == true)
            {
                return;
            }
            else
            {
                clearInterval(intv);
            }
            
            _setvalue(val);
        },
        100);
        
        
    };
    
    var _setvalue = function(val)
    {
        var tree = WFX.GetElement("tree_"+id);
        var current = tree.firstChild;
        
        var hidden = WFX.GetElement(id);
        hidden.value = val;
        
        var ids = val.split("|");

        var last_group = null;
        var count =0;
        var checked = 0;
        while(current != null)
        {
            if(current.id.split("_")[0]=="group")
            {
                if (last_group != null)
                {
                    var group_check = WFX.GetElement("group_"+id+"_ch_"+(last_group.id.split("_")[2]));
                       
                    var old_check = WFX.GetElement(group_check);
                    var old_check_parent = old_check.parentNode;
                        
                    var new_check = document.createElement("input");
                    new_check.setAttribute("id", old_check.id);
                    new_check.setAttribute("type", "checkbox");
                        
                    var i = group_check.id.split("_")[3];
                    var label = WFX.GetElement("group_"+id+"_folder_"+i);
                    old_check_parent.removeChild(old_check);
                    old_check_parent.insertBefore(new_check, label);
                    
                    if (count == checked)
                    {
                        new_check.setAttribute("checked", "checked");
                    }
                    
                    WFX.Events.AddEventHandler('click', ("group_"+id+"_ch_"+i), CheckChange); 
                    WFX.Events.AddEventHandler('mousedown', ("group_"+id+"_ch_"+i), function(e)
                    {
                        var curchek = WFX.Events.SrcElement(e);
                        SelectListItem(curchek.parentNode);
                    });

                    count = 0;
                    checked = 0;
                }
            
            
                last_group = current;
            }
            else
            {
                var h = WFX.GetElement("user_"+id+"_hidden_"+(current.id.split("_")[2]));

                var ch = WFX.GetElement("user_"+id+"_ch_"+current.id.split("_")[2]);
                var temp_id = ch.id;
                var parent = ch.parentNode;
                
                //WFX.Events.RemoveEventHandler('click', ("user_"+id+"_ch_"+current.id.split("_")[2]), check_event1);
                //WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+current.id.split("_")[2]), check_event3);                
                parent.removeChild(ch);
                
                var new_check = document.createElement("input");
                new_check.setAttribute("id", temp_id);
                new_check.setAttribute("type", "checkbox");
                var label = WFX.GetElement("user_"+id+"_title_"+current.id.split("_")[2]);
                parent.insertBefore(new_check, label);
                
                for (var i=0; i<ids.length; ++i)
                {
                    if (ids[i] == h.value)
                    {
                        new_check.setAttribute("checked", "checked");
                        checked++;
                    }
                }                  
                CheckGroupIfAll(current.id.split("_")[2]);
                //WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+current.id.split("_")[2]), check_event2);
                //WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+current.id.split("_")[2]), check_event1);
                //WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+current.id.split("_")[2]), check_event3);

                count++;
            }
            
            // ----->>
            current = current.nextSibling;
            if (current == null)
            {
                if (last_group != null)
                {
                    var group_check = WFX.GetElement("group_"+id+"_ch_"+(last_group.id.split("_")[2]));
                       
                    var old_check = WFX.GetElement(group_check);
                    var old_check_parent = old_check.parentNode;
                        
                    var new_check = document.createElement("input");
                    new_check.setAttribute("id", old_check.id);
                    new_check.setAttribute("type", "checkbox");
                        
                    var i = group_check.id.split("_")[3];
                    var label = WFX.GetElement("group_"+id+"_folder_"+i);
                    old_check_parent.removeChild(old_check);
                    old_check_parent.insertBefore(new_check, label);
                    
                    if (count == checked)
                    {
                        new_check.setAttribute("checked", "checked");
                    }
                    
                    WFX.Events.AddEventHandler('click', ("group_"+id+"_ch_"+i), CheckChange); 
                    WFX.Events.AddEventHandler('mousedown', ("group_"+id+"_ch_"+i), function(e)
                    {
                        var curchek = WFX.Events.SrcElement(e);
                        SelectListItem(curchek.parentNode);
                    });

                    count = 0;
                    checked = 0;
                }
            }
        }
        
        /*for (var k=0; k< ids_arr.length; k++)
        {
            for (var i=0; i<items2.length; i++)
            {
                for (var j=0; j< items2[i][1].length; j++)
                {  
                    if (items2[i][1][j][1] == ids_arr[k])
                    {
                        while(current)
                        {
                            if (current.id.split("_")[0] == "user")
                            {
                                var hd = WFX.GetElement("user_"+id+"_hidden_"+current.id.split("_")[2]);
                                for (var p = 0; p<ids_arr.length; p++)
                                {
                                    if (hd.value == ids_arr[p])
                                    {
                                        var ch = WFX.GetElement("user_"+id+"_ch_"+current.id.split("_")[2]);
                                        var temp_id = ch.id;
                                        var parent = ch.parentNode;
                                        parent.removeChild(ch);
                                        var new_check = document.createElement("input");
                                        new_check.setAttribute("id", temp_id);
                                        new_check.setAttribute("type", "checkbox");
                                        var label = WFX.GetElement("user_"+id+"_title_"+current.id.split("_")[2]);
                                        parent.insertBefore(new_check, label);
                                        new_check.setAttribute("checked", "checked");
                                        WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+current.id.split("_")[2]), check_event2);
                                        WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+current.id.split("_")[2]), check_event1);
                                        WFX.Events.AddEventHandler('click', ("user_"+id+"_ch_"+current.id.split("_")[2]), check_event3);
                                        check_all_in_group(new_check);
                                    }
                                }
                            }
                            current = current.nextSibling;
                        }         
                    }
                }
            }
        }*/
    };
    
    this.IsReady = function()
    {
        return ready;
    }
    
    this.GetSelectedTitles = function()
    {
        var tree = WFX.GetElement("tree_"+id);
        var current = tree.firstChild;    
        var rez = [];
        while(current)
        {
            if (current.id.split("_")[0] == "user")
            {
                var check = WFX.GetElement("user_"+id+"_ch_"+current.id.split("_")[2]);
                if (check.checked == true)
                {
                    var title = WFX.GetElement("user_"+id+"_title_"+current.id.split("_")[2]);
                    rez[rez.length] = title.innerHTML;
                }
            }
            current = current.nextSibling;
        }
        return rez.join("|");
    };
    
    this.GetName = function()
    {
        return id;  
    };
};

WFX.Serialization = new function() 
{
	var collection = new Array();
	
	this.AddControl = function(window, control) 
	{

		if ((collection[window] instanceof Array) == false ) 
		{
			collection[window] = [];
		}
		
		collection[window][collection[window].length] = control;
	};

	this.ClearCollection = function(window) 
	{
		// очищает все контролы из массива окна
		collection[window] = null;
	};
	
	this.Serialize = function(window) 
	{
		
		var rez_arr = [];
		for (var i = 0; i < collection[window].length; i++) 
		{
			var rez = collection[window][i].GetName();
			
			if (collection[window][i] instanceof WFX.Controls.AutoSuggestTextField) 
			{
				rez += "$" + "AutoSuggestTextField";
			}
			
			if (collection[window][i] instanceof WFX.Controls.CheckBoxList) 
			{
				rez += "$" + "CheckBoxList";
			}
			if (collection[window][i] instanceof WFX.Controls.MultiStringField) 
			{
				rez += "$" + "MultiStringField";
			}
			if (collection[window][i] instanceof WFX.Controls.TextField) 
			{
				rez += "$" + "TextField";
			}
			if (collection[window][i] instanceof WFX.Controls.TreeCheckList) 
			{
				rez += "$" + "TreeCheckList";
			}
			
			if (collection[window][i] instanceof WFX.Controls.DropDownList)
			{
			    rez += "$" + "DropDownList";
			}
			if (collection[window][i] instanceof WFX.Controls.MultiLineTextField)
			{
			    rez += "$" + "MultiLineTextField";
			}
			if (collection[window][i] instanceof WFX.Controls.CheckBox)
			{
			    rez += "$" + "CheckBox";
			}
			if (collection[window][i] instanceof WFX.Controls.Calendar)
			{
			    rez += "$" + "Calendar";
			}
			if (collection[window][i] instanceof WFX.Controls.SimpleTree)
			{
			    rez += "$" + "SimpleTree";
			}
			if (collection[window][i] instanceof WFX.Controls.PostTextField)
			{
			    rez += "$" + "PostTextField";
			}

			rez += "$" + collection[window][i].GetValue();
			
			rez_arr[rez_arr.length] = rez;
			
		}

		return rez_arr.join('|');
	};

} ();

WFX.Controls.Window = function(name, caption, url, action, cancel_button_title, accept_button_title, close_button_title, expand_button_title) 
{
    WFX.Images.Preload("/sysimages/window/wnd-close-hover.png");
    WFX.Images.Preload("/sysimages/window/wnd-close-down.png");
    
    WFX.Images.Preload("/sysimages/window/wnd-resume-down.png");
    WFX.Images.Preload("/sysimages/window/wnd-resume-hover.png");
    WFX.Images.Preload("/sysimages/window/wnd-resume2.png");
    WFX.Images.Preload("/sysimages/window/wnd-resume2-down.png");
    WFX.Images.Preload("/sysimages/window/wnd-resume2-hover.png");
    
	this.Version = "1.0.1";

    var cancel_bt = cancel_button_title || "Отменить";
    var accept_bt = accept_button_title || "Подтвердить";
    var close_bt = close_button_title || "Закрыть";
    var expand_bt = expand_button_title || "Развернуть/восстановить";

	var id = name;
	var btn_close = new WFX.Controls.ImageButton("btn_close_" + id, "/sysimages/window/wnd-close.png", "/sysimages/window/wnd-close-hover.png", "/sysimages/window/wnd-close-down.png", close_bt);
	var btn_resize = new WFX.Controls.HolderButton("btn_exp_" + id, "/sysimages/window/wnd-resume.png", "/sysimages/window/wnd-resume-down.png", "/sysimages/window/wnd-resume-hover.png", "/sysimages/window/wnd-resume2.png", "/sysimages/window/wnd-resume2-down.png", "/sysimages/window/wnd-resume2-hover.png", expand_bt);
	var url = url;
	var action = action || false;
    var fullscreen = false;
	var caption = caption;
	var offsetX = null;
	var offsetY = null;
	var Zy = null;
	var h1y = null;
	var Zx = null;
	var w1x = null;
	var resoffsetX = null;
	var resoffsetY = null;

	var ready = false;
	var content = "";
	var dragelement = null;
	
	var _width = 0;
	var _height = 0;

    var resizeable = true;
    this.Resizeable = function(flag)
	{
        resizeable = flag;
	};
	
	
	
	var _CatchResponse = function(response) 
	{
	    
		var elm = WFX.GetElement(id);
		
		WFX.Opacity.FadeOut(elm, 1, 0, 200, 0, function()
        {
	        setTimeout(function()
	        {
	            WFX.Serialization.ClearCollection(id);
                document.body.removeChild(elm);
            }, 300);
        });
		
		var bg = WFX.GetElement(id + "__");
		
		WFX.Opacity.FadeOut(bg, 0.3, 0, 200, 0, function()
        {
            setTimeout(function()
	        {
	            btn_close.RemoveEventHandler(onCancelClick);
                document.body.removeChild(bg);
                RunCloseHandlers(true, response);
            }, 300);
        });
	};
		
	var _ResumeButtons = function()
	{
	    var ok = WFX.GetElement('ok_'+id);
        var cancel = WFX.GetElement('cancel_'+id);
        ok.removeAttribute('disabled');
        cancel.removeAttribute('disabled');
	};
    
    var req = new WFX.Ajax.Request(null, _CatchResponse, _ResumeButtons);
    
	var CaptureElement = function(e) 
	{
		if (WFX.Browser.Name == Browsers.Firefox || WFX.Browser.Name == Browsers.Chrome) 
		{
			offsetX = e.layerX;
			offsetY = e.layerY + 2;
		}
		else 
		{
			offsetX = e.offsetX;
			offsetY = e.offsetY + 2;
		}
	};

	var ReleaseElement = function(e) 
	{
		offsetX = null;
		offsetY = null;
	};

	var DragElement = function(e) 
	{
		var wind = WFX.GetElement(id);
		if (offsetY == null || offsetX == null) 
		{
			return;
		}
		if (WFX.Browser.Name == Browsers.Firefox ) 
		{
			wind.style.top = (document.documentElement.scrollTop + e.clientY - offsetY) + "px";
			wind.style.left = (document.documentElement.scrollLeft + e.clientX - offsetX) + "px";
		}
		else if ( WFX.Browser.Name == Browsers.Chrome) 
		{
			wind.style.top = (document.body.scrollTop + e.clientY - offsetY) + "px";
			wind.style.left = (document.body.scrollLeft + e.clientX - offsetX) + "px";
		}
		else 
		{
			wind.style.pixelTop = (document.documentElement.scrollTop + e.clientY - offsetY);
			wind.style.pixelLeft = (document.documentElement.scrollLeft + e.clientX - offsetX);
		}
		if (WFX.Browser.Name == Browsers.Firefox || WFX.Browser.Name == Browsers.Chrome) 
		{
			if (window.getSelection()) 
			{
				window.getSelection().removeAllRanges();
			}
		}
		else 
		{
			document.selection.clear();
		}
	};

	var onResizerMouseDown = function(e) 
	{
	    WFX.GetElement("content_"+id).style.height = 100 + "%";
		Zy = e.clientY - WFX.Position.GetTopPosition(id);
		Zx = e.clientX - WFX.Position.GetLeftPosition(id);
		var wind = WFX.GetElement(id);

		if (WFX.Browser.Name == Browsers.Firefox) 
		{
			h1y = parseInt(wind.style.height) - (e.clientY - Zy);
			w1x = parseInt(wind.style.width) - (e.clientX - Zx);
			resoffsetX = e.layerX;
			resoffsetY = e.layerY + 2;
		}
		else 
		{
			h1y = wind.style.pixelHeight - (e.clientY - Zy);
			w1x = wind.style.pixelWidth - (e.clientX - Zx);
			resoffsetX = e.offsetX;
			resoffsetY = e.offsetY + 2;
		}
	};

	var onResizerMouseUp = function(e) 
	{
		resoffsetX = null;
		resoffsetY = null;
	};

	var onResizerMouseMove = function(e) 
	{
		var unf = WFX.GetElement("unfocus_" + id);
		if (resoffsetY == null || resoffsetX == null) 
		{
			return;
		}

		var y = ((e.clientY - Zy) + h1y);
		var x = ((e.clientX - Zx) + w1x);

		var wind = WFX.GetElement(id);
		if (WFX.Browser.Name == Browsers.Firefox) 
		{

			if (y >= _height) 
			{
				wind.style.height = y + "px";
			}

			if (x >= _width) 
			{
				wind.style.width = x + "px";
			}

			if (y >= _height) 
			{
				unf.style.height = y + "px";
			}

			if (x >= _width) 
			{
				unf.style.width = x + "px";
			}
			window.getSelection().removeAllRanges();
		}
		else 
		{

			if (y >= _height) 
			{
				wind.style.pixelHeight = y;
			}

			if (x >= _width) 
			{
				wind.style.pixelWidth = x;
			}

			if (y >= _height) 
			{
				unf.style.pixelHeight = y;
			}

			if (x >= _width) 
			{
				unf.style.pixelWidth = x;
			}

		}
	};
    
    var onResize = function(e)
    {
    
        var el = WFX.GetElement(id);
        if (!fullscreen)
        {
            if (WFX.Browser.Name == Browsers.Chrome)
            {
		        WFX.Position.Move(el, document.documentElement.scrollLeft,document.body.scrollTop);
	        }
	        else
	        {
	           WFX.Position.Move(el, document.documentElement.scrollLeft,document.documentElement.scrollTop); 
	        }
		    el.style.width = document.documentElement.clientWidth + "px";
		    if (WFX.Browser.Name == Browsers.Chrome || WFX.Browser.Name == Browsers.IE) 
		    {
		        el.style.height = (document.documentElement.clientHeight - 48) + "px"; 
		    }
		    else
		    {
		        el.style.height = (document.documentElement.clientHeight - 46) + "px";
		    }
		    WFX.GetElement("content_"+id).style.height = 100 + "%";
            WFX.GetElement("resizer_"+id).style.visibility = "hidden";
            fullscreen=true;
        }
        else
        {
            WFX.Sizes.SetHeight(el, _height);    
            WFX.Sizes.SetWidth(el, _width);
            WFX.Position.WatchForCenter(el);
            WFX.GetElement("resizer_"+id).style.visibility = "";
            fullscreen=false;
        }
    };
    
    this.TwoButtons = true;
    
	this.Create = function(width, height) 
	{
	   height -= 48;
		_width = width;
		_height = height;

        
        
		var o = document.createElement("div");
		//WFX.Opacity.SetOpacity(o, 0.3);
		document.body.appendChild(o);
		o.setAttribute("id", id + "__");
		o.style.position = "absolute";
		//o.style.backgroundColor = "#000000";
		o.style.border = "0px solid";
		o.style.backgroundImage = "url(/sysimages/trans-30-black.png)";
		
		WFX.Position.WatchForClientBegin(o);
		WFX.Sizes.Expand(o);
		WFX.Sizes.WatchForProportion(o);

		var w = document.createElement("div");
		w.setAttribute("id", id);
		w.style.position = "absolute";
		w.style.backgroundColor = "#f7f6f6";
		w.style.border = "0px #707070 solid";
       
		document.body.appendChild(w);

		if (WFX.Browser.Name == Browsers.Firefox) 
		{
			w.style.width = width + "px";
			w.style.height = height + "px";
		}
		else
		{
			w.style.pixelWidth = width;
			w.style.pixelHeight = height;
		}

		w.innerHTML =
		'<table border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse; -moz-user-select:none; -khtml-user-select:none;  width:100%; cursor:default; background-image:url(/sysimages/window/wnd-caption.png); background-repeat:repeat-x;">' +
			'<tr>' +
				'<td height="22px" style="font-weight:bold;" id="caption_' + id + '">'+
				    
				    '<table border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse;"><tr><td width="3px"></td><td>'+
				    '<span style="background-image:url(/sysimages/window/window-ico.png); background-repeat:no-repeat;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></td>' +
        			'<td><div style=" margin-bottom:2px; font-size:12px; font-family:Tahoma;">'+caption +'</div></td></tr></table>'+
				
				'</td>' +
				'<td width="20px" align="right">' + ((resizeable)?btn_resize.Build(15, 14):'') +
       			'</td>' +
       			'<td width="20px" align="right">' + btn_close.Build(15, 14) +
				'</td>' +
				'<td width="2px" align="right">&nbsp;' +
				'</td>' +
			'</tr>' +
		'</table>' +
		
		
		'<iframe src="" hspace="0" frameborder="0" marginheight="0" vspace="0" id="content_' + id + '" style="border-style:solid; border-width:0px; margin-bottom:0px;" width="100%" height="'+(height-48)+'"></iframe>' +

		
		'<table border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse; width:100%; background-image:url(/sysicons/controlbkg.gif); background-repeat:repeat-x;">' +
			'<tr height="3px" style="background-color:#f7f6f6;">' +
				'<td>' +
				'</td>' +
				'<td>' +
				'</td>' +
			'</tr>' +
			'<tr style="background-color:#f7f6f6;">' +
    			'<td>' +
					'<table border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse; width:100%;">' +
						'<tr>' +
							'<td align="left">' +
								('<input type="button" id="'+((this.TwoButtons == true)?("ok"):("cancel"))+'_' + id + '" name="'+((this.TwoButtons == true)?("ok"):("cancel"))+'_' + id + '" value="'+((this.TwoButtons == true)?(accept_bt):(close_bt))+'" />') +
							'</td>' +
							'<td align="right">' +
                    			((this.TwoButtons == true)?('<input  type="button" id="cancel_' + id + '" name="cancel_' + id + '" value="'+cancel_bt+'" />'):("")) +
							'</td>' +
						'</tr>' +
					'</table>' +
				'</td>' +
				'<td width="'+(resizeable?'20':'0')+'px" align="right">' +
					((resizeable)?('<div style="width:20px; height:20px; background-image:url(/sysimages/window/wnd-resizer.png);"  id="resizer_' + id + '"></div>'):"") +
				'</td>' +
  			'</tr>' +
		'</table>' +

        '<div id="unfocus_' + id + '" style="position:absolute; top:18px; width:400px; height:400px; background-color:#FFFFFF; display:none;"></div>';
           
        WFX.Events.AddEventHandler("load", "content_"+id, function(e)
        {
            WFX.GetElement("content_"+id).style.height = 100 + "%";
            
		});
		
		
		WFX.Events.AddEventHandler("resize", window, function(e)
        {
            if (fullscreen == true)
            {
               onResize(e);
            }
		});
           
        if (action == false)
        {
            w.innerHTML = ("<iframe id='upload_target_"+id+"' name='upload_target_"+id+"' src='' style='width:0;height:0;border:0px solid #ffffff;'></iframe>" + w.innerHTML);
        }   
        
        //w.innerHTML = '<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;"><tr><td width="4" height="4" style="background-image:url(/sysimages/window/shd-lt.png);">&nbsp;</td><td style="background-image:url(/sysimages/window/shd-t.png); background-repeat:repeat-x;"></td><td width="4" height="4" style="background-image:url(/sysimages/window/shd-rt.png);"></td></tr><tr><td style="background-image:url(/sysimages/window/shd-l.png); background-repeat:repeat-y;">&nbsp;</td><td>'+w.innerHTML;
        //w.innerHTML = w.innerHTML+'</td><td style="background-image:url(/sysimages/window/shd-r.png); background-repeat:repeat-y;"></td></tr><tr><td width="4" height="4" style="background-image:url(/sysimages/window/shd-lb.png);">&nbsp;</td><td style="background-image:url(/sysimages/window/shd-b.png); background-repeat:repeat-x;"></td><td width="4" height="4" style="background-image:url(/sysimages/window/shd-rb.png);"></td></tr></table>';
         
		this.CenterWindow();
		

		var mywnd = WFX.GetElement("caption_" + id);

        WFX.Events.AddEventHandler("load", "upload_target_"+id, function(e)
        {
			var iframe = (WFX.Browser.Name == Browsers.Firefox)? (WFX.GetElement("upload_target_"+id)):(frames["upload_target_"+id]);
			var response = (WFX.Browser.Name == Browsers.Firefox)? (iframe.contentDocument.documentElement.firstChild.nextSibling.innerHTML):(iframe.document.body.innerHTML);
	        
	        if (response.match("Fatal error"))
	        {
	            alert(response);
	            var ok = WFX.GetElement('ok_'+id);
                var cancel = WFX.GetElement('cancel_'+id);
                ok.removeAttribute('disabled');
                cancel.removeAttribute('disabled');
                
                return;
	        }
	        
			if (response == "" || isNaN(parseInt(response.split("::")[0])))
			{
			    var ok = WFX.GetElement('ok_'+id);
                var cancel = WFX.GetElement('cancel_'+id);
                ok.removeAttribute('disabled');
                cancel.removeAttribute('disabled');
                
				return;
			}
			else
			{
			
			    var msg = response.split("::");

                if (msg.length > 1) 
                {
	                msg = msg[1];
                }
        	    
                switch (parseInt(response))
                {
	                case 200:
	                {
		                _CatchResponse(response.substr(5));
		                break;
	                }

	                case 501:
	                {
		                alert("Ошибка базы данных.\n" + msg);
		                var ok = WFX.GetElement('ok_'+id);
                        var cancel = WFX.GetElement('cancel_'+id);
                        ok.removeAttribute('disabled');
                        cancel.removeAttribute('disabled');
		                break;
	                }

	                case 800:
	                {
		                alert("Ошибка ввода данных.\n" + msg);
		                var ok = WFX.GetElement('ok_'+id);
                        var cancel = WFX.GetElement('cancel_'+id);
                        ok.removeAttribute('disabled');
                        cancel.removeAttribute('disabled');
		                break;
	                }
        			
	                case 900:
	                {
	                    alert("Сообщение безопасности.\n"+msg);
	                    var ok = WFX.GetElement('ok_'+id);
                        var cancel = WFX.GetElement('cancel_'+id);
                        ok.removeAttribute('disabled');
                        cancel.removeAttribute('disabled');
	                    break;
	                }

	                default:
	                {
		                alert(msg);
		                var ok = WFX.GetElement('ok_'+id);
                        var cancel = WFX.GetElement('cancel_'+id);
                        if (ok)
                        {
                            ok.removeAttribute('disabled');
                        }
                        cancel.removeAttribute('disabled');
	                }
                }
			}
		});

		WFX.Events.AddEventHandler("mousedown", mywnd, function(e) 
		{
			var unf = WFX.GetElement("unfocus_" + id);
			var wnd = WFX.GetElement(id);
			var frm = WFX.GetElement("content_" + id);
			WFX.ShowElement(unf);
			if (WFX.Browser.Name == Browsers.Firefox) 
			{
				unf.style.width = (wnd.style.width);
				unf.style.height = WFX.Position.GetHeight(frm) + "px";
			}
			else 
			{
				unf.style.pixelWidth = wnd.style.pixelWidth;
				unf.style.pixelHeight = WFX.Position.GetHeight(frm);
			}
			unf.style.backgroundColor = "#FFFFFF";
			WFX.Opacity.SetOpacity(unf, 0.3);
		});

		WFX.Events.AddEventHandler("mouseup", document.body, function(e) 
		{
			var unf = WFX.GetElement("unfocus_" + id);
			WFX.HideElement(unf);
		});
		
		WFX.Events.AddEventHandler("mousedown", mywnd, CaptureElement);
		WFX.Events.AddEventHandler("mouseup", document.body, ReleaseElement);
		WFX.Events.AddEventHandler("mousemove", document.body, DragElement);

        if (this.TwoButtons == true)
        {
		    WFX.Events.AddEventHandler("click", "ok_" + id, onOkClick);
		}
		WFX.Events.AddEventHandler("click", "cancel_" + id, onCancelClick);

		btn_close.AddMouseClickHandler(onCancelClick);
        btn_resize.AddMouseClickHandler(onResize);
        
        if (resizeable)
        {
		    WFX.Events.AddEventHandler("mousedown", "resizer_" + id, onResizerMouseDown);
		    WFX.Events.AddEventHandler("mousedown", "resizer_" + id, function(e) 
		    {
			    var unf = WFX.GetElement("unfocus_" + id);
			    var res = WFX.GetElement("resizer_" + id);
			    var frm = WFX.GetElement("content_" + id);
			    WFX.ShowElement(unf);
			    if (WFX.Browser.Name == Browsers.Firefox) 
			    {
				    unf.style.width = (res.style.pixelWidth - 100) + "px";
				    unf.style.height = WFX.Position.GetHeight(frm) - 3 + "px";
			    }
			    else 
			    {
				    unf.style.pixelwidth = res.style.pixelWidth;
				    unf.style.pixelHeight = WFX.Position.GetHeight(frm) - 3;
			    }
			    unf.style.backgroundColor = "#FFFFFF";
			    WFX.Opacity.SetOpacity(unf, 0.3);
		    });
		    WFX.Events.AddEventHandler("mousemove", document.body, onResizerMouseMove);
		    WFX.Events.AddEventHandler("mouseup", document.body, onResizerMouseUp);
        }
	    var container = WFX.GetElement("content_" + id);
	    container.src = url;
	    var unf = WFX.GetElement("unfocus_" + id);
	};

	var onOkClick = function() 
	{
	    var ok = WFX.GetElement('ok_'+id);
        var cancel = WFX.GetElement('cancel_'+id);
        ok.setAttribute('disabled', 'disabled');
        cancel.setAttribute('disabled', 'disabled');
        
	    if (action != false)
	    {
		    var container = WFX.GetElement("content_" + id);
		    var s = "";
    		
		    if (WFX.Browser.Name == Browsers.Firefox) 
		    {
			    s = window.frames[window.frames.length - 1].WFX.Serialization.Serialize(id);
		    }
		    else 
		    {
			    s = window.frames["content_" + id].WFX.Serialization.Serialize(id);
		    }

		    req.Post(action, WFX.Ajax.EncType.FormUrlencoded, [["content", s]]);
		    WFX.Position.StopWatchForClientBegin(WFX.GetElement("id", id + "__"));
            WFX.Sizes.StopWatchForProportion(WFX.GetElement("id", id + "__"));
        }
        else
        {
            var content_frame = null;
    		
		    if (WFX.Browser.Name == Browsers.Firefox) 
		    {
			    content_frame = window.frames[window.frames.length - 1];
		    }
		    else 
		    {
			    content_frame = window.frames["content_" + id];
		    }

		    if (content_frame.document.forms.length < 1)
		    {
		        alert("Не найдена форма в окне");
		        return;
		    }
		    if (content_frame.document.forms.length > 1)
		    {
		        alert("Окно может содержать только одну форму");
		        return;
		    }
		    
		    content_frame.document.forms[0].target = "upload_target_"+id;
		    content_frame.document.forms[0].submit();
        }
	};
          
	var onCancelClick = function() 
	{
	    var ok = WFX.GetElement('ok_'+id);
        var cancel = WFX.GetElement('cancel_'+id);
        if (ok) ok.setAttribute('disabled', 'disabled');
        cancel.setAttribute('disabled', 'disabled');
		                
	    var elm = WFX.GetElement(id);
	    
	    WFX.Opacity.FadeOut(elm, 1, 0, 200, 0, function()
		{
			setTimeout(function()
			{
			    WFX.Serialization.ClearCollection(id);
		        document.body.removeChild(elm);
		    }, 300);
		});
		
		var bg = WFX.GetElement(id + "__");
								
		WFX.Opacity.FadeOut(bg, 0.3, 0, 200, 0, function()
		{
		    setTimeout(function()
			{
			    btn_close.RemoveEventHandler(onCancelClick);
		        document.body.removeChild(bg);
                RunCloseHandlers(false);
            }, 300);
		});
	};
    
    var close_handlers = [];
    this.AddCloseHandler = function(handler) 
    {
		close_handlers[close_handlers.length] = handler;
	};

	var RunCloseHandlers = function(cause, resp) 
	{
		for (var i = 0; i < close_handlers.length; i++) 
		{
			close_handlers[i](cause, resp);
		}
	};
	
	this.RemoveCloseHandler = function(rem_handler)
	{
	    var handlers2 = [];
	    for (var i=0; i<close_handlers.length; i++)
	    {
	        if (close_handlers[i] != rem_handler)
	        {
	            handlers2[handlers2.length] = handler[i];
	        }
	    }    
	    close_handlers = handlers2;
	};

	var create_handlers = [];
	this.AddCreateHandler = function(handler) 
	{
		create_handlers[create_handlers.length] = handler;
	};

	var RunCreateHandlers = function() 
	{
		for (var i = 0; i < create_handlers.length; i++) 
		{
			create_handlers[i]();
		}
	};
	this.RemoveCreateHandler = function(rem_handler) 
	{
		var handlers2 = [];
		for (var i = 0; i < create_handlers.length; i++) 
		{
			if (create_handlers[i] != rem_handler) 
			{
				handlers2[handlers2.length] = handler[i];
			}
		}
		create_handlers = handlers2;
	};


	this.MoveTo = function(x, y) 
	{
		WFX.Position.Move(id, x, y);
	};

	this.CenterWindow = function() 
	{
		var elm = WFX.GetElement(id);

		WFX.Position.MoveToCenter(elm);
	};

	this.DestroyWindow = function() 
	{
		var elm = WFX.GetElement(id);
		if (elm != null) 
		{
			document.body.removeChild(elm);
			WFX.Serialization.ClearCollection(id);
		}
	};
};



WFX.Controls.ImageButton = function(name, normal, hover, down, title) 
{
	var id = name;
	var normal = normal;
	var hover = hover;
	var down = down;
    this.disable = false;
	var title = title;

	var _width = null;
	var _height = null;

	this.Build = function(width, height) 
	{
		_width = width;
		_height = height;
		var out = "<div title='"+title+"' id='" + id + "' style='width:" + width + "px; height:" + _height + "px;background-image:url(" + normal + ");'></div>";
        if (this.disable == false)
        {
	        WFX.Events.AddEventHandler('mouseover', id, function(e) {
		        var elm = WFX.GetElement(id);
		        elm.style.backgroundImage = "url(" + hover + ")";
	        });

	        WFX.Events.AddEventHandler('mouseout', id, function(e) {
		        var elm = WFX.GetElement(id);
		        elm.style.backgroundImage = "url(" + normal + ")";
	        });

	        WFX.Events.AddEventHandler('mousedown', id, function(e) {
		        var elm = WFX.GetElement(id);
		        elm.style.backgroundImage = "url(" + down + ")";
	        });

	        WFX.Events.AddEventHandler('mouseup', id, function(e) {
		        var elm = WFX.GetElement(id);
		        elm.style.backgroundImage = "url(" + hover + ")";
	        });
	        WFX.Events.AddEventHandler('click', id, RunMouseClickHandlers);
	    }
		return out;
	};

	this.Show = function(width, height) {
		document.write(this.Build(width, height));
	};

	var handlers = [];
	this.AddMouseClickHandler = function(handler) {
		handlers[handlers.length] = handler;
	};

	var RunMouseClickHandlers = function(e) {
		for (var i = 0; i < handlers.length; i++) {
			handlers[i](e);
		}
	};
	this.RemoveEventHandler = function(rem_handler)
	{
	    var handlers2 = [];
	    for (var i=0; i<handlers.length; i++)
	    {
	        if (handlers[i] != rem_handler)
	        {
	            handlers2[handlers2.length] = handler[i];
	        }
	    }    
	    handlers = handlers2;
	};
    this.GetName = function()
    {
        return id;  
    };
};

WFX.Controls.HolderButton = function(name, normal, down, hover, normal2, down2, hover2, title)
{
    var id = name;
    var normal = normal;
    var down = down;
    var hover = hover;
    var normal2 = normal2;
    var down2 = down2;
    var hover2 = hover2;
    var title = title;
    
    var _width = null;
    var _height = null;
    
    var press = false;
    
    this.Build = function(width, height)
    {
        _width = width;
        _height = height;
        
        var out = "<div title='"+title+"' id='"+id+"' style='width:"+width+"px; height:"+_height+"px;background-image:url("+normal+");'></div>"; 
        
        WFX.Events.AddEventHandler('mouseover', id, function(e)
        {
            var elm = WFX.GetElement(id);
            if (press == true)
            {
                elm.style.backgroundImage = "url("+hover2+")";
            }
            else
            {
                elm.style.backgroundImage = "url("+hover+")";
            } 
        }); 
        
        WFX.Events.AddEventHandler('mouseout', id, function(e)
        {
            var elm = WFX.GetElement(id);
            if (press == true)
            {
                elm.style.backgroundImage ="url("+normal2+")";
            }
            else
            {
                elm.style.backgroundImage ="url("+normal+")";
            }
        });
        
        WFX.Events.AddEventHandler('mousedown', id, function(e)
        {
            var elm = WFX.GetElement(id);
            if (press == true)
            {
                 elm.style.backgroundImage = "url("+down2+")";
                 press = false;
            }
            else
            {
                 elm.style.backgroundImage = "url("+down+")";
                 press = true;
            }
        });
        
        WFX.Events.AddEventHandler('mouseup', id, function(e)
        {
            var elm = WFX.GetElement(id);
            if (press == true)
            {
                elm.style.backgroundImage="url("+hover2+")";
            }
            else
            {
                elm.style.backgroundImage="url("+hover+")";
            }
        });
        
        WFX.Events.AddEventHandler('click', id, RunMouseClickHandlers);
        return out;    
    };
    
    this.Show = function(width, height)
    {
        document.write(this.Build(width, height));  
    };
    
    var handlers = [];
    this.AddMouseClickHandler = function(handler)
    {
        handlers[handlers.length] = handler;
    };
    
    var RunMouseClickHandlers = function(e)
    {
        for (var i=0; i<handlers.length; i++)
        {
            handlers[i](e, press);
        }   
    };    
    
};



WFX.Controls.ProgressBar = function(name)
{
	var id = name;

	this.Build = function(width, height)
	{
		var _width = width;
		var _height = height;
		var out = "<div style='position:relative;'>";
		out += "<table border='0' cellspacing='0' cellpadding='0' width='" + _width + "px' height='" + _height + "px'>";
		out += "<tr>";
		out += "<td id='fill_" + id + "' style='background-image:url(/sysimages/progressbar.png);'></td>";
		out += "<td style='background-color:#CCCCCC;'></td>";
		out += "</tr>";
		out += "</table>";
		out += "<div id='percents_" + id + "' style='position:absolute; text-align:center; display:inline; font-size:10px; top:1px; width:100%; height:" + _height + "px;'></div>";
		out += "</div>";

		return out;
	};

	this.Show = function(width, height)
	{
		document.write(this.Build(width, height));
	};

	this.SetPosition = function(pos)
	{
		var prg_fill = WFX.GetElement("fill_" + id);
		var percents = WFX.GetElement("percents_" + id);
		prg_fill.style.width = pos + "%";
		prg_fill.nextSibling.style.width = (100 - pos) + "%";
		percents.innerHTML = pos + "%";

	};

};

WFX.Controls.Calendar = function(name, curdate)
{
	this.Version = "1.0.0";

	var items = [];
	var id = name;
	var _width;

	var calendar_width = 200;
	var calendar_height = 143;

	if (curdate)
	{
		var mass = [];
		mass = curdate.split(".");

		if (mass[1] > 0)
		{
			mass[1] = mass[1] - 1;
		}
		else
		{
			mass[1] = 11;
			mass[2] = mass[2] - 1;
		}

		var now = new Date(mass[2], (mass[1]), mass[0]);
		var prev = new Date(mass[2], (mass[1]), mass[0]);
		var curDate = new Date(mass[2], (mass[1]), mass[0]);
		var currentMonth = now.getMonth();
	}
	else
	{
		var now = new Date();
		var prev = new Date();
		var curDate = new Date();
		var currentMonth = now.getMonth();
	}
	var month_change = false;
	var added_tr = false;


	var sel_cell = null;
	var setted_date = null;
	var today = curDate.getDate();

	var currentYear = now.getFullYear();
	now.setDate(1);

	if (now.getDay() == 0)
	    var dayOfWeek = 7;
	else
	    var dayOfWeek = now.getDay();
	    
	var dayOfWeekCheck = 0;
	var daysInMonth = 28;

	while (currentMonth == now.getMonth())
	{
		now.setDate(++daysInMonth);
	}

	--daysInMonth;

	prev.setMonth(currentMonth - 1);
	var prevDaysInMonth = 28;

	while ((currentMonth - 1) == prev.getMonth())
	{
		prev.setDate(++prevDaysInMonth);
	}
	--prevDaysInMonth;

	var k = 1;
	//----------------------------------------------------------------------
	var week_day = ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс", ];
	var month = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь", ];
    var _year = null;
    var _month = null;
    if (now.getMonth() == 0)
    {
         _month = month[currentMonth];    
        _year = now.getFullYear()-1;
    }
    else
    {
        _year = now.getFullYear();
        _month = month[currentMonth];
    }
	var now_bg_color = "#f1c1d4";
	var selected_bg_color = "#fde76e";
	var bg_color = "#FFFFFF";
	var normal_color = "#0000cc";
	var out_color = "#b6b9bd";

	this.LoadData = function()
	{
		var out = "<table style='background-color:#4682b4; border-collapse:collapse; background-image:url(/sysimages/calendar/bg.png);' border='0' width='100%' align='center' >";
		out += "<tr>";
		out += "<td width='10%'><img id='prev_year_" + id + "' src='/sysimages/calendar/prev-year.png' /></td>";
		out += "<td width='10%'><img id='prev_month_" + id + "' src='/sysimages/calendar/prev-month.png' /></td>";
		out += "<td width='10%'>&nbsp;</td>";
		out += "<td id='month_" + id + "'>" + _month + "</td>";
		out += "<td id='year_" + id + "'>" + _year + "</td>";
		out += "<td width='10%'>&nbsp;</td>";
		out += "<td width='10%'><img id='next_month_" + id + "' src='/sysimages/calendar/next-month.png' /></td>";
		out += "<td width='10%'><img id='next_year_" + id + "' src='/sysimages/calendar/next-year.png' /></td>";
		out += "</tr>";
		out += "<table>";
		out += "<table border='0' width='100%' cellpadding='2' cellspacing='0' style='background-color:#e7eaf5; border-collapse:collapse;' align='center'>";
		out += "<tr>";
		for (var i = 0; i < 7; i++)
		{
			out += "<td width='14%' align='center'>" + week_day[i] + "</td>";
		}
		out += "</tr>";
		out += "</table>";
		out += "<table style='border-collapse:collapse; border-color:#e2e2e2; border-width:1px; border-style:solid;' border='1' id='calendar_" + id + "' cellpadding='2' cellspacing='0' width='100%' align='center'>";
		var temp = 0;
		for (var i = 0; i < 5; i++)
		{
			out += "<tr>";
			for (var j = 0; j < 7; j++)
			{
				if (dayOfWeekCheck == dayOfWeek - 1)
				{
					if (k > daysInMonth)
					{
						k = 1;
						currentMonth++;
						if (currentMonth == 12)
						{
							currentMonth = 0;
						}
					}

					if (k == today && (curDate.getMonth() == currentMonth))
					{
						out += "<td id='cell_" + temp + "_" + id + "' align='center' style='background-color:" + now_bg_color + ";'><a style='color:" + normal_color + ";' href='javascript:void(0);'>" + k + "</a></td>";
						sel_cell = temp;
					}
					else
					{
						if (curDate.getMonth() == currentMonth)
							out += "<td id='cell_" + temp + "_" + id + "' align='center' style='background-color:#ffffff;'><a style='color:" + normal_color + ";' href='javascript:void(0);'>" + k + "</a></td>";
						else
							out += "<td id='cell_" + temp + "_" + id + "' align='center' style='background-color:#ffffff;'><a style='color:" + out_color + ";' href='javascript:void(0);'>" + k + "</a></td>";
					}
					k++;
				}
				else
				{
					out += "<td id='cell_" + temp + "_" + id + "' align='center' style='background-color:#ffffff;'><a style='color:" + out_color + ";' href='javascript:void(0);'>" + (prevDaysInMonth - (dayOfWeek - 2) + j) + "</a></td>";
					dayOfWeekCheck++;
				}
				temp++;
			}
			out += "</tr>";
		}

		if (currentMonth != 0 && currentMonth == now.getMonth())
		{
			// ВТОРОЕ УСЛОВИЕ ВОЗМОЖНО ПРИЙДЁТСЯ УБРАТЬ!!!!!!!
			currentMonth--;
		}

		out += "</table>";

		var d = WFX.GetElement("list_" + id);
		d.innerHTML = out;

		WFX.Events.AddEventHandler("click", "drop_" + id, function(e)
		{
			var elm = WFX.GetElement(id);
			var list = WFX.GetElement("date_" + id);

			var elm_y = WFX.Position.GetTopPosition(elm);

			if (document.documentElement.clientHeight - (elm_y - document.documentElement.scrollTop) > (_height + WFX.Position.GetHeight(elm)))
			{
				WFX.Position.SetPosition(list, elm, ((WFX.Browser.Name == Browsers.IE) ? 2 : 0), WFX.Position.GetHeight(elm));
			}
			else
			{
				if (elm_y < _height)
				{
					WFX.Position.SetPosition(list, elm, ((WFX.Browser.Name == Browsers.IE) ? 2 : 0), WFX.Position.GetHeight(elm));
				}
				else
				{
					WFX.Position.SetPosition(list, elm, ((WFX.Browser.Name == Browsers.IE) ? 2 : 0), -(_height));
				}
			}
			WFX.ShowHideElement(list);
		});

		WFX.Events.AddEventHandler("click", "next_month_" + id, function(e)
		{
			currentMonth++;
			if (currentMonth == 12)
			{
				currentMonth = 0;
			}
			if (added_tr == true)
			{
				var calendar = WFX.GetElement("calendar_" + id);
				var tr = WFX.GetElement("last_tr_" + id);
				calendar.firstChild.removeChild(tr);
				added_tr = false;
			}

			month_change = false;
			var next_month = WFX.GetElement("month_" + id);
			next_month.innerHTML = month[currentMonth];

			now.setMonth(currentMonth);
			now.setDate(1);
			var nowDayOfWeek = now.getDay();
			var nowDaysInMonth = 28;

			while (currentMonth == now.getMonth())
			{
				now.setDate(++nowDaysInMonth);
			}

			--nowDaysInMonth;

			if (currentMonth == 0)
			{
				var year = WFX.GetElement("year_" + id);
				year.innerHTML = now.getFullYear();
				currentMonth = 11;
				prev.setMonth(currentMonth);
				prevDaysInMonth = 28;
				while (currentMonth == prev.getMonth())
				{
					prev.setDate(++prevDaysInMonth);
				}
				currentMonth = 0;
			}
			else
			{
				prev.setMonth(currentMonth - 1);
				prevDaysInMonth = 28;
				while ((currentMonth - 1) == prev.getMonth())
				{
					prev.setDate(++prevDaysInMonth);
				}
			}
			--prevDaysInMonth;

			var cell = null;

			if (nowDayOfWeek == 0)
			{
				nowDayOfWeek = 7;
			}

			var temp = 0;
			k = 0;

			var cur_ = WFX.GetElement(id);
			cur_ = cur_.value.split(".");

			for (var i = 0; i < 35; i++)
			{
				if (temp == nowDayOfWeek - 1)
				{
					k++;
					if (k > nowDaysInMonth)
					{
						month_change = true;
						k = 1;
					}
					if (month_change == true)
					{
						cell = WFX.GetElement("cell_" + i + "_" + id);
						cell.firstChild.innerHTML = k;
						cell.style.background = bg_color; // след +1
						cell.firstChild.style.color = out_color;

						if (cur_[0] == k && cur_[1] == (now.getMonth() + 1) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}

					}
					else
					{
						cell = WFX.GetElement("cell_" + i + "_" + id);
						cell.firstChild.innerHTML = k;
						cell.style.background = bg_color; // тек
						cell.firstChild.style.color = normal_color;

						if (cur_[0] == k && cur_[1] == (now.getMonth()) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}

					}
				}
				else
				{
					for (var j = 0; j < nowDayOfWeek - 1; j++)
					{
						cell = WFX.GetElement("cell_" + j + "_" + id);
						cell.firstChild.innerHTML = (prevDaysInMonth - (nowDayOfWeek - 2) + j);
						cell.style.background = bg_color; // пред
						cell.firstChild.style.color = out_color;

						if (cur_[1].length == 2 && cur_[1].substr(0, 1) == "0")
						{
							cur_[1] = cur_[1].substr(1);
						}

						if (cur_[0] == ((prevDaysInMonth - (nowDayOfWeek - 2) + j)) && parseInt(cur_[1]) == (now.getMonth() - 1) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}

						temp++;
					}
					i = temp - 1;
				}
			}
			if (k < nowDaysInMonth && month_change == false)
			{
				var calendar = WFX.GetElement("calendar_" + id);
				var tr = document.createElement("tr");
				tr.setAttribute("id", "last_tr_" + id);
				calendar.firstChild.appendChild(tr);
				for (var i = 0; i < 7; i++)
				{
					k++;
					if (k > nowDaysInMonth)
					{
						k = 1;
						month_change = true;
					}
					var td = document.createElement("td");
					var a = document.createElement("a");
					a.setAttribute("href", "javascript:void(0);");
					a.innerHTML = k;
					td.appendChild(a);
					td.setAttribute("align", "center");
					td.setAttribute("id", "cell_" + (35 + i) + "_" + id);
					tr.appendChild(td);

					td.style.background = bg_color;
					if (month_change == true)
					{
						td.firstChild.style.color = out_color;
					}
					else
					{
						td.firstChild.style.color = normal_color;
					}

					WFX.Events.AddEventHandler("click", "cell_" + (35 + i) + "_" + id, GetData);
				}
				added_tr = true;
			}

			if (curDate.getMonth() == currentMonth && now.getFullYear() == currentYear)
			{
				var cell = WFX.GetElement("cell_" + sel_cell + "_" + id);

				cell.style.background = now_bg_color;
			}
		});

		WFX.Events.AddEventHandler("click", "prev_month_" + id, function(e)
		{
			if (added_tr == true)
			{
				var calendar = WFX.GetElement("calendar_" + id);
				var tr = WFX.GetElement("last_tr_" + id);
				calendar.firstChild.removeChild(tr);
				added_tr = false;
			}

			var prev_month = WFX.GetElement("month_" + id);
			month_change = false;
			if (currentMonth == 0)
			{
				prev_month.innerHTML = month[11];
				now.setDate(-31);
				var year = WFX.GetElement("year_" + id);
				year.innerHTML = now.getFullYear();
				currentMonth = 12;
				prev.setFullYear(now.getFullYear());
			}
			else
			{
				prev_month.innerHTML = month[currentMonth - 1];
				if (now.getFullYear != curDate.getFullYear())
				{
					now.setDate(-31);
					now.setMonth(currentMonth - 1);
				}
				else
				{
					now.setMonth(currentMonth - 1);
				}
			}

			now.setDate(1);

			var nowDayOfWeek = now.getDay();
			var nowDaysInMonth = 28;
			while ((currentMonth - 1) == now.getMonth())
			{
				now.setDate(++nowDaysInMonth);
			}
			--nowDaysInMonth;
			if (nowDayOfWeek != 1)
			{
				if (currentMonth == 1)
				{
					prev.setMonth(currentMonth - 1);
				}
				else
				{
					prev.setMonth(currentMonth - 2);
				}
				prevDaysInMonth = 28;
				if (currentMonth == 1)
				{
					while ((currentMonth - 1) == prev.getMonth())
					{
						prev.setDate(++prevDaysInMonth);
					}
				}
				else
				{
					while ((currentMonth - 2) == prev.getMonth())
					{
						prev.setDate(++prevDaysInMonth);
					}
				}
				--prevDaysInMonth;
			}
			var cell = null;

			if (nowDayOfWeek == 0)
			{
				nowDayOfWeek = 7;
			}
			var temp = 0;
			k = 0;

			var cur_ = WFX.GetElement(id);
			cur_ = cur_.value.split(".");

			for (var i = 0; i < 35; i++)
			{
				if (temp == nowDayOfWeek - 1)
				{
					k++;
					if (k > nowDaysInMonth)
					{
						month_change = true;
						k = 1;
					}
					if (month_change == true)
					{
						cell = WFX.GetElement("cell_" + i + "_" + id);
						cell.firstChild.innerHTML = k;
						cell.style.background = bg_color; // след +1
						cell.firstChild.style.color = out_color;

						if (cur_[0] == k && cur_[1] == (now.getMonth() + 1) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}
					}
					else
					{
						cell = WFX.GetElement("cell_" + i + "_" + id);
						cell.firstChild.innerHTML = k;
						cell.style.background = bg_color; // тек
						cell.firstChild.style.color = normal_color;

						if (cur_[0] == k && cur_[1] == (now.getMonth()) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}
					}
				}
				else
				{
					for (var j = 0; j < nowDayOfWeek - 1; j++)
					{
						cell = WFX.GetElement("cell_" + j + "_" + id);
						cell.firstChild.innerHTML = (prevDaysInMonth - (nowDayOfWeek - 2) + j);
						cell.style.background = bg_color; // пред
						cell.firstChild.style.color = out_color;

						if (cur_[1].length == 2 && cur_[1].substr(0, 1) == "0")
						{
							cur_[1] = cur_[1].substr(1);
						}

						if (cur_[0] == ((prevDaysInMonth - (nowDayOfWeek - 2) + j)) && parseInt(cur_[1]) == (now.getMonth() - 1) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}
						temp++;
					}
					i = temp - 1;
				}
			}
			currentMonth--;
			if (k < nowDaysInMonth && month_change == false)
			{
				var calendar = WFX.GetElement("calendar_" + id);
				var tr = document.createElement("tr");
				tr.setAttribute("id", "last_tr_" + id);
				calendar.firstChild.appendChild(tr);
				for (var i = 0; i < 7; i++)
				{
					k++;
					if (k > nowDaysInMonth)
					{
						k = 1;
						month_change = true;
					}
					var td = document.createElement("td");
					var a = document.createElement("a");
					a.setAttribute("href", "javascript:void(0);");
					a.innerHTML = k;
					td.appendChild(a);
					td.setAttribute("id", "cell_" + (35 + i) + "_" + id);
					td.setAttribute("align", "center");
					tr.appendChild(td);
					td.style.background = bg_color;
					if (month_change == true)
					{
						td.firstChild.style.color = out_color;
					}
					else
					{
						td.firstChild.style.color = normal_color;
					}
					WFX.Events.AddEventHandler("click", "cell_" + (35 + i) + "_" + id, GetData);
				}
				added_tr = true;
			}
			if (curDate.getMonth() == currentMonth && now.getFullYear() == currentYear)
			{
				var cell = WFX.GetElement("cell_" + sel_cell + "_" + id);
				cell.style.background = now_bg_color;
			}
		});

		WFX.Events.AddEventHandler("click", "next_year_" + id, function(e)
		{
			if (added_tr == true)
			{
				var calendar = WFX.GetElement("calendar_" + id);
				var tr = WFX.GetElement("last_tr_" + id);
				calendar.firstChild.removeChild(tr);
				added_tr = false;
			}
			var year = WFX.GetElement("year_" + id);
			if (now.getMonth() == 0)
				now.setFullYear(now.getFullYear());
			else
				now.setFullYear(now.getFullYear() + 1);
			year.innerHTML = now.getFullYear();
			now.setMonth(currentMonth);
			month_change = false;
			var nowDayOfWeek = now.getDay();
			var nowDaysInMonth = 28;
			while ((currentMonth) == now.getMonth())
			{
				now.setDate(++nowDaysInMonth);
			}
			--nowDaysInMonth;
			if (nowDayOfWeek != 1)
			{
				prev.setMonth(currentMonth - 1);
				prevDaysInMonth = 28;
				if (currentMonth == 0)
				{
					while (11 == prev.getMonth())
					{
						prev.setDate(++prevDaysInMonth);
					}
				}
				else
				{
					if (currentMonth == 1)
					{
						while ((currentMonth - 1) == prev.getMonth())
						{
							prev.setDate(++prevDaysInMonth);
						}
					}
					else
					{
						while ((currentMonth - 1) == prev.getMonth())
						{
							prev.setDate(++prevDaysInMonth);
						}
					}
				}
				--prevDaysInMonth;
			}
			var cell = null;

			if (nowDayOfWeek == 0)
			{
				nowDayOfWeek = 7;
			}
			var temp = 0;
			k = 0;

			var cur_ = WFX.GetElement(id);
			cur_ = cur_.value.split(".");

			for (var i = 0; i < 35; i++)
			{
				if (temp == nowDayOfWeek - 1)
				{
					k++;
					if (k > nowDaysInMonth)
					{
						month_change = true;
						k = 1;
					}
					if (month_change == true)
					{
						cell = WFX.GetElement("cell_" + i + "_" + id);
						cell.firstChild.innerHTML = k;
						cell.style.background = bg_color; // след +1
						cell.firstChild.style.color = out_color;

						if (cur_[0] == k && cur_[1] == (now.getMonth() + 1) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}
					}
					else
					{
						cell = WFX.GetElement("cell_" + i + "_" + id);
						cell.firstChild.innerHTML = k;
						cell.style.background = bg_color; // тек
						cell.firstChild.style.color = normal_color;

						if (cur_[0] == k && cur_[1] == (now.getMonth()) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}
					}
				}
				else
				{
					for (var j = 0; j < nowDayOfWeek - 1; j++)
					{
						cell = WFX.GetElement("cell_" + j + "_" + id);
						cell.firstChild.innerHTML = (prevDaysInMonth - (nowDayOfWeek - 2) + j);
						cell.style.background = bg_color; // пред
						cell.firstChild.style.color = out_color;

						if (cur_[1].length == 2 && cur_[1].substr(0, 1) == "0")
						{
							cur_[1] = cur_[1].substr(1);
						}

						if (cur_[0] == ((prevDaysInMonth - (nowDayOfWeek - 2) + j)) && parseInt(cur_[1]) == (now.getMonth() - 1) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}
						temp++;
					}
					i = temp - 1;
				}
			}
			if (k < nowDaysInMonth && month_change == false)
			{
				var calendar = WFX.GetElement("calendar_" + id);
				var tr = document.createElement("tr");
				tr.setAttribute("id", "last_tr_" + id);
				calendar.firstChild.appendChild(tr);
				for (var i = 0; i < 7; i++)
				{
					k++;
					if (k > nowDaysInMonth)
					{
						k = 1;
						month_change = true;
					}
					var td = document.createElement("td"); 
					var a = document.createElement("a");
					a.setAttribute("href", "javascript:void(0);");
					a.innerHTML = k;
					td.appendChild(a);
					td.setAttribute("id", "cell_" + (35 + i) + "_" + id);
					td.setAttribute("align", "center");
					tr.appendChild(td);
					td.style.background = bg_color;
					if (month_change == true)
					{
						td.firstChild.style.color = out_color;
					}
					else
					{
						td.firstChild.style.color = normal_color;
					}
					WFX.Events.AddEventHandler("click", "cell_" + (35 + i) + "_" + id, GetData);
				}
				added_tr = true;
			}
			if (curDate.getMonth() == currentMonth && now.getFullYear() == currentYear)
			{
				var cell = WFX.GetElement("cell_" + sel_cell + "_" + id);
				cell.style.background = now_bg_color;
			}

		});

		WFX.Events.AddEventHandler("click", "prev_year_" + id, function(e)
		{
			if (added_tr == true)
			{
				var calendar = WFX.GetElement("calendar_" + id);
				var tr = WFX.GetElement("last_tr_" + id);
				calendar.firstChild.removeChild(tr);
				added_tr = false;
			}
			var year = WFX.GetElement("year_" + id);
			if (now.getMonth() == 0)
				now.setFullYear(now.getFullYear() - 2);
			else
				now.setFullYear(now.getFullYear() - 1);
			year.innerHTML = now.getFullYear();
			now.setMonth(currentMonth);
			month_change = false;
			var nowDayOfWeek = now.getDay();
			var nowDaysInMonth = 28;
			while ((currentMonth) == now.getMonth())
			{
				now.setDate(++nowDaysInMonth);
			}
			--nowDaysInMonth;
			if (nowDayOfWeek != 1)
			{
				prev.setMonth(currentMonth - 1);
				prevDaysInMonth = 28;
				if (currentMonth == 0)
				{
					while (11 == prev.getMonth())
					{
						prev.setDate(++prevDaysInMonth);
					}
				}
				else
				{
					if (currentMonth == 1)
					{
						while ((currentMonth - 1) == prev.getMonth())
						{
							prev.setDate(++prevDaysInMonth);
						}
					}
					else
					{
						while ((currentMonth - 1) == prev.getMonth())
						{
							prev.setDate(++prevDaysInMonth);
						}
					}
				}
				--prevDaysInMonth;
			}
			var cell = null;

			if (nowDayOfWeek == 0)
			{
				nowDayOfWeek = 7;
			}
			var temp = 0;
			k = 0;

			var cur_ = WFX.GetElement(id);
			cur_ = cur_.value.split(".");

			for (var i = 0; i < 35; i++)
			{
				if (temp == nowDayOfWeek - 1)
				{
					k++;
					if (k > nowDaysInMonth)
					{
						month_change = true;
						k = 1;
					}
					if (month_change == true)
					{
						cell = WFX.GetElement("cell_" + i + "_" + id);
						cell.firstChild.innerHTML = k;
						cell.style.background = bg_color; // след +1
						cell.firstChild.style.color = out_color;

						if (cur_[0] == k && cur_[1] == (now.getMonth() + 1) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}
					}
					else
					{
						cell = WFX.GetElement("cell_" + i + "_" + id);
						cell.firstChild.innerHTML = k;
						cell.style.background = bg_color; // тек
						cell.firstChild.style.color = normal_color;

						if (cur_[0] == k && cur_[1] == (now.getMonth()) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}
					}
				}
				else
				{
					for (var j = 0; j < nowDayOfWeek - 1; j++)
					{
						cell = WFX.GetElement("cell_" + j + "_" + id);
						cell.firstChild.innerHTML = (prevDaysInMonth - (nowDayOfWeek - 2) + j);
						cell.style.background = bg_color; // пред
						cell.firstChild.style.color = out_color;

						if (cur_[1].length == 2 && cur_[1].substr(0, 1) == "0")
						{
							cur_[1] = cur_[1].substr(1);
						}

						if (cur_[0] == ((prevDaysInMonth - (nowDayOfWeek - 2) + j)) && parseInt(cur_[1]) == (now.getMonth() - 1) && cur_[2] == (now.getFullYear()))
						{
							cell.style.background = selected_bg_color;
						}
						temp++;
					}
					i = temp - 1;
				}
			}
			if (k < nowDaysInMonth && month_change == false)
			{
				var calendar = WFX.GetElement("calendar_" + id);
				var tr = document.createElement("tr");
				tr.setAttribute("id", "last_tr_" + id);
				calendar.firstChild.appendChild(tr);
				for (var i = 0; i < 7; i++)
				{
					k++;
					if (k > nowDaysInMonth)
					{
						k = 1;
						month_change = true;
					}
					var td = document.createElement("td");
					var a = document.createElement("a");
					a.setAttribute("href", "javascript:void(0);");
					a.innerHTML = k;
					td.appendChild(a);
					td.setAttribute("align", "center");
					td.setAttribute("id", "cell_" + (35 + i) + "_" + id);
					tr.appendChild(td);
					td.style.background = bg_color;
					if (month_change == true)
					{
						td.firstChild.style.color = out_color;
					}
					else
					{
						td.firstChild.style.color = normal_color;
					}
					WFX.Events.AddEventHandler("click", "cell_" + (35 + i) + "_" + id, GetData);
				}
				added_tr = true;
			}
			if (curDate.getMonth() == currentMonth && now.getFullYear() == currentYear)
			{
				var cell = WFX.GetElement("cell_" + sel_cell + "_" + id);
				cell.style.background = "#f1c1d4";
			}

		});

	};

	var onBtnClick = function(e)
	{
		var elm = WFX.GetElement(id);
		var list = WFX.GetElement("list_" + id);

		var elm_y = WFX.Position.GetTopPosition(elm);

		if (document.documentElement.clientHeight - (elm_y - document.documentElement.scrollTop) > (calendar_height + WFX.Position.GetHeight(elm)))
		{
			WFX.Position.SetPosition(list, elm, 1, WFX.Position.GetHeight(elm));
		}
		else
		{
			if (elm_y < calendar_height)
			{
				WFX.Position.SetPosition(list, elm, 0, WFX.Position.GetHeight(elm));
			}
			else
			{
				WFX.Position.SetPosition(list, elm, 0, -(calendar_height));
			}
		}
		WFX.ShowHideElement(list);
	};

	WFX.Events.AddEventHandler('click', 'btn_' + id, onBtnClick);
	WFX.Events.AddEventHandler('click', id, onBtnClick);
    if (curdate == "")
        curdate = WFX.Strings.Format(curDate.getDate(), 2)+"."+WFX.Strings.Format((curDate.getMonth()+1), 2)+"."+curDate.getFullYear();
	this.Build = function(width)
	{
		var out = "";
		_width = width || 200;
            
		out += "<div style='width:" + _width + "px; display:inline;'>";
		out += "<input value='" + curdate + "' readonly='readonly' autocomplete='off' style='cursor:default;border-style:solid;border-color:#707070;border-width:1px;margin-bottom:1px; width:" + (_width - 18) + "px;' type='text' id='" + id + "' name='" + id + "' />";
		out += "<input id='btn_" + id + "' type='button' style='width:18px;' value='v' />";

		out += '<div id="list_' + id + '" style="z-index:1000; cursor:default; overflow:auto; display:none; width:' + ((WFX.Browser.Name == Browsers.Opera) ? (calendar_width + 6) : ((WFX.Browser.Name == Browsers.Firefox) ? (calendar_width + 2) : (calendar_width + 3))) + 'px; height:' + calendar_height + 'px; background-color:#FFFFFF; border-style:solid; border-width:1px; border-color:#7f9db9; position:absolute;"></div>';
		out += "</div>";

		return out;
	};

	this.Show = function(width)
	{
		document.write(this.Build(width));

		for (var i = 0; i < 35; i++)
		{
			WFX.Events.AddEventHandler("click", "cell_" + i + "_" + id, GetData);
		}

	};

	var selel = null;

	var GetData = function(e)
	{
		var result = WFX.GetElement(id);
		var year = WFX.GetElement("year_" + id);
		var sel_elm = WFX.Events.SrcElement(e);
		var getCellNumber = (sel_elm.parentNode.id).split("_");

		if (sel_elm.tagName == "A")
		{

			if (selel != null)
			{
				if (curDate.getMonth() == currentMonth && now.getFullYear() == currentYear && selel.parentNode.id == ("cell_" + sel_cell + "_" + id))
				{
					var cell = WFX.GetElement("cell_" + sel_cell + "_" + id);
					cell.style.background = now_bg_color;
				}
				else
				{
					selel.parentNode.style.background = "#FFFFFF";
				}
			}

			selel = sel_elm;

			if (curDate.getMonth() == currentMonth && now.getFullYear() == currentYear && selel.parentNode.id == ("cell_" + sel_cell + "_" + id))
			{
				var cell = WFX.GetElement("cell_" + sel_cell + "_" + id);
				cell.style.background = now_bg_color;
			}
			else
			{
				selel.parentNode.style.background = selected_bg_color;
			}

			if (getCellNumber[1] < 7)
			{
				if (sel_elm.innerHTML > 7)
				{
					if (now.getMonth() == 0)
						result.value = ((sel_elm.innerHTML < 10) ? ("0" + sel_elm.innerHTML) : (sel_elm.innerHTML)) + "." + "01" + "." + (now.getFullYear() - 1);
					else
					{
						result.value = ((sel_elm.innerHTML < 10) ? ("0" + sel_elm.innerHTML) : (sel_elm.innerHTML)) + "." + ((now.getMonth() - 1 == 0) ? (12) : (((now.getMonth() - 1 < 10) ? ("0" + (now.getMonth() - 1)) : (now.getMonth() - 1)))) + "." + ((now.getMonth() - 1 == 0) ? (now.getFullYear() - 1) : (year.innerHTML));
					}
				}
				else
				{
					if (now.getMonth() == 0)
						result.value = ((sel_elm.innerHTML < 10) ? ("0" + sel_elm.innerHTML) : (sel_elm.innerHTML)) + "." + 12 + "." + ((now.getMonth() == 0) ? (now.getFullYear() - 1) : (year.innerHTML));
					else
						result.value = ((sel_elm.innerHTML < 10) ? ("0" + sel_elm.innerHTML) : (sel_elm.innerHTML)) + "." + ((now.getMonth() < 10) ? ("0" + now.getMonth()) : (now.getMonth())) + "." + ((now.getMonth() == 0) ? (now.getFullYear()) : (year.innerHTML));
				}
			}
			if (getCellNumber[1] > 27)
			{
				if (sel_elm.innerHTML < 7)
				{
					if (now.getMonth() == 0)
						result.value = ((sel_elm.innerHTML < 10) ? ("0" + sel_elm.innerHTML) : (sel_elm.innerHTML)) + "." + "01" + "." + now.getFullYear();
					else
						result.value = ((sel_elm.innerHTML < 10) ? ("0" + sel_elm.innerHTML) : (sel_elm.innerHTML)) + "." + ((now.getMonth() + 1 < 10) ? ("0" + (now.getMonth() + 1)) : (now.getMonth() + 1)) + "." + now.getFullYear();
				}
				else
				{
					if (now.getMonth() == 0)
						result.value = ((sel_elm.innerHTML < 10) ? ("0" + sel_elm.innerHTML) : (sel_elm.innerHTML)) + "." + 12 + "." + ((now.getMonth() - 1 == 0) ? (now.getFullYear() - 1) : (year.innerHTML));
					else
						result.value = ((sel_elm.innerHTML < 10) ? ("0" + sel_elm.innerHTML) : (sel_elm.innerHTML)) + "." + ((now.getMonth() < 10) ? ("0" + now.getMonth()) : (now.getMonth())) + "." + ((now.getMonth() - 1 == 0) ? (now.getFullYear()) : (year.innerHTML));
				}
			}
			if (getCellNumber[1] <= 27 && getCellNumber[1] >= 7)
				result.value = ((sel_elm.innerHTML < 10) ? ("0" + sel_elm.innerHTML) : (sel_elm.innerHTML)) + "." + ((now.getMonth() == 0) ? (12) : (((now.getMonth() < 10) ? ("0" + now.getMonth()) : (now.getMonth())))) + "." + year.innerHTML;
		}

		var c = WFX.GetElement("list_" + id);

		WFX.HideElement(c);
	};

	this.SetValue = function(set_date, set_month, set_year)
	{
		var result = WFX.GetElement(id);
		result.value = (((set_date < 10) ? ("0" + set_date) : (set_date)) + "." + ((set_month < 10) ? ("0" + set_month) : (set_month)) + "." + set_year);
	};

	this.GetValue = function()
	{
		var hidden = WFX.GetElement(id);
		return hidden.value;
	};

	this.GetName = function()
	{
		return id;
	};
};



WFX.Controls.PostTextField = function(name, url)
{
	var id = name;

	var _width = null;
	var _height = null;
	this.Suffix = "";
	var digitonly = false;
	this.myvar = false;

	var req = new WFX.Ajax.Request(null, function(response)
	{

		var msg = response.split(":");

		if (msg.length > 1)
		{
			msg = msg[1];
		}

		switch (parseInt(response))
		{
			case 200:
				{
					var field = WFX.GetElement(id);
					var mybtn = WFX.GetElement("btn_ok_" + id);

					WFX.HideElement(mybtn);
					field.style.background = "#ffffff";
					field.style.border = "1px solid #707070";

					break;
				}

			case 500:
				{
					alert("Неопознанная ошибка сервера.\n" + msg);
					break;
				}

			case 501:
				{
					alert("Ошибка базы данных.\n" + msg);
					break;
				}

			case 502:
				{
					alert("Ошибка ввода данных.\n" + msg);
					break;
				}

			default:
				{
					alert("Неопознанная ошибка.\n" + msg);
				}
		}


	});



	var text_change = function(e)
	{
		var field = WFX.GetElement(id);
		var key = WFX.Events.KeyCode(e);
		var mybtn = WFX.GetElement("btn_ok_" + id);
		
		switch (key)
		{
			case WFX.KeyCodes.Enter:
			{
				if (field.value < 0 || field.value > 100)
				{
					alert("Неверно введено значние");
				}
				else
				{
					req.Post(url, WFX.Ajax.EncType.FormUrlencoded, [["p", field.value]]);
				}

				break;
			}
			default:
			{
			    if (url)
			    {
				    WFX.ShowElement(mybtn);
				    field.style.background = "#FFCCCC";
				    field.style.border = "1px solid #707070";
				}
				break;
			}
		}

	};

	this.Build = function(width)
	{
		_width = width;
		var out = "";
		out += "<table border='0' cellpadding='0' cellspacing='0' width='" + _width + "'>";
		out += "<tr>";
		out += "<td width='23px'><input id='" + id + "' type='text' style='border-style:solid; border-width:1px; border-color:#898c95; width:" + _width + "px;' /></td>";
		out += "<td width='10px'>&nbsp;" + this.Suffix + "</td>";
		out += "<td id='btn_ok_" + id + "' style='display:none;'><input style='width:25px;' type='button' value='ok' /></td>";
		out += "</tr>";
		out += "</table>";

		WFX.Events.AddEventHandler("keyup", id, text_change);
		
		WFX.Events.AddEventHandler("keypress", id, function(e)
		{
			var key = WFX.Events.KeyCode(e);
			var keychar = String.fromCharCode(key);

			if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27))
			{
				return true;
			} 
			else if ( ("0123456789").indexOf(keychar) > -1)
			{
				return true;
			}
			else if (e && (keychar == ".")) 
			{
				WFX.Events.SrcElement(e).focus();
				WFX.Events.Stop(e);
				return false;
			}
			else
			{
				WFX.Events.Stop(e);
				return false;
			}
		});
		
		
		WFX.Events.AddEventHandler("click", "btn_ok_" + id, function(e)
		{
			var field = WFX.GetElement(id);
			var mybtn = WFX.GetElement("btn_ok_" + id);

			if (field.value < 0 || field.value > 100)
			{
				alert("Неверно введено значние");
			}
			else
			{
				req.Post(url, WFX.Ajax.EncType.FormUrlencoded, [["p", field.value]]);
			}

		});
		return out;
	};

	this.Show = function(width)
	{
		document.write(this.Build(width));
	};

	this.LoadData = function(load_url)
	{
		var req_info = new WFX.Ajax.Request(null, function(response)
		{
			var str = response;

			var field = WFX.GetElement(id);

			field.value = str.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'");

		});

		req_info.Get(load_url);
	};

	this.SetDigitOnly = function(state)
	{
		digitonly = state;
	};
	
	this.GetName = function()
	{
	    return id;
	};
	
	this.GetValue = function()
	{
	    var field = WFX.GetElement(id);
	    return field.value;
	};
	
	this.SetValue = function(val)
	{
	    var field = WFX.GetElement(id);
	    field.value = val.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'");
	};
};

WFX.Controls.MultiLineTextField = function(name, url, static_field)
{
    var _static = static_field || false;
    var id = name;
    var _width = null;
	var _height = null;
	var upload_url = url || false;
	WFX.Globals.Attach(id, this);
	 
	var req = new WFX.Ajax.Request(null, function(response)
	{
		var msg = response.split("::");

		if (msg.length > 1)
		{
			msg = msg[1];
		}

		switch (parseInt(response))
		{
			case 200:
				{
				    if (upload_url != false)
				    {
					    WFX.HideElement("btn_ok_" + id);
					    WFX.HideElement("btn_cancel_"+id);
					}
					if (_static == false)
					{
					    var area = WFX.GetElement(id);
	                    area.style.height = _height+"px"; 
	                }
					break;
				}

			case 500:
				{
					alert("Неопознанная ошибка сервера.\n" + msg);
					break;
				}

			case 501:
				{
					alert("Ошибка базы данных.\n" + msg);
					break;
				}

			case 502:
				{
					alert("Ошибка ввода данных.\n" + msg);
					break;
				}

			default:
				{
					alert("Неопознанная ошибка.\n" + msg);
				}
		}


	});
	
	this.Build = function(width, height)
	{
	    _height = height;
	    _width = width;
	    var out = "";
	    out += "<div style='text-align:right;width:"+_width+"px;'><textarea id='"+id+"' style='resize: none; border-style:solid; border-width:1px; border-color:#898c95; width:"+_width+"px; height:"+_height+"px'></textarea><br/>";
	    out += "<a href='javascript:void(0);' style='display:none;' id='btn_cancel_"+id+"' >Отменить</a>&nbsp;&nbsp;<a href='javascript:void(0);' style='display:none;' id='btn_ok_"+id+"' >Сохранить</a></div>"; 
	    return out;
	};
	
	this.Show = function(width, height)
	{
	    document.write(this.Build(width, height));    
	};
	
	WFX.Events.AddEventHandler("focus", id, function(e)
	{
	    if (_static == false)
	    {
	        var area = WFX.Events.SrcElement(e);
	        area.style.height = _height+ 100 +"px";
	    }

        if (upload_url != false)
        {
	        WFX.ShowElement("btn_ok_"+id);       
	        WFX.ShowElement("btn_cancel_"+id); 
	    }
	});
	
	WFX.Events.AddEventHandler("click", id, function(e)
	{
	    if (WFX.IsVisible("btn_ok_"+id) == false)
	    {
	        return;
	    }
	    
	    if (_static == false)
	    {
	        var area = WFX.Events.SrcElement(e);
	        area.style.height = _height+ 100 +"px";
	    }
	});
	
	if (_static == false)
	{
	    WFX.Events.AddEventHandler("blur", id, function(e)
	    {
	        var intv = setTimeout(function()
	        {
	            clearTimeout(intv);
	            var area = WFX.GetElement(id);
	            area.style.height = _height+"px";
	        }, 10);
    	    
	    });
	}
	
	WFX.Events.AddEventHandler("click", "btn_ok_"+id, function(e)
	{
	    var area = WFX.GetElement(id);
	    req.Post(upload_url, WFX.Ajax.EncType.FormUrlencoded, [["p", area.value]]);
	});
	
	WFX.Events.AddEventHandler("click", "btn_cancel_"+id, function(e)
	{
	    var $this = WFX.Globals.GetObject(id);
	    $this.LoadData(init_url);
	});
	
	this.SetValue = function(val)
	{
	    var intv = setInterval(function()
	    {
	        var ar = WFX.GetElement(id);
	        
	        if (ar)
	        {
	            clearInterval(intv);
	        }
	        else
	        {
	            return;
	        }
	        
	        ar.value = val.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'");
	    }, 100);
	    
	};
	
	this.GetValue = function(e)
	{
	    var area = WFX.GetElement(id);
	    return area.value;        
	};
	
	this.GetName = function(e)
	{
	    return id;    
	};
	var init_url = null;
	this.LoadData = function(load_url)
	{
	    init_url = load_url;
		var req_info = new WFX.Ajax.Request(null, function(response)
		{
			var str = response;
			var field = WFX.GetElement(id);
			field.value = str;
			
			WFX.HideElement("btn_ok_" + id);
		    WFX.HideElement("btn_cancel_"+id);
		    var area = WFX.GetElement(id);
	        area.style.height = _height+"px"; 
		});
		req_info.Get(load_url);
	};
};



WFX.Controls.MultiTree = function(name, url)
{
    this.Version = "1.0.1";
    
    var items = [];
    this.WithoutClearButton = false;
    var new_items = [];
    var id = name;
    var chlist_height;
    var chlist_width;
    var selected_id = null;
    var ready = false;
    var withnew = withnew || true;
    var upload_url = url;
    var init_url = null;
    WFX.Globals.Attach(id, this);
    
    var tree = new WFX.Controls.TreeCheckList("tr-"+id);
    
    var reqst = new WFX.Ajax.Request(null, function(response)
	{
		var msg = response.split("::");

		if (msg.length > 1)
		{
			msg = msg[1];
		}

		switch (parseInt(response))
		{
			case 200:
				{
					var mybtn = WFX.GetElement("btn_ok_" + id);
					WFX.HideElement(mybtn);
					
					break;
				}

			case 500:
				{
					alert("Неопознанная ошибка сервера.\n" + msg);
					break;
				}

			case 501:
				{
					alert("Ошибка базы данных.\n" + msg);
					break;
				}

			case 502:
				{
					alert("Ошибка ввода данных.\n" + msg);
					break;
				}

			default:
				{
					alert("Неопознанная ошибка.\n" + msg);
				}
		}
	}); 
	
    this.Reload = function()
    {
		tree.Reload(init_url);
		var h = WFX.GetElement(id);
		this.SetValue(h.value);
    };
    
    this.Load = function(tree_url)
    {
        init_url = tree_url;
        tree.Load(init_url);        
    };
    
    this.LoadSelection = function(url)
    {
        var req = new WFX.Ajax.Request(null, function(response)
        {
            var msg = response.split("::");

		    if (msg.length > 1)
		    {
			    msg = msg[1];
		    }

		    switch (parseInt(response))
		    {
			    case 200:
				    {
					    var $this = WFX.Globals.GetObject(id);
    					$this.SetValue(msg);
					    break;
				    }

			    case 500:
				    {
					    alert("Неопознанная ошибка сервера.\n" + msg);
					    break;
				    }

			    case 501:
				    {
					    alert("Ошибка базы данных.\n" + msg);
					    break;
				    }

			    case 502:
				    {
					    alert("Ошибка ввода данных.\n" + msg);
					    break;
				    }

			    default:
				    {
					    alert("Неопознанная ошибка.\n" + msg);
				    }
		    }
        });
        
        req.Get(url);
    };
       
    var onBtnClick = function(e)
    {
        if (tree.IsReady() == false)
        {
            alert("Элемент управления не готов. Повторите попытку позже.");
            return;
        }
        
        var chlist = WFX.GetElement("chlist_"+id);
        var btn = WFX.Events.SrcElement(e);
        var but_height = WFX.Position.GetHeight(btn);
        var elm_y = WFX.Position.GetTopPosition(btn);
        
        if ((document.documentElement.clientHeight - (elm_y - document.documentElement.scrollTop)) >= (chlist_height) )
        {
            WFX.Position.SetPosition(chlist, btn);
        }   
        else
        {
            if (elm_y < chlist_height)
            {
                WFX.Position.SetPosition(chlist, btn);
            }
            else
            {
                WFX.Position.SetPosition(chlist, btn, ((WFX.Browser.Name == Browsers.IE)?2:0), -(chlist_height-but_height)); 
            }
        }
        
        WFX.ShowElement(chlist);
        tree.SetFocus();
        
        var hidden = WFX.GetElement(id);
    };
    
    var onOkClick = function(e)
    {
        var chlist = WFX.GetElement("chlist_"+id);
        WFX.HideElement(chlist);
        
        var hidden = WFX.GetElement(id);
        hidden.value = "";
        
        hidden.value = tree.GetValue();
        
        var rez = WFX.GetElement("result_"+id);
        var oldVars = rez.value;
        rez.value="";
        
        var titles = tree.GetSelectedTitles().split("|").join("; ");
        
        rez.value = titles;
        
        if (titles.length > 0)
        {
            rez.value +=".";
        }
        
        var btn_ok = WFX.GetElement("btn_ok_"+id);
        if (rez.value != oldVars)
        {
            rez.style.background="#FFCCCC";
            rez.style.border = "1px solid #707070";
			WFX.ShowElement(btn_ok);
		}
    };
    
    var onCancelClick = function()
    {
        WFX.HideElement("chlist_"+id);
        var hidden = WFX.GetElement(id);
        tree.SetValue(hidden.value);
    };
       
    WFX.Events.AddEventHandler('click', 'btn_'+id, onBtnClick);
    WFX.Events.AddEventHandler('click', 'ok_'+id, onOkClick);
    WFX.Events.AddEventHandler('click', 'cancel_'+id, onCancelClick);
    
    this.Build = function(width, height)
    {
        chlist_height = height || 120;
        chlist_width = width || 120;
        width =  width || 120;
        height = height || 100;
        new_items[0]= 1;
        
        var out = "";
        out += "<button id='btn_"+id+"' style='width:20px;'>...</button>";
        out += "<input style='margin-bottom:1px;border-style:solid; border-width:1px; border-color:#898c95; width:"+(width-20)+"px;' id='result_"+id+"' type='text' readonly='readonly' />";
        out += "<input type='button' id='btn_ok_"+id+"' value='OK' style='display:none;' />";
        out += "<input type='hidden' name='"+id+"' id='"+id+"' />";
        
        out += '<div id="chlist_'+id+'" style="padding:1px;background-image:url(/sysicons/controlbkg.gif); background-repeat:repeat-x; background-position:bottom;display:none;background-color:#ffffff;border-style:solid; border-color:#7f9db9; border-width:1px; height:'+height+'px; width:'+(width+1)+'px; position:absolute;">';
            out += tree.Build(width-1, height-22);
            out += '<div> <input id="ok_'+id+'" type="button" value="OK" /> <input id="cancel_'+id+'" type="button" value="Отмена" /> </div>';
        out += '</div>';
        
        WFX.Events.AddEventHandler("click", "btn_ok_"+id, function(e)
        {
			var res = WFX.GetElement(id);
			var rez = WFX.GetElement("result_"+id);
			rez.style.background="#FFFFFF";
			reqst.Post(upload_url, WFX.Ajax.EncType.FormUrlencoded, [["p", res.value]]);
			
        });
        return out;
    };
    
    this.Show = function(width, height)
    {  
        document.write(this.Build(width, height));
    };
    
    this.SetValue = function(value)
    { 
        var intv = setInterval(function()
        {
            if (tree.IsBusy()==true)
            {
                return;
            }
            else
            {
                clearInterval(intv);
            }
            
            var hidden = WFX.GetElement(id);
            hidden.value = value;
        
            tree.SetValue(value);
            var titles = tree.GetSelectedTitles().split("|").join("; ");
            if (titles.length>0)
            {
                titles += ".";
            }
            var rez = WFX.GetElement("result_"+id);
            rez.value = titles;
        }, 100);
    };
    
    this.GetValue = function()
    {
        var hidden = WFX.GetElement(id);
        return hidden.value;
    };
    
    this.GetName = function()
    {
        return id;  
    };
    
};


WFX.Controls.SpinButton = function(name)
{
    var id = name;
    var _width = null;
    var step = 1;
    var min_value = 0;
    var max_value = 100;
    
    var btn_down = new WFX.Controls.ImageButton("btn_down_" + id, "/sysimages/spinbutton/s_down.png", "/sysimages/spinbutton/s_down_hover.png", "/sysimages/spinbutton/s_down_pick.png", "Уменьшение значения");
	var btn_up = new WFX.Controls.ImageButton("btn_up_" + id, "/sysimages/spinbutton/s_up.png", "/sysimages/spinbutton/s_up_hover.png", "/sysimages/spinbutton/s_up_pick.png", "Увеличение значения");
	
    this.Build = function(width)
    {
        _width = width;
        var out = "<table width='"+_width+"' border='0' style='border-collapse:collapse;' cellpadding='0' cellspacing='0'>";
                out += "<tr>";
                    out += "<td rowspan='2' ><input id='"+id+"' name='"+id+"' type='text' value='0' readonly='readonly' style='border-style:solid; border-width:1px; border-color:#898c95; width:"+(_width-13)+"px;' /></td>";
                    out += "<td >"+btn_up.Build(13, 10)+"</td>";
                out += "</tr>";
                out += "<tr>";
                    out += "<td >"+btn_down.Build(13, 10)+"</td>";
                out += "</tr>";
            out += "</table>";
        return out;
    };
    
    this.SetRange = function(min, max, _step)
    {
        min_value = min;
        max_value = max;
        step = _step; 
    };
    
    this.SetValue = function(value)
    {
        var val = WFX.GetElement(id);
        val.value = parseFloat(value);
    };
    
    this.GetValue = function()
    {
        var val = WFX.GetElement(id);
        return val.value;
    };
    var intv = null;
    this.Show = function(width)
    {
        document.write(this.Build(width));
        
        WFX.Events.AddEventHandler('mousedown', "btn_down_"+id, function(e)
        {
            var val = WFX.GetElement(id);
            if ((parseFloat(val.value)- step) >= min_value)
            {
                val.value = parseFloat(val.value) -  parseFloat(step);
            }
        });
        
        WFX.Events.AddEventHandler('mousedown', "btn_up_"+id, function(e)
        {
            var val = WFX.GetElement(id);
            if ((parseFloat(val.value)+ step) <= max_value)
            {
                val.value = parseFloat(val.value) +  parseFloat(step);
            }
        });
        
        WFX.Events.AddEventHandler('mousedown', "btn_up_"+id, function(e)
        {
            clearInterval(intv); intv=null;
            intv = setInterval(function()
            {
                var val = WFX.GetElement(id);
                if ((parseFloat(val.value)+ step) <= max_value)
                {
                    val.value = parseFloat(val.value) +  parseFloat(step);
                }
            }, 600);
            
            setTimeout(function(){clearInterval(intv); intv=null;}, 25000);
        });
        
        WFX.Events.AddEventHandler('mouseup', "btn_up_"+id, function(e)
        {
            clearInterval(intv);
            intv = null;
        });
        
        WFX.Events.AddEventHandler('mousedown', "btn_down_"+id, function(e)
        {
            clearInterval(intv); intv=null;
            intv = setInterval(function()
            {
                var val = WFX.GetElement(id);
                if ((parseFloat(val.value)- step) >= min_value)
                {
                    val.value = parseFloat(val.value) -  parseFloat(step);
                }
            }, 600);
            
            setTimeout(function(){clearInterval(intv); intv=null;}, 25000);
        });  
        
        WFX.Events.AddEventHandler('mouseup', "btn_down_"+id, function(e)
        {
            clearInterval(intv);
            intv = null;
        });
          
    };
        
};


WFX.Controls.Slider = function(name, _min, _max, _step)
{
    var id = name;
    var _width = null;
    var txt_id = null;
    var moveState = false;
    var x0, y0;
    var divX0, divY0;
    
    var min = _min;
    var max = _max;
    var step = _step;
    
    WFX.Globals.Attach(id, this);
    
    this.Build = function(width)
    {
        _width = width;

        var out = "<table border='0' style='border-collapse:collapse;' cellpadding='0' width='"+_width+"px' cellspacing='0'>";
                out += "<tr>";
                    out += "<td>";
                        out += "<table width='100%' height='10px' border='0' cellpadding='0' cellspacing='0' style='border-collapse:collapse;'>";
                            out += "<tr>";
                                out += "<td width='30px' align='center' style='font-size:9px;'>"+min+"</td>";
                                out += "<td width='"+(_width-60)+"px'></td>";
                                out += "<td width='30px' align='center' style='font-size:9px;'>"+max+"</td>";
                            out += "</tr>";
                        out += "</table>";
                    out += "</td>";
                out += "</tr>";
                out += "<tr>";
                    out += "<td>";
                        out += "<table width='100%' border='0' cellpadding='0' cellspacing='0' style='border-collapse:collapse;'>";
                            out += "<tr>";
                                out += "<td width='10px'></td>";
                                out += "<td width='"+(_width-20)+"px'>";
                                
                                    out += "<table style='-moz-user-select:none;' height='100%' border='0' cellspacing='0' cellpadding='0'>";
                                        out += "<tr>";
                                            out += "<td>";
                                                out += "<table width='100%' border='0' cellspasing='0' height='10px' cellspadding='0' style='border-collapse:collapse;'>";
                                                    out += "<tr>";
                                                    out += "<td width='3px'></td>";
                                                        for (var i=0; i < parseInt(max/step); i++)
                                                        {   
                                                            if (i == parseInt(max/step)-1)
                                                            {
                                                                out += "<td style='border-left-style:solid; border-left-width:2px; border-left-color:#b0b0b0; border-right-style:solid; border-right-width:2px; border-right-color:#b0b0b0'></td>";
                                                                out += "<td width='2px'></td>";
                                                            }
                                                            else
                                                            {   
                                                                out += "<td style='border-left-style:solid; border-left-width:2px; border-left-color:#b0b0b0'></td>";
                                                            }
                                                        }
                                                    out += "</tr>";
                                                out += "</table>";
                                            out += "</td>";
                                        out += "</tr>";
                                        out += "<tr>";
                                            out += "<td id='line_"+id+"' style='background-image:url(/images/slider/slider_bg.png); background-repeat:repeat-x;' width='"+(_width-20)+"px' height='20px'><div id='slider_"+id+"' style='position:relative; background-image:url(/images/slider/slider_button.png); z-index:100; width:10px; height:20px; left:0px; top:0px; '></div></td>";
                                        out += "</tr>";
                                    out += "</table>";
                                    
                                out += "</td>";
                                out += "<td width='10px'></td>";
                            out += "</tr>";
                        out += "</table>";
                    out += "</td>";    
                out += "</tr>";
            out += "</table>";
        return out;
    };
    
    var defPosition = function(event)
    {
        var x = y = 0;
        
        if (WFX.Browser.Name == Browsers.IE || WFX.Browser.Name == Browsers.Opera)
        {
            x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
            y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
        }
        else if (WFX.Browser.Name == Browsers.Firefox || WFX.Browser.Name == Browsers.Safari)
        {
            x = event.clientX + window.scrollX;
            y = event.clientY + window.scrollY;
        }
        return {x:x, y:y};

    };
    
    this.Show = function(width)
    {
        document.write(this.Build(width));
        
        WFX.Events.AddEventHandler('mousedown', 'slider_'+id,  function(e)
        {
            var div = WFX.GetElement("slider_"+id);
            var event = e || window.event;
            x0 = defPosition(event).x;
            divX0 = parseInt(div.style.left);
            moveState = true;
        });                       
        
        WFX.Events.AddEventHandler('mouseup', 'slider_'+id,  function(e)
        {
            moveState = false;
        }); 
        document.onmouseup = function()
        {
            moveState = false;
        };
                              
        WFX.Events.AddEventHandler('mousemove', document.body, function(e)
        {
           if (moveState) 
           {
                var event = e || window.event;
                var line = WFX.GetElement("line_"+id);
                var div = WFX.GetElement("slider_"+id);
                var rez = WFX.GetElement(txt_id);
                var size = parseInt((_width-30))/max;
                if (WFX.Browser.Name == Browsers.IE)
            	{
                    document.selection.clear();
                }
                if ((divX0 + defPosition(event).x - x0) <= (_width-30) && (divX0 + defPosition(event).x - x0) >= 0) 
                {
                    div.style.left = divX0 + defPosition(event).x - x0 +'px';
                    rez.value = parseInt(parseInt(div.style.left)/size);
                }
                if ((divX0 + defPosition(event).x - x0) > (_width-33))
                {
                    div.style.left = parseInt(_width-30)+'px';
                    rez.value = max;
                }
                if ((divX0 + defPosition(event).x - x0) <0 )
                {
                    div.style.left = 0+'px';
                    rez.value = min;
                }
           }
        });
        WFX.Events.AddEventHandler('click', "line_"+id, function(e)
        {
            var elm = WFX.GetElement("slider_"+id);
            var event = e || window.event;
            var text = WFX.GetElement(txt_id);
            
            if (WFX.Browser.Name == Browsers.IE)
            {
                elm.style.left = (defPosition(event).x-50)  +'px';    
            }
            else
            {
                elm.style.left = (defPosition(event).x-44)  +'px';
            }
            
            if ((defPosition(event).x) > (_width - 33))
            {
                elm.style.left = parseInt(_width-30)+'px';
            }
            if ((defPosition(event).x - 50)  < 0)
            {
                elm.style.left = 0+'px';
            }
            var val = parseInt((max * parseInt(elm.style.left))/(_width-30));
            text.value = val;
            if (val > max)
            {
                text.value = max;
            }
            if (val < min)
            {
                text.value = min;
            }
        });                   
    };
    
    var GetValue = function()
    {
        var rez = WFX.GetElement(id);
        return rez.value;
    };
    
    this.SetValue = function(val)
    {
        var rez = WFX.GetElement(txt_id);
        var div = WFX.GetElement("slider_"+id);
        rez.value = val;
        div.style.left = (_width-30)/(max/val)+ 'px';
        
        if (val <= min)
        {
            div.style.left = 0+'px';
            //rez.value = min;
        }        
        if (val >= max)
        {
            div.style.left = parseInt(_width-30)+'px';
            rez.value = max;
        }
    };
    
    this.AttachChangeHandler = function(field)
    {
        txt_id = field;
        var text_field = WFX.GetElement(field);
        WFX.Events.AddEventHandler('keyup', txt_id, function(e)
        {
            var $this = WFX.Globals.GetObject(id);
            var val = WFX.Events.GetElement(e);
            
            $this.SetValue(val.value);
        });
        
        WFX.Events.AddEventHandler("keypress", field , function(e)
		{
			var key = WFX.Events.KeyCode(e);
			var keychar = String.fromCharCode(key);
            var elm = WFX.Events.SrcElement(e);
			if (parseInt(elm.value+keychar) > max)
			{
			    WFX.Events.Stop(e);
				return false;
			}
			if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27))
			{
				return true;
			} 
			else if ( ("0123456789").indexOf(keychar) > -1)
			{
				return true;
			}
			else if (e && (keychar == ".")) 
			{
				WFX.Events.SrcElement(e).focus();
				WFX.Events.Stop(e);
				return false;
			}
			else
			{
				WFX.Events.Stop(e);
				return false;
			}
			
		});
    };
};



WFX.Controls.SimpleTree = function(name)
{
    this.Version = "1.0";
    var id=name;
    var items = [];
    var items2 = [];
    var selected_id = null;
    var init_url = null;
    var tree_height;
    var tree_width;
    var ready = false;
    var busy = false;
    var req = new WFX.Ajax.Request
    (
        function()
        {
            ready = false;
        },
        
        function(response)
        {
            var str = response.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'").split("|");
            for (var i=0; i < str.length; i++)
            {
                items2[i] = new Array();
                var temp =  str[i].split(":");
                var temp2 = temp[0].split("$");
                temp[0] = temp2;
                var names = temp[1].split(";");
                for (var j =0; j<names.length; j++)
                {
                    var ids = names[j].split("$");
                    names[j] = ids;
                }
                temp[1] = names;
                items2[i] = temp;
            }
            ready = true;
        }
    );
  
    this.Reload = function(url)
    {
        busy = true;
        this.Clear();
        req.Get(url);
        
        var intv = setInterval
        ( 
            function()
            {
                if (ready == false)
                {
                    return;
                }
                else
                {
                    clearInterval(intv);
                }
                
                Fill();
            }, 
            100
        );    
    };
    
    this.Load = function(url)
    {
        var clist = WFX.GetElement("list_"+id);
        
        if (clist.childNodes.length > 1)
        {
            return;
        }
        
        init_url = url;
        this.Reload(url);
    };
    
    this.Clear = function() 
	{
		WFX.Events.RemoveEventHandler('keydown', ("list_" + id), OnListKeyDown);

		var list = WFX.GetElement("list_" + id);

		while (list.childNodes.length > 0) 
		{
			list.removeChild(list.firstChild);
		}

		selected_id = null;
	};
	
    var Fill = function()
    {
        var list = WFX.GetElement("list_" + id);
        list.innerHTML = "";
        var k = 0;
        for (var i=0; i<items2.length; ++i)
        {
            var div = document.createElement("div");
            div.setAttribute("id", "group_"+id+"_"+i);
            div.innerHTML = '<table cellpadding="0" cellspacing="0" border="0" style="display:inline;">';
            div.innerHTML += '<tr><td width="16px" height="14px">&nbsp;<img id="group_'+id+'_c_'+i+'" src="/images/minus.png" /></td></tr>';
            div.innerHTML += '</table>';   
            div.innerHTML += '<table  cellpadding="0" cellspacing="0" border="0" style="display:inline;">';
            div.innerHTML += '<tr><td width="16px" height="14px"><img id="group_'+id+'_folder_'+i+'"src="/images/foldero.png" /></td></tr>';
            div.innerHTML += '</table>&nbsp;';   
            div.innerHTML += '<label style="font-weight:bold;" id="group_'+id+"_title_"+i+'">'+items2[i][0][0].replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'")+'</label>';    
            
            WFX.Events.AddEventHandler("mouseover", "group_"+id+"_"+i, function(e)
            {
                var temp = WFX.Events.SrcElement(e);
                var temp_id = temp.id.split("_");
                if (temp_id.length > 3)
                {
                    var elm = WFX.GetElement("group_"+id+"_"+temp_id[3]);
                }
                else
                {
                    var elm = temp;
                }
                elm.style.color = "#ffffff";
                elm.style.background = "#316ac5";
            });
            
            WFX.Events.AddEventHandler("mouseout", "group_"+id+"_"+i, function(e)
            {
                var temp = WFX.Events.SrcElement(e);
                var temp_id = temp.id.split("_");
                if (temp_id.length > 3)
                {
                    var elm = WFX.GetElement("group_"+id+"_"+temp_id[3]);
                }
                else
                {
                    var elm = temp;
                }
                elm.style.color = "#000000";
                elm.style.background = "";
            });    
            
            var hidden = document.createElement("input");
            hidden.setAttribute("type", "hidden");
            hidden.setAttribute("id", ("group_"+id+"_hidden_"+i));
            hidden.value = items2[i][0][0][1];
            div.appendChild(hidden);
                                
            list.appendChild(div);
                    
            for (var j=0; j<items2[i][1].length; j++)
            {
                var div1 = document.createElement("div");
                div1.setAttribute("id", "user_"+id+"_"+k);
                div1.innerHTML += '<table  cellpadding="0" cellspacing="0" border="0" style="display:inline;">';
                div1.innerHTML += '<tr><td width="16px" height="16px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>';
                div1.innerHTML += '</table>';   
                div1.innerHTML += "<label id=user_"+id+"_title_"+k+">"+items2[i][1][j][0].replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#036;/g, "$").replace(/&#039;/g, "'")+"</label>";
                WFX.Events.AddEventHandler("mouseover", "user_"+id+"_"+k, function(e)
                {
                    var temp = WFX.Events.SrcElement(e);
                    var temp_id = temp.id.split("_");
                    if (temp_id.length > 3)
                    {
                        var elm = WFX.GetElement("user_"+id+"_"+temp_id[3]);
                    }
                    else
                    {
                        var elm = temp;
                    }
                    elm.style.color = "#ffffff";
                    elm.style.background = "#316ac5";
                });
                
                WFX.Events.AddEventHandler("mouseout", "user_"+id+"_"+k, function(e)
                {
                    var temp = WFX.Events.SrcElement(e);
                    var temp_id = temp.id.split("_");
                    if (temp_id.length > 3)
                    {
                        var elm = WFX.GetElement("user_"+id+"_"+temp_id[3]);
                    }
                    else
                    {
                        var elm = temp;
                    }
                    elm.style.color = "#000000";
                    elm.style.background = "";
                });
                
                //onmouseover=\"style.color='#ffffff'; style.background='#316ac5';\" 
                //onmouseout=\"style.color='#000000'; style.background='';\" 
                
                var hidden1 = document.createElement("input");
                hidden1.setAttribute("type", "hidden");
                hidden1.setAttribute("id", ("user_"+id+"_hidden_"+k));
                hidden1.value = items2[i][1][j][1];
                div1.appendChild(hidden1);
                list.appendChild(div1);
                
                WFX.Events.AddEventHandler('mouseup', ("user_"+id+"_title_"+k), function(e)
                {
                    var curitem = WFX.Events.SrcElement(e);
                    var cur_id = curitem.id.split("_");
                    SelectListItem(curitem.parentNode);
                    var res = WFX.GetElement("result_"+id);
                    res.value = curitem.innerHTML;
                    var curhidden = WFX.GetElement("user_"+id+"_hidden_"+cur_id[3]);
                    var hidden = WFX.GetElement(id);
                    hidden.value = curhidden.value;
                    WFX.HideElement(list); 
                });
                k++;
            }
            WFX.Events.AddEventHandler('mousedown', ("group_"+id+"_c_"+i), function(e)
            {
                var imgcheck = WFX.Events.SrcElement(e);
                var myid = imgcheck.id.split("_"); 
                var foldcheck = WFX.GetElement("group_"+myid[1]+"_folder_"+myid[3]);
                var temp = imgcheck.parentNode.id.split("_");
                var ch = imgcheck.parentNode;
                if (temp[0] == "group")
                {
                    while (ch.nextSibling != null)
                    { 
                        ch = ch.nextSibling;
                        temp = ch.id.split("_");
                        if (temp[0] == "group")
                        {
                            break;
                        }
                        else
                        {
                            temp = ch.id.split("_");
                            var elm = WFX.GetElement("user_"+temp[1]+"_title_"+temp[2]);
                         
                            if (WFX.IsVisible(elm.parentNode) == true)
                            {
                                foldcheck.src= "/images/folderc.png";
                                imgcheck.src = "/images/plus.png";
                                WFX.HideElement(elm.parentNode);
                            }
                            else 
                            {
                                foldcheck.src= "/images/foldero.png";
                                imgcheck.src = "/images/minus.png";
                                WFX.ShowElement(elm.parentNode);
                            }
                        }
                    } 
                }
            });
        }
        
        busy = false;
    };
    
    var ShiftUp = function(selected)
    {
        var list = WFX.GetElement('list_'+id);
        var summ = 0;
        
        var s = selected;
        
        while(s.previousSibling)
        {
            summ += s.previousSibling.offsetHeight;
            s = s.previousSibling;
        }

        if ( summ < list.scrollTop )
        {
            list.scrollTop = summ;
        }
    };
    
    var ShiftDown = function(selected)
    {
        var list = WFX.GetElement('list_'+id);
        var summ = 0;
        
        while(selected.previousSibling)
        {
            summ += selected.previousSibling.offsetHeight;
            selected = selected.previousSibling;
        }

        if ( ((parseInt(summ)-parseInt(list.scrollTop)) + selected.offsetHeight) > list.clientHeight )
        {
            list.scrollTop += (((parseInt(summ)-parseInt(list.scrollTop)) + selected.offsetHeight)-parseInt(list.clientHeight));
        }
    };
    
    var OnListKeyDown = function(e)
    {
        var tree = WFX.Events.SrcElement(e);
        var key = WFX.Events.KeyCode(e);          
        switch(key)
        {
            case WFX.KeyCodes.Down:
            {
                if (selected_id == null)
                {
                    SelectListItem(tree.firstChild);
                    WFX.Events.Stop(e);
                    break;
                }
                
                var curcheck = WFX.GetElement(selected_id);
                if (curcheck.nextSibling != null)
                {
                    while(curcheck.nextSibling.style.display == 'none')
                    {
                        curcheck = curcheck.nextSibling;
                        
                        if (curcheck.nextSibling == null)
                        {
                            WFX.Events.Stop(e);
                            return;
                        }
                    }
                   
                    SelectListItem(curcheck.nextSibling);
                    selected = WFX.GetElement(selected_id);
                    ShiftDown(selected);
                }
                WFX.Events.Stop(e);
                
                break;
            }
        
            case WFX.KeyCodes.Up:
            {
                if (selected_id == null)
                {
                    break;
                }
                
                var curcheck = WFX.GetElement(selected_id);                
                if (curcheck.previousSibling)
                {
                    while(curcheck.previousSibling.style.display == 'none')
                    {
                        curcheck = curcheck.previousSibling;
                    }
                   
                    SelectListItem(curcheck.previousSibling);
                    selected = WFX.GetElement(selected_id);
                    ShiftUp(selected);
                }
                WFX.Events.Stop(e);
                
                break;   
            }
            case WFX.KeyCodes.Right:
            {   
                if (selected_id == null)
                {
                    break;
                }
                var cur_id = selected_id.split("_");
                var foldcheck = WFX.GetElement("group_"+id+"_"+cur_id[2]);
                var fold_id = foldcheck.id.split("_");
                if (cur_id[0] == "group")
                {
                    var child = foldcheck;
                    while (child.nextSibling != null)
                    {
                        child = child.nextSibling;
                        cur_id = child.id.split("_");
                        if (cur_id[0] == "group")
                        {
                            break;
                        }
                        cur_id = child.id.split("_");
                        var elm = WFX.GetElement("user_"+id+"_title_"+cur_id[2]);
                        foldcheck.src= "/images/foldero.png";
                        var plus = WFX.GetElement("group_"+id+"_c_"+fold_id[2]);
                        plus.src = "/images/minus.png";
                        WFX.ShowElement(elm.parentNode);
                        
                    }
                    
                }
                break;   
            }
            case WFX.KeyCodes.Left:
            {
                if (selected_id == null)
                {
                    break;
                }
                
                var cur_id = selected_id.split("_");
                var foldcheck = WFX.GetElement("group_"+id+"_"+cur_id[2]);
                var fold_id = foldcheck.id.split("_");
                if (cur_id[0] == "group")
                {
                    var child = foldcheck;
                    while (child.nextSibling != null)
                    {
                        child = child.nextSibling;
                        cur_id = child.id.split("_");
                        if (cur_id[0] == "group")
                        {
                            break;
                        }
                        cur_id = child.id.split("_");
                        var elm = WFX.GetElement("user_"+id+"_title_"+cur_id[2]);
                        foldcheck.src= "/images/foldero.png";
                        var plus = WFX.GetElement("group_"+id+"_c_"+fold_id[2]);
                        plus.src = "/images/plus.png";
                        WFX.HideElement(elm.parentNode);
                        
                    }
                    
                }
                break;
            }
            case WFX.KeyCodes.Enter:
            {
                var cur_id = selected_id.split("_");
                if (cur_id[0] != "group")
                {
                    var curtitle = WFX.GetElement("user_"+id+"_title_"+cur_id[2]);
                    var rez = WFX.GetElement("result_"+id);
                    rez.value = curtitle.innerHTML;
                    var curhidden = WFX.GetElement("user_"+id+"_hidden_"+cur_id[2]);
                    var hidden = WFX.GetElement(id);
                    hidden.value = curhidden.value;
                    var lst = WFX.GetElement("list_"+id);
                    WFX.HideElement(lst);
                }
                break;    
            }
        }
        
    };
    var SelectListItem = function(element)
    {
        if (selected_id != null)
        {
            var selected = WFX.GetElement(selected_id);
            selected.style.color = "#000000";
            selected.style.background = "#ffffff";
        }  
        
        if (element != null)
        {
            var to_select = WFX.GetElement(element);
            
            to_select.style.color = "#ffffff";
            to_select.style.background = "#316ac5"; 
            selected_id = element.id;
        }  
        else
        {
            selected_id = null;
        } 
    };
    
    var onBtnClick = function(e)
    {
        if (busy == true)
        {   
            alert("Элемент управления еще не готов!\r\nПопробуйте позже...\r\n");
            return;
        }
        
        var list = WFX.GetElement("list_"+id);
        if (WFX.IsVisible(list))
        {
            WFX.HideElement(list);
        }
        else
        {
            WFX.ShowElement(list);
            list.focus();
        }
        
        var btn = WFX.Events.SrcElement(e);
        var but_height = WFX.Position.GetHeight(btn);
        var elm_y = WFX.Position.GetTopPosition(btn);
        
        var result = WFX.GetElement("result_"+id);
        var result_height = WFX.Sizes.GetHeight(result);
        var result_width = WFX.Sizes.GetWidth(result);
        var result_y = WFX.Position.GetTopPosition(result);
        
        if ((document.documentElement.clientHeight - (elm_y - document.documentElement.scrollTop)) >= (tree_height) )
        {
            WFX.Position.SetPosition(list, result, 1, 1);
            WFX.Sizes.SetWidth(list, result_width-2);
        }   
        else
        {
            if (result_y < tree_height)
            {
                WFX.Position.SetPosition(list, result, -1, -2);
            }
            else
            {
                WFX.Position.SetPosition(list, result, 1, -(tree_height-result_height+1));
                WFX.Sizes.SetWidth(list, result_width-2);
                 
            }
        }
    };
    
    WFX.Events.AddEventHandler("click", "btn_"+id, onBtnClick);
    
    this.Build = function(width, height)
    {
        tree_height = height;
        tree_width = width;
        
        var out = "<button id='btn_"+id+"' style='width:20px;'>...</button>";
            out += "<input style='margin-bottom:1px;border-style:solid; border-width:1px; border-color:#898c95; width:"+(tree_width-20)+"px;' id='result_"+id+"' type='text' readonly='readonly' />";
            out += "<input type='hidden' name='"+id+"' id='"+id+"' />";
            out += "<div id='list_"+id+"' style='z-index:1000; display:none; cursor:default; overflow:auto; width:"+((WFX.Browser.Name == Browsers.Firefox)?(tree_width-17):(tree_width-20))+"px; height:"+tree_height+"px; background-color:#FFFFFF; border-style:solid; border-width:1px; border-color:#898c95; position:absolute;'></div>";
            out +="<input type='hidden' id='"+id+"' name='"+id+"' />";
        return out;
        
    };
    
    this.Show = function(width, height)
    {  
        document.write(this.Build(width, height));
        WFX.Events.AddEventHandler('keydown', "list_"+id, OnListKeyDown);
    };
    
    this.SetValue = function(val)
    {
        var intv = setInterval(function()
        {
            if (busy == true)
            {
                return;
            }
            else
            {
                clearInterval(intv);
            }
            
            for (var i=0; i<items2.length; i++)
            {
                 for (var j=0; j<items2[i][1].length; j++)
                 {
                    if (items2[i][1][j][1] == val)
                    {
                        var res = WFX.GetElement("result_"+id);
                        res.value = items2[i][1][j][0];
                        var hidden = WFX.GetElement(id);
                        hidden.value = val;
                    }   
                 }         
            }    
        }, 100);
    };
    
    this.GetValue = function()
    {
        var hidden = WFX.GetElement(id);
        return hidden.value;
    };  
    
    this.GetName = function()
    {
        return id;
    };  
};


WFX.Controls.ContextMenu = function(name)
{
    var id = name;

    var _width = null;

    var icons = [];
    var items = [];
    var handlers = [];
    var active = [];
    
    WFX.Images.Preload("/sysimages/ctxmenu/icon-bg.png");
    WFX.Images.Preload("/sysimages/ctxmenu/splitter.gif");
    
    WFX.Globals.Attach(id, this);
    
    var srcelement = null;
    this.GetElement = function()
    {
        return srcelement;
    };

    var onmenu = null;
    
    this.SetOnShowEvent = function(handler)
    {
        onmenu = handler;
    };

    this.AttachTo = function(el)
    {
        if (WFX.Browser.Name == Browsers.Opera)
        {
            WFX.Events.AddEventHandler('mousedown', el, function(e)
            {
                if (e.button == 2)
                {
                    srcelement = WFX.Events.GetElement(e);
                    var $this = WFX.Globals.GetObject(id);
                    
                    $this.Show();
                    $this.MoveToCursor(e); 
                    WFX.Events.Stop(e);
                }
                return false;           
            });
            
            WFX.Events.AddEventHandler('mouseup', el, function(e)
            {
                if (e.button == 2)
                {
                    
                    WFX.Events.Stop(e);
                }
                return false;           
            });
            
        }
        else
        {  
            WFX.Events.AddEventHandler('contextmenu', el, function(e)
            {
            
                srcelement = WFX.Events.GetElement(e);
                var $this = WFX.Globals.GetObject(id);
                
                $this.Show();
                $this.MoveToCursor(e); 
                WFX.Events.Stop(e);
                return false;           
            });
        }
    }; 
    
    this.MoveToCursor = function(e)
    {
        var main = WFX.GetElement(id);
        
        var elm_y = 0;
        var elm_x = 0;
            
        if ( WFX.Browser.Name == Browsers.Chrome) 
		{
		    var elm_y = (e.clientY + document.body.scrollTop+1);
            var elm_x = (e.clientX + document.body.scrollLeft+1);
		}
		else
		{
            var elm_y = (e.clientY + document.documentElement.scrollTop+1);
            var elm_x = (e.clientX + document.documentElement.scrollLeft+1);
        }

        var x = 0;
        var y = 0;
        
        if ((document.documentElement.clientHeight - (elm_y - ((WFX.Browser.Name == Browsers.Chrome)?(document.body.scrollTop):(document.documentElement.scrollTop)))) >= (WFX.Sizes.GetHeight(main)) )
        {
            y = elm_y;
        }
        else
        {
            if (elm_y < WFX.Sizes.GetHeight(main))
            {   
                y = elm_y;
            }
            else
            {
                y = (e.clientY + ((WFX.Browser.Name == Browsers.Chrome)?(document.body.scrollTop):(document.documentElement.scrollTop))+1)-WFX.Sizes.GetHeight(main);
            }
        }
        
        if ((document.documentElement.clientWidth - (elm_x - ((WFX.Browser.Name == Browsers.Chrome)?(document.body.scrollTop):(document.documentElement.scrollLeft)))) >= (WFX.Sizes.GetWidth(main)) )
        {
            x = elm_x;
        }
        else
        {
            if (elm_x < WFX.Sizes.GetWidth(main))
            {   
                x = elm_x;
            }
            else
            {
                x = (e.clientX + ((WFX.Browser.Name == Browsers.Chrome)?(document.body.scrollTop):(document.documentElement.scrollLeft))+1)-WFX.Sizes.GetWidth(main);
            }
        }
        
        WFX.Position.Move(main, x, y);
        
    };
    var last_color = null;    
    this.Create = function(width)
    {
        _width = width;
           
        var out = "<div id ='"+id+"' style='position:absolute; display:none;width:"+_width+"px; border-width:1px; border-style:solid; border-color:#898c95; background-color:#FFFFFF'>";
                out += "<table id='table_"+id+"' border='0' cellspacing='0' cellpadding='1' style='border-collapse:collapse;' width='100%'>";
                    for (var i=0; i < items.length; i++)
                    {
                        out += "<tr id='row_"+id+"_"+i+"'><td id='foricon_"+id+"_"+i+"' style='background-color:#FFFFFF;  background-image:url(/sysimages/ctxmenu/icon-bg.png); background-repeat:repeat-y; padding-left:3px; padding-right:3px;' width='18px'>"+((icons[i])?("<img src='"+icons[i]+"' />"):(""))+"</td><td style='cursor:default; padding-left:5px; text-align:left; background-color:#FFFFFF; "+((items[i] == "")?"background-image:url(/sysimages/ctxmenu/splitter.gif); background-repeat:repeat-x; height:3px;":"height:22px;")+"' id='item_"+id+"_"+i+"'>"+((items[i]=="")?"":items[i])+"</td></tr>";

                        WFX.Events.AddEventHandler('mouseup', "row_"+id+"_"+i, RunMouseClickHandlers);
                        
                        if (handlers[i] != null)
                        {
                            WFX.Events.AddEventHandler('mouseover', "foricon_"+id+"_"+i, function(e)
                            {
                                var srcel = WFX.Events.GetElement(e);
                                if (srcel.tagName == "IMG")
                                {
                                    srcel = srcel.parentNode;
                                }
                                var el = WFX.GetElement('item_'+id+'_'+srcel.id.split('_')[2]);
                                last_color = el.style.color;
                                el.style.color = "#ffffff";
                                el.style.background="#316ac5";
                            });
                            WFX.Events.AddEventHandler('mouseout', "foricon_"+id+"_"+i, function(e)
                            {
                                var srcel = WFX.Events.GetElement(e);
                                if (srcel.tagName == "IMG")
                                {
                                    srcel = srcel.parentNode;
                                }
                                var el = WFX.GetElement('item_'+id+'_'+srcel.id.split('_')[2]);
                                el.style.color = last_color;
                                el.style.background="#ffffff";
                            });
                            
                            WFX.Events.AddEventHandler('mouseover', "item_"+id+"_"+i, function(e)
                            {
                                var el = WFX.Events.GetElement(e);
                                last_color = el.style.color;
                                el.style.color = "#ffffff";
                                el.style.background="#316ac5";
                            });
                            WFX.Events.AddEventHandler('mouseout', "item_"+id+"_"+i, function(e)
                            {
                                var el = WFX.Events.GetElement(e);
                                el.style.color = last_color;
                                el.style.background="#ffffff";
                            });
                        }
                        
                    }
                out += "</table>";
            out += "</div>";    
        
       document.write(out);
       
       
       for(var i=0; i<handlers.length; i++)
       {
            if (handlers[i] == null)
            {
                this.DeactivateItem(i+1);
            }
       }
       
       WFX.Events.AddEventHandler('click', document.body, function(e)
       {
            var $this = WFX.Globals.GetObject(id);
            if ($this.IsVisible() == true)
            {
                var intv = setTimeout
                (
                    function()
                    {
                        $this.Hide();
                    }, 
                    
                    100
                );
            }
       });
    };   
    
    this.IsVisible = function()
    {
        var main = WFX.GetElement(id);
        return WFX.IsVisible(main);
    };
    
    this.Show = function()
    {
        if (onmenu != null)
        {
            onmenu(srcelement);
        }
        var main = WFX.GetElement(id);
        WFX.ShowElement(main);
    };
    
    this.Hide = function()
    {
        var main = WFX.GetElement(id);
        WFX.HideElement(main);
    };

    
    this.AddItem = function(title, handler, icon)
    {
        items[items.length] = title;
        handlers[handlers.length] = handler;
        icons[icons.length] = icon;
        active[active.length] = 1;
    };
    
    this.DeactivateItem = function(i)
    {
        /*if (this.IsActiveItem(i) == false)
        {
            return;
        }*/

        var item = WFX.GetElement("row_"+id+"_"+(i-1));
        active[i-1]=0;
        WFX.Events.RemoveEventHandler('mouseup', item, RunMouseClickHandlers);
        item.firstChild.nextSibling.style.color = "#999999";
    };
  
    this.IsActiveItem = function(i)
    {
        return active[i-1] == 1; 
    };
    
    this.ActivateItem = function(i)
    {
        if (this.IsActiveItem(i))
        {
            return;
        }

        var item = WFX.GetElement("row_"+id+"_"+(i-1));
       
        WFX.Events.AddEventHandler('mouseup', item, RunMouseClickHandlers);
        item.firstChild.nextSibling.style.color = "#000000";
        active[i-1] = 1;
    };
    
    var RunMouseClickHandlers = function(e)
    {
        var elm = WFX.Events.SrcElement(e);
        
        var ind = 0;
        if (elm.tagName == "TD")
        {
            ind = elm.id.split("_");
        }
        else if(elm.tagName == "IMG")
        {
            ind = elm.parentNode.id.split("_");
        }
        
        var $this = WFX.Globals.GetObject(id);
        $this.Hide();
        
        if (handlers[ind[2]] != null)
        {
            handlers[ind[2]]($this.GetElement());
        }
        
    };
    
    this.Rename = function(index, title)
    {
        items[index-1] = title;
        
        var el = WFX.GetElement(id);
        
        el.firstChild.firstChild.childNodes.item(index-1).childNodes.item(1).innerHTML=title;
    };
    
    this.Destroy = function()
    {
        var main = WFX.GetElement(id);
        if (main != null)
        {
            main.parentNode.removeChild(main);
        }
    };
};

WFX.Controls.DropDownList = function(name, with_empty_item)
{
    var id = name;
    var items = [];
    var _width = null;
    var ready = false;
    var with_empty = with_empty_item || false;
    
    var req = new WFX.Ajax.Request
    (
        function()
        {
            ready = false;
        }, 
        
        function(response) 
        {
        
            if (WFX.Strings.Trim(response).length == 0)
            {
                return;
            }
            
            if(ready == true)
            {
                return;
            }
            
		    var msg = response.split("::");

			msg = msg[msg.length-1];

		    if (response.length > 0) 
		    {
			    var temp_items = msg.split("|");
			    for (var i = 0; i < temp_items.length; i++) 
			    {
				    items[i] = new Array();
				    items[i][0] = temp_items[i].split(":")[0];
				    items[i][1] = temp_items[i].split(":")[1];
			    }
		    }
		    ready = true;
	    }
	);
    var busy = false;
    this.Reload = function(url)
    {
        busy = true;
        this.Clear();
        req.Get(url);
        
        var intv = setInterval
        ( 
            function()
            {
                if (ready == false)
                {
                    return;
                }
                else
                {
                    clearInterval(intv);
                }
                Fill();
            }, 
            100
        );    
    };
    
    this.Load = function(url)
    {
        var list = WFX.GetElement(id);
        
        if (list.childNodes.length > 1)
        {
            return;
        }
        
        init_url = url;
        this.Reload(url);
    };
    
    this.Clear = function() 
	{
		var list = WFX.GetElement(id);
		while (list.childNodes.length > 0) 
		{
			list.removeChild(list.firstChild);
		}

		selected_id = null;
	};
	
	var Fill = function()
	{
	    var list = WFX.GetElement(id);
	    
	    if (with_empty_item == true)
	    {
	        var option = document.createElement("option");
            option.setAttribute("value", -1);
            option.innerHTML = "&nbsp;";
            list.appendChild(option);
	    }

        for (var i=0; i< items.length; i++)
        {
            var option = document.createElement("option");
            option.setAttribute("value", items[i][0]);
            option.innerHTML = items[i][1];
            list.appendChild(option);
        }    
        
        busy = false;
	};
	
    this.Build = function(width)
    {
        _width = width;

        var out = "<select style='border-style:solid; border-width:1px; border-color:#898c95; width:"+_width+"px' name='"+id+"' id='"+id+"' size='1'></select>";
        return out;    
    };
    
    this.Show = function(width)    
    {
        document.write(this.Build(width)); 
        
        WFX.Events.AddEventHandler('change', id, RunChangeHandlers);       
    };
    
    this.GetName = function()
    {
        return id;
    };
    
    this.GetValue = function()
    {
        var parent = WFX.GetElement(id);
        
        if (parent.selectedIndex == -1)
        {
            return "";
        }
        
        return parent.childNodes.item(parent.selectedIndex).value;
    }; 
    
    this.SetValue = function(value)
    {
        var intv = setInterval(function()
        {
            if (busy == true)
            {
                return;
            }
            else
            {
                clearInterval(intv);
            }
            
            var parent = WFX.GetElement(id);
        
            for (var i=0; i<parent.childNodes.length; i++)
            {
                if (parent.childNodes.item(i).value == value)
                {
                    parent.selectedIndex = i;
                    break;
                }
            }
        
        },
        
        100);
    };
    
    var handlers = [];
    
    this.AddChangeHandler = function(handler)
    {
        handlers[handlers.length] = handler;
    };
    
    var RunChangeHandlers = function(e)
    {
        var val = null;
        
        var parent = WFX.Events.GetElement(e);
        
        if (parent.selectedIndex == -1)
        {
            val = "";
        }
        
        val = parent.childNodes.item(parent.selectedIndex).value;
        
        for (var i=0; i<handlers.length; i++)
        {
            handlers[i](e, val);
        }   
    };
};


WFX.Selection = new function()
{
    var preventSelection = false;
    
    this.RemoveSelection = function()
    {
        if (window.getSelection) 
        { 
            window.getSelection().removeAllRanges(); 
        }
        else if (document.selection && document.selection.clear)
        {
            document.selection.clear();
        }
    };
    
    this.KillCtrlA = function(event)
    {
        var event = event || window.event;
        var sender = event.target || event.srcElement;

        if (sender.tagName.match(/INPUT|TEXTAREA/i))
          return;

        var key = event.keyCode || event.which;
        if (event.ctrlKey && key == 'A'.charCodeAt(0))  // 'A'.charCodeAt(0) можно заменить на 65
        {
            WFX.Selection.RemoveSelection();

            if (event.preventDefault) 
                event.preventDefault();
            else
                event.returnValue = false;
        }
    };
    
    
    this.PreventSelection = function(element)
    {
        
        // не даем выделять текст мышкой
        WFX.Events.AddEventHandler('mousemove', element, function()
        {
            if(preventSelection)
            {
                WFX.Selection.RemoveSelection();
            }
        });
        
        WFX.Events.AddEventHandler('mousedown', element, function(event)
        {
            var event = event || window.event;
            var sender = event.target || event.srcElement;
            preventSelection = !sender.tagName.match(/INPUT|TEXTAREA/i);
        });

        // борем dblclick
        // если вешать функцию не на событие dblclick, можно избежать
        // временное выделение текста в некоторых браузерах
        WFX.Events.AddEventHandler('mouseup', element, function()
        {
            if (preventSelection)
            {
                WFX.Selection.RemoveSelection();
            }
            preventSelection = false;
        });

      // борем ctrl+A
      // скорей всего это и не надо, к тому же есть подозрение
      // что в случае все же такой необходимости функцию нужно 
      // вешать один раз и на document, а не на элемент
      WFX.Events.AddEventHandler('keydown', element, this.KillCtrlA);
      WFX.Events.AddEventHandler('keyup', element, this.KillCtrlA);
    };

};

function preventSelection(element)
{
    WFX.Selection.PreventSelection();
}
// ----------------------------------------------
var __WFXLOADED = true;


