//forms plugin
/*
 * jQuery Form Plugin
 * version: 2.12 (06/07/2008)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: jQueryIdjQuery
 */
(function(jQuery) {

/*
    Usage Note:
    -----------
    Do not use both ajaxSubmit and ajaxForm on the same form.  These
    functions are intended to be exclusive.  Use ajaxSubmit if you want
    to bind your own submit handler to the form.  For example,

    jQuery(document).ready(function() {
        jQuery('#myForm').bind('submit', function() {
            jQuery(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });

    Use ajaxForm when you want the plugin to manage all the event binding
    for you.  For example,

    jQuery(document).ready(function() {
        jQuery('#myForm').ajaxForm({
            target: '#output'
        });
    });

    When using ajaxForm, the ajaxSubmit function will be invoked for you
    at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
jQuery.fn.ajaxSubmit = function(options) {
    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

    options = jQuery.extend({
        url:  this.attr('action') || window.location.toString(),
        type: this.attr('method') || 'GET'
    }, options || {});

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
   }

    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data)
            a.push( { name: n, value: options.data[n] } );
    }

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }

    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }

    var q = jQuery.param(a);

    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var jQueryform = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { jQueryform.resetForm(); });
    if (options.clearForm) callbacks.push(function() { jQueryform.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            jQuery(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i].call(this, data, status, jQueryform);
    };

    // are there files to upload?
    var files = jQuery('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) {
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if (jQuery.browser.safari && options.closeKeepAlive)
           jQuery.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       jQuery.ajax(options);

    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;


    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = jQueryform[0];

        if (jQuery(':input[@name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }

        var opts = jQuery.extend({}, jQuery.ajaxSettings, options);

        var id = 'jqFormIO' + (new Date().getTime());
        var jQueryio = jQuery('<iframe id="' + id + '" name="' + id + '" />');
        var io = jQueryio[0];

        if (jQuery.browser.msie || jQuery.browser.opera)
            io.src = 'javascript:false;document.write("");';
        jQueryio.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {}
        };

        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! jQuery.active++) jQuery.event.trigger("ajaxStart");
        if (g) jQuery.event.trigger("ajaxSend", [xhr, opts]);

        var cbInvoked = 0;
        var timedOut = 0;

        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }

        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = jQueryform.attr('target'), a = jQueryform.attr('action');
            jQueryform.attr({
                target:   id,
                encoding: 'multipart/form-data',
                enctype:  'multipart/form-data',
                method:   'POST',
                action:   opts.url
            });

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            jQuery('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);

                // add iframe to doc and submit the form
                jQueryio.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                jQueryform.attr('action', a);
                t ? jQueryform.attr('target', t) : jQueryform.removeAttr('target');
                jQuery(extraInputs).remove();
            }
        }, 10);

        function cb() {
            if (cbInvoked++) return;

            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var operaHack = 0;
            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;

                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;

                if (doc.body == null && !operaHack && jQuery.browser.opera) {
                    // In Opera 9.2.x the iframe DOM is not always traversable when
                    // the onload callback fires so we give Opera 100ms to right itself
                    operaHack = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }

                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = jQuery.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                jQuery.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how jQuery.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) jQuery.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) jQuery.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --jQuery.active) jQuery.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

            // clean up
            setTimeout(function() {
                jQueryio.remove();
                xhr.responseXML = null;
            }, 100);
        };

        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
jQuery.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        jQuery(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        jQuery(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var jQueryform = this.form;
            jQueryform.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    jQueryform.clk_x = e.offsetX;
                    jQueryform.clk_y = e.offsetY;
                } else if (typeof jQuery.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = jQuery(this).offset();
                    jQueryform.clk_x = e.pageX - offset.left;
                    jQueryform.clk_y = e.pageY - offset.top;
                } else {
                    jQueryform.clk_x = e.pageX - this.offsetLeft;
                    jQueryform.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { jQueryform.clk = jQueryform.clk_x = jQueryform.clk_y = null; }, 10);
        });
    });
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
jQuery.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        jQuery(":submit,input:image", this).unbind('click.form-plugin');
    });

};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: jQuery.get, jQuery.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
jQuery.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = jQuery.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
jQuery.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return jQuery.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
jQuery.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = jQuery.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return jQuery.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = jQuery(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = jQuery(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = jQuery(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
jQuery.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = jQuery.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? jQuery.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
jQuery.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = jQuery.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
jQuery.fn.clearForm = function() {
    return this.each(function() {
        jQuery('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.
 */
jQuery.fn.clearFields = jQuery.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
jQuery.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

/**
 * Enables or disables any matching elements.
 */
jQuery.fn.enable = function(b) {
    if (b == undefined) b = true;
    return this.each(function() {
        this.disabled = !b
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
jQuery.fn.select = function(select) {
    if (select == undefined) select = true;
    return this.each(function() {
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var jQuerysel = jQuery(this).parent('select');
            if (select && jQuerysel[0] && jQuerysel[0].type == 'select-one') {
                // deselect all other options
                jQuerysel.find('option').select(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// set jQuery.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if (jQuery.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};


})(jQuery);

//scrollTo plugin
(function( jQuery ){

	var jQueryscrollTo = jQuery.scrollTo = function( target, duration, settings ){
		jQuery(window).scrollTo( target, duration, settings );
	};

	jQueryscrollTo.defaults = {
		axis:'y',
		duration:1
	};

	jQueryscrollTo.window = function( scope ){
		return jQuery(window).scrollable();
	};

	jQuery.fn.scrollable = function(){
		return this.map(function(){
			var win = this.parentWindow || this.defaultView,
				elem = this.nodeName == '#document' ? win.frameElement || win : this,
				doc = elem.contentDocument || (elem.contentWindow || elem).document,
				isWin = elem.setInterval;

			return elem.nodeName == 'IFRAME' || isWin && jQuery.browser.safari ? doc.body
				: isWin ? doc.documentElement
				: this;
		});
	};

	jQuery.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };

		settings = jQuery.extend( {}, jQueryscrollTo.defaults, settings );
		duration = duration || settings.speed || settings.duration;
		settings.queue = settings.queue && settings.axis.length > 1;

		if( settings.queue )
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this.scrollable().each(function(){
			var elem = this,
				jQueryelem = jQuery(elem),
				targ = target, toff, attr = {},
				win = jQueryelem.is('html,body');

			switch( typeof targ ){
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(px)?jQuery/.test(targ) ){
						targ = both( targ );
						break;
					}
					targ = jQuery(targ,this);
				case 'object':
					if( targ.is || targ.style )
						toff = (targ = jQuery(targ)).offset();
			}
			jQuery.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					Dim = axis == 'x' ? 'Width' : 'Height',
					dim = Dim.toLowerCase();

				if( toff ){
					attr[key] = toff[pos] + ( win ? 0 : old - jQueryelem.offset()[pos] );

					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}

					attr[key] += settings.offset[pos] || 0;

					if( settings.over[pos] )
						attr[key] += targ[dim]() * settings.over[pos];
				}else
					attr[key] = targ[pos];

				if( /^\d+jQuery/.test(attr[key]) )
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );

				if( !i && settings.queue ){
					if( old != attr[key] )
						animate( settings.onAfterFirst );
					delete attr[key];
				}
			});
			animate( settings.onAfter );

			function animate( callback ){
				jQueryelem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};
			function max( Dim ){
				var attr ='scroll'+Dim,
					doc = elem.ownerDocument;

				return win
						? Math.max( doc.documentElement[attr], doc.body[attr]  )
						: elem[attr];
			};
		}).end();
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );

jQuery.fn.bgIframe = jQuery.fn.bgiframe = function() {
    // This is only for IE6
    if ( !(jQuery.browser.msie && typeof XMLHttpRequest == 'function') ) return this;
    var html = '<iframe class="bgiframe" src="javascript:;" tabindex="-1" '
    		    +'style="display:block; position:absolute; '
			+'top: expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)  || 0) * -1) + \'px\'); '
			+'left:expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth) || 0) * -1) + \'px\'); '
			+'z-index:-1; filter:Alpha(Opacity=\'0\'); '
			+'width:expression(this.parentNode.offsetWidth + \'px\'); '
			+'height:expression(this.parentNode.offsetHeight + \'px\')"/>';
    return this.each(function() {
	if ( !jQuery('iframe.bgiframe', this)[0] )
	    this.insertBefore( document.createElement(html), this.firstChild );
    });
};

/**
 * jQuery.Preload
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com
 * Dual licensed under MIT and GPL.
 * Date: 3/12/2008
 *
 * @projectDescription Multifunctional preloader
 * @author Ariel Flesler
 * @version 1.0.7
 *
 * @id jQuery.preload
 * @param {String, jQuery, Array< String, <a>, <link>, <img> >} original Collection of sources to preload
 * @param {Object} settings Hash of settings.
 *
 * @id jQuery.fn.preload
 * @param {Object} settings Hash of settings.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @example Link Mode:
 *	jQuery.preload( '#images a' );
 *
 * @example Rollover Mode:
 *	jQuery.preload( '#images img', {
 *		find:/\.(gif|jpg)/,
 *		replace:'_over.jQuery1'
 *	});
 *
 * @example Src Mode:
 *	jQuery.preload( [ 'red', 'blue', 'yellow' ], {
 *		base:'images/colors/',
 *		ext:'.jpg'
 *	});
 *
 * @example Placeholder Mode:
 *	jQuery.preload( '#images img', {
 *		placeholder:'placeholder.jpg',
 *		notFound:'notfound.jpg'
 *	});
 *
 * @example Placeholder+Rollover Mode(High res):
 *	jQuery.preload( '#images img', {
 *		placeholder:true,
 *		find:/\.(gif|jpg)/,
 *		replace:'_high.jQuery1'
 *	});
 */
(function( jQuery ){

	var jQuerypreload = jQuery.preload = function( original, settings ){
		if( original.split )//selector
			original = jQuery(original);

		settings = jQuery.extend( {}, jQuerypreload.defaults, settings );
		var sources = jQuery.map( original, function( source ){
			if( !source )
				return;//skip
			if( source.split )//URL Mode
				return settings.base + source + settings.ext;
			var url = source.src || source.href;//save the original source
			if( typeof settings.placeholder == 'string' && source.src )//Placeholder Mode, if it's an image, set it.
				source.src = settings.placeholder;
			if( url && settings.find )//Rollover mode
				url = url.replace( settings.find, settings.replace );
			return url || null;//skip if empty string
		});

		var data = {
			loaded:0,//how many were loaded successfully
			failed:0,//how many urls failed
			next:0,//which one's the next image to load (index)
			done:0,//how many urls were tried
			//found:false,//whether the last one was successful
			total:sources.length//how many images are being preloaded overall
		};

		if( !data.total )//nothing to preload
			return finish();

		var imgs = '<img/>',//ensure one
			thres = settings.threshold;//save a copy

		while( --thres > 0 )//it could be oddly negative
			imgs += '<img/>';
		imgs = jQuery(imgs).load(handler).error(handler).bind('abort',handler).each(fetch);

		function handler( e ){
			data.found = e.type == 'load';
			data.image = this.src;
			var orig = data.original = original[this.index];
			data[data.found?'loaded':'failed']++;
			data.done++;
			if( settings.placeholder && orig.src )//special case when on placeholder mode
				orig.src = data.found ? data.image : settings.notFound || orig.src;
			if( settings.onComplete )
				settings.onComplete( data );
			if( data.done < data.total )//let's continue
				fetch( 0, this );
			else{//we are finished
				if( imgs.unbind )//sometimes IE gets here before finishing line 84
					imgs.unbind('load').unbind('error').unbind('abort');//cleanup
				imgs = null;
				finish();
			}
		};
		function fetch( i, img, retry ){
			if( jQuery.browser.msie && data.next && data.next % jQuerypreload.gap == 0 && !retry ){//IE problem, can't preload more than 15
				setTimeout(function(){ fetch( i, img, true ); }, 0);
				return false;
			}
			if( data.next == data.total ) return false;//no more to fetch
			img.index = data.next;//save it, we'll need it.
			img.src = sources[data.next++];
			if( settings.onRequest ){
				data.image = img.src;
				data.original = original[data.next-1];
				settings.onRequest( data );
			}
		};
		function finish(){
			if( settings.onFinish )
				settings.onFinish( data );
		};
	};

	// each time we load this amount and it's IE, we must rest for a while, make it lower if you get stack overflow.
	jQuerypreload.gap = 14;

	jQuerypreload.defaults = {
		threshold:2,//how many images to load simultaneously
		base:'',//URL mode: a base url can be specified, it is prepended to all string urls
		ext:'',//URL mode:same as base, but it's appended after the original url.
		replace:''//Rollover mode: replacement (can be left empty)
		/*
		find:null,//Rollover mode: a string or regex for the replacement
		notFound:''//Placeholder Mode: Optional url of an image to use when the original wasn't found
		placeholder:'',//Placeholder Mode: url of an image to set while loading
		onRequest:function( data ){ ... },//callback called every time a new url is requested
		onComplete:function( data ){ ... },//callback called every time a response is received(successful or not)
		onFinish:function( data ){ ... }//callback called after all the images were loaded(or failed)
		*/
	};

	jQuery.fn.preload = function( settings ){
		jQuerypreload( this, settings );
		return this;
	};

})( jQuery );
//!!!!



function _uGetOffset(obj){
	if(!obj) return { 'left' : 0, 'top' : 0 };
	var left_offset = obj.offsetLeft;
	var top_offset = obj.offsetTop;
	if(!left_offset && !top_offset && obj.offsetParent==null) {
	left_offset=parseInt(obj.style.left);
	top_offset=parseInt(obj.style.top);
	} else
	while ((obj = obj.offsetParent) != null)
	{
		left_offset += obj.offsetLeft;
		top_offset += obj.offsetTop;
	}

	return { 'left' : left_offset, 'top' : top_offset };
}


function _uMenu(id,par,group) {
    this.init(id,par,group);
}
_uMenu.get=function(id) {
    var o=jQuery('#'+id)[0];
    if(o) return o._umenu;
    return null;
}
_uMenu.show=function(id,par,tp,mid,dy,dx) {
    var o=_uMenu.get(id);
    if(o)o.show_menu(par,tp,mid,dy,dx);
};
_uMenu.hide=function(id,c) {
    var o=_uMenu.get(id);
    if(o) if(!c)o.hide_menu();else o.hide_child();
};
_uMenu.hideAll=function(e) {
//    if (e.which!=1 && e.type == 'click')return;
    var gr;
    with(_uMenu.prototype) {
	for (gr in have_active) {
	    if(have_active[gr] && !donothide[gr]) {
		for (var i in all_menus[gr]) _uMenu.hide(i);
    	    have_active[gr]='';
	    }
	donothide[gr]=false;
	}
    }
};
_uMenu.showOver=function (id,par,tp,mid,dy,dx) {
    var o=_uMenu.get(id);
    if(o) {
	var gr=o.group;
        with(_uMenu.prototype) {
	    if(timerid2[gr]) clearTimeout(timerid2[gr]);
	    if (have_active[gr].length>0 && have_active[gr].indexOf(","+id+",")==-1)
		o.show_menu(par,tp,mid,dy,dx);
	}
    }
};
_uMenu.schedule_hidechild=function(id) {
    var o=_uMenu.get(id);
    if(o) {
	var gr=o.group;
        with(_uMenu.prototype) {
    	if(timerid2[gr]) clearTimeout(timerid2[gr]);
	    timerid2[gr]=setTimeout("_uMenu.hide('"+id+"',1);_uMenu.prototype.timerid2['"+gr+"']=0;",800);
	}
    }
}

_uMenu.prototype={
    donothide: [], //group is first key
    all_menus: [], //group is first key
    have_active: [], //group is first key
    timerid: [], //group is first key
    timerid2: [], //group is first key
    global_set: false,
    init: function (id,par,group){
		this.id=id;
        this.obj=jQuery('#'+id)[0];
        if(!this.obj) return;
        this.obj._umenu=this;
        if(!par) par=id;
        this.parentid=par;
        if(!group) group='def';
        this.group=group;
        this.obj.style.display = 'none';
        jQuery(this.obj).bind("click",this,function(e) {e.data.donothide[e.data.group]=true;});
	if(this.all_menus[group]==undefined) this.all_menus[group]=[];
	if(this.have_active[group]==undefined) this.have_active[group]='';
	this.all_menus[group][id]=this;
	if(!this.global_set) {
	    jQuery(document).bind("click",_uMenu.hideAll);
	    jQuery(window).bind("resize",_uMenu.hideAll);
	    _uMenu.prototype.global_set=true;
	}
    },
    show_menu: function (par,tp,mid,dy,dx) {
        var ddX=0;
        var ddY=0;
        if(this.timerid2[this.group]) clearTimeout(this.timerid2[this.group]);
        if(this.have_active[this.group].indexOf(","+this.id+",")>=0) {
                this.hide_menu();
                return;
        }
        if(!dy)dy=0;
        if(!dx)dx=0;
        if(mid){
                ddX=jQuery('#'+mid)[0].offsetLeft;
                ddY=jQuery('#'+mid)[0].offsetTop;
        }
        this.allmenus_hidenp();
        if(!par) par=this.obj.parentNode; else par=jQuery('#'+par)[0];
        var pos=_uGetOffset(par);
        pos['left']+=dx-ddX;
        pos['top']+=dy-ddY;
        if(tp=='r') pos['left']+=par.offsetWidth-4;
    	    else pos['top']+=par.offsetHeight+1; //tp=='d'
        var ww=jQuery(window).width();
        with(this.obj.style) {
    	left=pos['left']+'px';
    	top=pos['top']+'px';
    	display='';
    	visibility='visible';
        };
        try { if(pos['left']+this.obj.offsetWidth>ww) {
                pos['left']=ww-this.obj.offsetWidth-5;
                this.obj.style.left=pos['left']+'px';
                }
        } catch(e) {}
        if(!this.have_active[this.group]) this.have_active[this.group]='';
        this.have_active[this.group]+=','+this.id+',';
        if(this.timerid[this.group]) clearTimeout(this.timerid[this.group]);
        this.donothide[this.group]=true;
        this.timerid[this.group]=setTimeout("with(_uMenu.prototype){donothide['"+this.group+"']=false;timerid['"+this.group+"']=null;};",100);
    },
    allmenus_hidenp: function () {
        var parents={};
        var id=this.id;
        while(this.all_menus[this.group][id] && this.all_menus[this.group][id].parentid!=id && id) {parents[this.all_menus[this.group][id].parentid]=1;id=this.all_menus[this.group][id].parentid;}
        for (var i in this.all_menus[this.group]) {
                if(parents[i]==1) continue;
                this.all_menus[this.group][i].hide_menu();
        }
    },
    hide_menu: function () {
      with(this) {
        hide_child();
        var x=have_active[group].indexOf(","+id+",");
        if(x>=0) have_active[group]=have_active[group].substring(0,x);
        obj.style.display = 'none';
        obj.style.visibility = 'hidden';
      }
    },
    hide_child: function () {
      with(this) {
        for (var i in all_menus[group]) if(all_menus[group][i].parentid==id && i!=id) all_menus[group][i].hide_menu();
      }
    }
};


/*
Each menu item can be in form:
1.  'string' - just string with default action onitem (if it's defined) or without action. in last case item has not hover hightlight by default
2.  'sep' - separator
3.  ['label',action,props]
	def props is {hl:0} if action is not defined
	action can be:
	3.1 'a' - tells that item has <a> tag and item action is to follow href in that tag
	3.2 function - action(item_index,menuobj,id,item_opts). if null then global onitem is used. default this parameter is thispar from menu props
	3.3 array - submenu
	props:
		{
		action - 'a' or function is second element was array for creating submenu (to add action to item opening submenu)
		id - item string id which will be sent to action or onitem func in addition to index
		hl  - hover highlight. can be used to overwrite menu property
		thispar - this parameter for action
		mark - if menu has marks enabled specifies the state of mark (false - hidden, true - visible)
		marktext - if mark is visible (mark is true) then specifies html content for mark element (e.g. img tag). can be specified as array (object). then mark true values are used as index to this array. menu.props.withmarks is the default value of this field
		onldown - action for left mouse down
		onrdown - action for right mouse down
		pos - override default pos properties for submenu
		opts - override default properties for submenu
		}
*/

function _uMENU(name,pos,opts,elems,noinit) {
	this.constructor=_uMENU;
	this.name=name;
	this.pos=jQuery.extend({
		pos: null,
		alignObj: null,
		align: 'd',
//r(R) - to the right from object + dx, top edge from object + dy ; R will change horiz pos to l-rules if goes out screen
//l(L) - to the left from object + dx, top edge from object + dy ; L will change horiz pos to r-rules if goes out screen
//d(D) - left (right from rtl) edge from object+dx, to the down from object + dy ; D will change vert pos to u-rules if goes out screen
//u(U) - left (right from rtl) edge from object+dx, to the up from object + dy ; U will change vert pos to d-rules or horiz pos to l-rules if goes out screen
		parent: null,
		dx:0,
		dy:0,
		childdy:0,
		childdx:0
	},pos || {});
	this.props=jQuery.extend({
		parentnode: null, //inherited by child menus
		design: _uMENU.defdesign || 'std',
		hidden: opts.static && elems && elems.length>0 ? 0 : 1,
		shadow: 1,
		addclass: '', //add this class to class of top menu html object
		withmarks: null, //if true (some object specified) then items of this menu can have marks to the left (u-menumarks is added to top menu object). value of this field is the default marktext
		highlight: 1, //whether hovered items must be highlighted by adding class u-menuitemhl
		static: opts.horiz ? 1 : 0, //do not hide menu on mouse clicks
		hidetimer: 0, //time in ms to hide menu if no item was hovered
		horiz: 0, //whether menu is horizontal
		noabs: 0, //do not use position:absolute for menu
		width: 0, //0 - width is calculated by content, auto - width is just not assigned (for noabs=1), X - specified value
		onshow: null, //(menuobj,menuidx) called just before menu is shown (can be used to set marks)
		onhide: null,
		ondestroy: null,
		onitem: null, //inherited by child menus, reaction to item click
		onldown: null, //inherited by child menus, reaction to item left mouse down
		onrdown: null, //inherited by child menus, reaction to item right mouse down
		thispar: null, //'this' param for handlers; inherited by child menus
		wnd:null, //inherited by child menus
		rtl:0 //inherited by child menus
	},opts || {});
	this.state={visible:false,init:false,destroyed:false};
    this.design=this.props.design && _uMENU.designs[this.props.design] ? _uMENU.designs[this.props.design] : _uMENU.designs['std'];
    this.idx=_uMENU.nextidx++;
    _uMENU.all[this.idx]=this;
   	if(!this.pos.parent) this.zpos=_uMENU.defz;
   		else this.zpos=this.pos.parent.zpos+5;
    this.xpos=this.ypos=0;
	this.width=10;
	this.height=10;
	this.elems=[];
	this.add_elems=elems && elems.length>0 ? [elems] : [];
	this.del_elems=[];
	this.pend_show=null;
	this.appendtimer=null;
	this.decor={w:0,h:0};
	this.frame=null;
	this.childtimer=null;
	this.sh=null;
	this.have_active=null;
	this.hidetimer=null;

	var t=document.createElement("div");
	t.id="_umenu"+this.idx;
	if(!this.props.parentnode) jQuery(jQuery("body")[0]).prepend(t);
		else this.props.parentnode.appendChild(t);

	this.top=t;
    jQuery(t).addClass("x-unselectable").css({visibility:'hidden',display:'block'});
    var m=document.createElement("div");
    t.appendChild(m);
    this.menu=m;

	if(
//	!this.props.horiz ||
	!this.props.noabs) {
    	jQuery(t).css({position:'absolute',zIndex:this.zpos});
	    if(jQuery.browser.msie && parseFloat(jQuery.browser.version)<7){
		    var html = '<iframe tabindex="-1" '
    		    +'style="display:block; position:absolute; '
			+'filter:Alpha(Opacity=\'0\'); '
			+'width:'+this.width+'px'
			+'height:'+this.height+'px;border:0"/>';

	    	this.frame=document.createElement(html);
			t.appendChild(this.frame);
	    }
	    if(this.props.shadow && !this.props.horiz && (!jQuery.browser.msie || jQuery.browser.version>6)) {
			this.shadow_init();
			this._resizeSh();
	    }
    	jQuery(m).css({position:"absolute",zIndex:2,left:0});
	}
   	jQuery(m).css("width","50px").bind("mousedown",this,_uMENU._onmenumousedown);

    this.parts=this.design.menu_init(m,this.props.horiz ? 10 : 50,this.props,this.pos.parent);
	if(!_uMENU.globalset) {
		_uMENU.globalset=true;
	    jQuery(document).bind("mousedown",_uMENU.hideallmenus);
	    jQuery(window).bind("resize",_uMENU.hideallmenus);
	}
	this.toinit=[]; //submenus which require init1()
	this.tocalcsize=[]; //submenus which require calcsize()
	this.createsubmenus();

	if(!this.props.hidden) this.show();
	if(!noinit)setTimeout("var m=_uMENU.all["+this.idx+"];if(m)m.init1();",10);
}


_uMENU.all=[];
_uMENU.nextidx=0;
_uMENU.lastz=0;
_uMENU.defz=20050;
_uMENU.defdesign='std';
_uMENU.globalset=false;
_uMENU.ignoreclick=null;

_uMENU.getbyname=function(name) {
    var a=this.all;
    for(var i=0;i<a.length;i++) if(a[i] && a[i].name==name) return a[i];
    return null;
};

_uMENU.designs={
    std: {
	sh_sz: [4,2], //design specific shadow config

	shadow_init: function(top) {
	    var sh=[];
	    for(var i=0;i<3;i++) {
		sh[i]=document.createElement("div");
		top.appendChild(sh[i]);
		jQuery(sh[i]).attr("class","x-sh").css("position","absolute").css("z-index",1);
	    }
	    jQuery(sh[0]).addClass("xsl").css({width:(this.sh_sz[0]+this.sh_sz[1])+"px",left:(-this.sh_sz[0])+"px",top:"0px"}).html('<div class="xstl"><div class="xsml"></div></div>');
	    jQuery(sh[1]).addClass("xsr").css({width:(this.sh_sz[0]+this.sh_sz[1])+"px",top:"0px"}).html('<div class="xstr"><div class="xsmr"></div></div>');
	    jQuery(sh[2]).addClass("xsb").css({height:(this.sh_sz[0]+this.sh_sz[1])+"px",left:(-this.sh_sz[0])+"px"}).html('<div class="xsbl"><div class="xsbr"><div class="xsbc"></div></div></div>');
	    return sh;
	},
	shadow_resize: function(sh,w,h) {
	    jQuery(sh[0]).css({height:(h-this.sh_sz[1])+"px"});
	    jQuery(sh[1]).css({height:(h-this.sh_sz[1])+"px",left:(w-this.sh_sz[1])+"px"});
	    jQuery(sh[2]).css({width:(w+this.sh_sz[0]*2)+"px",top:(h-this.sh_sz[1])+"px"});
	},
	shadow_hide: function(sh) {
	    jQuery(sh[0]).add(sh[1]).add(sh[2]).hide();
	},
	shadow_show: function(sh) {
	    jQuery(sh[0]).add(sh[1]).add(sh[2]).show();
	},
	menu_init: function(menu,inith,props,parent) {
	    var p={};
		if(!props.horiz) {
			jQuery(menu).attr("class","u-menu"+(props.addclass ? ' '+String(props.addclass): '')+(props.withmarks ? ' u-menumarks': ''));
			if(jQuery.browser.msie) jQuery(menu).css("overflow","hidden");
		    jQuery(menu).html(
(parent && parent.props.horiz ? '' : '<div class="xw-tl"><div class="xw-tr"><div class="xw-tc xw-tsps"></div></div></div>')
+ '<div class="xw-ml"><div class="xw-mr"><div class="xw-mc"><div class="u-menubody">'
+ '<div class="u-menucont" style="overflow:visible;height:'+inith+'px"></div></div></div></div></div>'
+ '<div class="xw-bl"><div class="xw-br"><div class="xw-bc"><div class="xw-footer"></div></div></div></div>'
		    );
//		    p.upper=jQuery(menu).find(".xw-tl")[0];
//		    p.center=jQuery(wnd).find(".xw-ml")[0];
//	    	jQuery(wnd).find(".xw-mc").bind("mousedown",function(e){e.stopPropagation();});
		} else {
			jQuery(menu).attr("class","u-menuh"+(props.addclass ? ' '+String(props.addclass): '')+(props.withmarks ? ' u-menumarks': '')).css("overflow","hidden");
			jQuery(menu).html('<div class="u-menubody"><div class="u-menucont" style="overflow:hidden;height:'+inith+'px"></div></div>');
		}
	    p.content=jQuery(menu).find(".u-menucont")[0];
		p.elems=[];
		p.marks=[];
		jQuery(menu).find("div,span").andSelf().attr("unselectable","on");
	    return p;
	},
	append_item: function(o,el,hl) {
		var i=o.elems.length,a,txt,act=null,mark,actl,actr;
		act=el[1] || el[2].action || o.props.onitem;
		actl=el[2].onldown || o.props.onldown;
		actr=el[2].onrdown || o.props.onrdown;
		txt=el[0];
		if(el[2].hl!=undefined) hl=el[2].hl;
		if(o.props.withmarks && txt!='sep' && el[2].mark!=undefined) { //if we have to add u-menumark object
			txt='<div class="u-menumark"></div>'+txt;
			mark=1;
		}
		if(act && (act=='a' || el[2].action=='a')) {
			a=document.createElement('a');
			jQuery(a).css('display','block');
		} else a=document.createElement('div');
		if(!o.props.horiz) {
			if(txt=='sep') {
				a.className='u-menuvsep';
			} else {
				a.className='u-menuvitem';
				if(!act || act.constructor!=_uMENU) {
					jQuery(a).html(txt);
					if(hl) jQuery(a).bind("mouseover",{hl:hl,item:-1,obj:o},_uMENU._onitemmouseover).bind("mouseout",{hl:hl,item:-1,obj:o},_uMENU._onitemmouseout);
					if(act) jQuery(a).bind("click",{act:act,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(actl || actr) jQuery(a).bind("mousedown",{actl:actl,actr:actr,obj:o,item:i,itemobj:el},_uMENU._onitemmousedown);
				} else {
//					jQuery(a).addClass('u-menuvitemparent').html('<div class="u-menuarrow" style="float:right"></div>'+txt);
//					jQuery(a).addClass('u-menuvitemparent').html('<table align="center" style="text-align:left;padding:0;margin:0;botder:0" cellspacing="0" cellpadding="0"><tr><td style="white-space:nowrap">'+txt+'</td><td><div class="u-menuarrow"></div></td></tr></table>');
					jQuery(a).addClass('u-menuvitemparent').html('<div class="u-menuarrow"></div>'+txt);
					jQuery(a).bind("mouseover",{hl:hl,item:i,obj:o},_uMENU._onitemmouseover).bind("mouseout",{hl:hl,item:i,obj:o},_uMENU._onitemmouseout);
					jQuery(a).bind("mousedown",{child:act,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(el[2].action) jQuery(a).bind("click",{act:el[2].action,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(actl || actr) jQuery(a).bind("mousedown",{actl:actl,actr:actr,obj:o,item:i,itemobj:el},_uMENU._onitemmousedown);
				}
			}
		} else { //horiz
			jQuery(a).css("float","left");
			if(txt=='sep') {
				a.className='u-menuhsep';
			} else {
				a.className='u-menuhitem';
				if(!act || act.constructor!=_uMENU) {
					jQuery(a).html(txt);
					if(hl) jQuery(a).bind("mouseover",{hl:hl,item:i,obj:o},_uMENU._onitemmouseover).bind("mouseout",{hl:hl,item:i,obj:o},_uMENU._onitemmouseout);
					if(act) jQuery(a).bind("click",{act:act,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(actl || actr) jQuery(a).bind("mousedown",{actl:actl,actr:actr,obj:o,item:i,itemobj:el},_uMENU._onitemmousedown);
				} else {
					jQuery(a).addClass('u-menuhitemparent').html(txt);
					jQuery(a).bind("mouseover",{hl:hl,item:i,obj:o},_uMENU._onitemmouseover).bind("mouseout",{hl:hl,item:i,obj:o},_uMENU._onitemmouseout);
					jQuery(a).bind("mousedown",{child:act,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(el[2].action) jQuery(a).bind("click",{act:el[2].action,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(actl || actr) jQuery(a).bind("mousedown",{actl:actl,actr:actr,obj:o,item:i,itemobj:el},_uMENU._onitemmousedown);
				}
			}
		}
		if(hl) jQuery(a).find("*").andSelf().filter('[nodeType=1]').attr("unselectable","on");
		o.elems[i]=el;
		o.parts.elems[i]=a;
		if(mark) o.parts.marks[i]=jQuery(a).find('.u-menumark')[0];
		if(o.props.horiz && (o.props.rtl || window._rtl))
			o.parts.content.insertBefore(a,o.parts.content.firstChild);
			else
			o.parts.content.appendChild(a);
	},
	calc_size: function(o) {
		var w=0,h=0,hm=0,prevm=0;
		if(!o.props.horiz) {
			for(var i=0;i<o.parts.elems.length;i++) {
				w=Math.max(w,Math.max(o.parts.elems[i].offsetWidth,o.parts.elems[i].scrollWidth));
				hm+=Math.max(prevm,parseInt('0'+jQuery(o.parts.elems[i]).css('margin-top')));
				prevm=parseInt('0'+jQuery(o.parts.elems[i]).css('margin-bottom'));
				h+=o.parts.elems[i].offsetHeight;
			}
			h+=hm+prevm;
		} else {  //horiz
			for(var i=0;i<o.parts.elems.length;i++) {
				w+=Math.max(o.parts.elems[i].offsetWidth,o.parts.elems[i].scrollWidth);
				h=Math.max(h,o.parts.elems[i].offsetHeight);
			}
		}
		return {w:w,h:h};
	},
	_onitemmouseover: function(e) {
		jQuery(this).addClass("u-menuitemhl");
	},
	_onitemmouseout: function(e) {
		jQuery(this).removeClass("u-menuitemhl");
	}
    }
};
_uMENU._onitemmouseover=function(e) {
		var d=e.data;
		if(d.hl) d.obj.design._onitemmouseover.apply(this,[e]);
		if(d.obj.hidetimer) clearTimeout(d.obj.hidetimer); d.obj.hidetimer=null;
		if(d.item>=0)if(!d.obj.props.horiz || d.obj.have_active)d.obj.schedule_childopen(d.item);
};
_uMENU._onitemmouseout=function(e) {
		var d=e.data;
		if(d.hl) d.obj.design._onitemmouseout.apply(this,[e]);
		d.obj.reset_childopen();
};
_uMENU._onitemclick=function(e) {
		var d=e.data,act=d.itemobj[1] || d.itemobj[2].action || d.obj.props.onitem;
		if(!d.child && act) {
			if(!d.obj.props.static)d.obj.hide(true);else d.obj.hidechildren();
			if(act.constructor==Function) {
				act.apply(d.itemobj[2].thispar || d.obj.props.thispar,[d.item,d.obj,d.itemobj[2].id,d.itemobj[2]]);
			}
			else if(act=='a') {
				var l=null;
			    if(this==e.target || e.target.tagName.toLowerCase()!='a') {
					if(this!=e.target) { //check that we do not have tag-A parent
						var c1=jQuery(e.target).find('*').andSelf(),c2=jQuery(this).find('*').not(c1);
						if(c2.filter("A").length==0) l=jQuery(this).find("a")[0];
							else l=null;
					} else l=jQuery(this).find("a")[0];
					if(l) {
						this.target=l.target;
						this.href=l.href;
						if(l.onclick) return l.onclick();
					}
				}
				if(!l){
					this.removeAttribute('href');
				}
			}
			return;
		}
		if(!d.child) return;
		_uMENU.ignoreclick=d.child;
		d.obj.reset_childopen();
		d.obj.hidechildren(d.child);
		if(d.child.state.visible) d.child.hide();
			else d.obj.childopen(d.item,d.itemobj[2]);
};
_uMENU._onitemmousedown=function(e) {
		var d=e.data,actl=d.actl || d.obj.props.onldown,actr=d.actr || d.obj.props.onrdown;
		if(e.which==1 && e.ctrlKey) e.which=3;
		if(e.which==1 && actl) {
			_uWnd.globalmousedown();
			actl.apply(d.itemobj[2].thispar || d.obj.props.thispar,[d.item,d.obj,d.itemobj[2].id,d.itemobj[2]]);
			e.stopPropagation();
		} else if(e.which==3 && actr) {
			actr.apply(d.itemobj[2].thispar || d.obj.props.thispar,[d.item,d.obj,d.itemobj[2].id,d.itemobj[2]]);
			_uWnd.globalmousedown();
			e.preventDefault();
			e.stopPropagation();
		}
};
//hides all non-static menus which are visible except for 'exc' and its parents
_uMENU.hideallmenus=function() { //optional exception
	var i,m,ig;
loop:
	for(i=0;i<_uMENU.all.length;i++) {
		m=_uMENU.all[i];
		if(!m || !m.state.visible || m.props.static) continue;
		ig=_uMENU.ignoreclick;
		while(ig) {
			if(ig==m) continue loop;
			ig=ig.pos.parent;
		}
		m.hide();
	}
	if(_uMENU.ignoreclick)setTimeout("_uMENU.ignoreclick=null;",10);
};
_uMENU._onmenumousedown=function(e) {
	if(!_uMENU.ignoreclick)_uMENU.ignoreclick=e.data;
//	e.stopPropagation();
};
_uMENU.prototype={
	shadow_init:function() {
    	this.sh=this.design.shadow_init(this.top);
	},
	_resizeSh:function() {
	    if(this.sh)this.design.shadow_resize(this.sh,this.width,this.height);
	},
	moveTo:function(x,y) {
		with(this) {
			jQuery(top).css("left",x+'px').css("top",y+'px');
		    xpos=x;
    		ypos=y;
  		}
	},
	resizeTo:function(w,h) {
		with(this) {
			if(props.width==0) jQuery(menu).css("width",w+'px');
				else if(props.width!='auto') jQuery(menu).css("width",props.width);
				else jQuery(menu).css("width",'auto');
			if(props.horiz) {
				jQuery(menu).css("height",h+'px');
	    		jQuery(parts.content).css("width",(w-decor.w)+'px').css("height",(h-decor.h)+'px');
			} else {
//			    jQuery(menu).css("width",w+'px');//.css("height",h+'px');
    			jQuery(parts.content).css("width",(w-decor.w)+'px');//.css("height",(h-decor.h)+'px');
			}
//   		jQuery(parts.upper).css("width",w+'px');
//    		jQuery(parts.upper.firstChild.firstChild).css("width",w+'px');
		    if(frame) jQuery(frame).css("width",w+'px').css("height",h+'px');
		    width=w;
		    height=h;
		    _resizeSh();
		}
	},
	init1: function(nocalcsize) {
		with(this) {
    		decor.w=50-parts.content.offsetWidth;
    		decor.h=menu.offsetHeight-(props.horiz ? 10 : 50);
			state.init=true;
//alert('in init of '+this.idx);
			_initsubmenus();
			if(add_elems)appendItems(null,0,nocalcsize);
				else {
				if(pend_show)show(pend_show);
//				if(oninit && props.wnd)oninit.apply(props.wnd);
				}
  		}
	},
	show: function(pos) {
		if(this.state.destroyed) return;
		if(!this.state.init){this.pend_show=pos || {};return;}
		this.pend_show=null;
		this.pos=jQuery.extend(this.pos,pos || {});
	    if(!this.pos.parent) this.zpos=_uMENU.defz;
    		else this.zpos=this.pos.parent.zpos+5;
		jQuery(this.top).css("z-index",this.zpos);
		if(this.pos.pos || this.pos.alignObj) {
			var a,pos,ow,oh;
//			this.moveTo(this.pos.pos.x,this.pos.pos.y);
			if(this.pos.alignObj) {
				a=this.pos.alignObj;
				pos=jQuery(a).offset();
				ow=a.offsetWidth;
				oh=a.offsetHeight;
			} else {
				pos={left:this.pos.pos.x,top:this.pos.pos.y};
				ow=oh=0;
			}
		        var ppos,x,y,
		        	d=_uWnd.getdims(),ww=d.clientW,wh=d.clientH,wl=d.clientLeft,wt=d.clientTop,
		        	al=this.pos.align || 'd';
				if(this.props.wnd && this.props.wnd.desktop) {
					d=this.props.wnd.desktop;
					ww=d.width;
					wh=d.height;
					wl=0;
					wt=0;
				}
				if(this.props.rtl || window._rtl) x=pos.left+ow+this.pos.dx-this.width;
					else
					x=pos.left+this.pos.dx;
				y=pos.top+this.pos.dy;

				if(al=='r' || al=='R') x=pos.left+ow+this.pos.dx;
					else if(al=='l' || al=='L') x=pos.left-this.width+this.pos.dx;
					else if(al=='d' || al=='D') y=pos.top+oh+this.pos.dy;
					else if(al=='u' || al=='U') y=pos.top-this.height+this.pos.dy;
				if(x-wl+this.width>ww-3-this.design.sh_sz[0] || x-wl<1)
					if(al=='R' || al=='U') x=pos.left-this.width-this.pos.dx;
						else if(al=='L') x=pos.left+ow-this.pos.dx;
				if(x-wl+this.width>ww-3) x=ww-3-this.design.sh_sz[0]-this.width+wl;
				if(x-wl<1) x=1+wl;

				if(y-wt+this.height>wh-3-this.design.sh_sz[1] || y-wt<1)
					if(al=='D') y=pos.top-this.height-this.pos.dy;
						else if(al=='U') y=pos.top+oh-this.pos.dy;
				if(y-wt+this.height>wh-3) y=wh-3-this.design.sh_sz[1]-this.height+wt;
				if(y-wt<1) y=1+wt;

		        if(this.props.parentnode){
		        	ppos=jQuery(this.props.parentnode).offset();
		        	x-=ppos.left;
		        	y-=ppos.top;
		        }
        		this.moveTo(x,y);
			}
    	if(this.props.onshow) this.props.onshow.apply(this.props.thispar,[this,this.idx]);
		//check marks
		if(this.props.withmarks) {
			for(var i=0;i<this.elems.length;i++) {
				var c=this.elems[i];
				if(c && c[2] && this.parts.marks[i]) {
					if(!c[2].mark) this.parts.marks[i].style.display='none';
						else {
							var m=c[2].marktext || this.props.withmarks;
							if(typeof m=='object' && m.constructr!=String) m=m[c[2].mark];
							this.parts.marks[i].innerHTML=String(m);
							this.parts.marks[i].style.display='block';
						}
				}
			}
		}

		jQuery(this.top).show();
		this.state.visible=true;
		if(this.pos.parent) this.pos.parent.have_active=this;
		if(this.props.hidetimer>0) this.hidetimer=setTimeout("var m=_uMENU.all["+this.idx+"];if(m)m.hide();",this.props.hidetimer);
	},
	hidechildren: function(except) {
		if(this.state.destroyed) return;
		var e=this.elems;
		for(var i=0;i<e.length;i++)
			if(e[i] && e[i].constructor==Array && e[i][1] && e[i][1].constructor==_uMENU) if(e[i][1]!=except) e[i][1].hide();
	},
	hide: function(withpar) {
		if(this.state.destroyed) return;
		if(!this.state.visible) return;
		jQuery(this.top).hide();
		this.state.visible=false;
		if(this.hidetimer) clearTimeout(this.hidetimer); this.hidetimer=null;

		this.pend_show=null;
		this.hidechildren();
		if(this.pos.parent && this.pos.parent.have_active==this) this.pos.parent.have_active=null;
    	if(this.props.onhide) this.props.onhide.apply(this.props.thispar,[this,this.idx]);

		if(withpar) { //hide all non-static parents
			var p=this.pos.parent;
			while(p && !p.props.static && p!=this) {p.hide(false);p=p.pos.parent;}
		}
	},
	childopen: function(i) {
		if(this.state.destroyed) return;
		if(this.childtimer) clearTimeout(this.childtimer);
		this.childtimer=null;
		var h=this.parts.elems[i];
		var c=this.elems[i];
		if(!c) return;
		c=c[1];
		if(!c || c.constructor!=_uMENU) {
			if(this.props.horiz) {this.hidechildren(c);this.have_active=this;}
			return;
		}
		this.hidechildren(c);
		c.show({dx:(this.props.horiz ? 0 : -3 * (this.props.rtl || window._rtl ? -1 : 1)),alignObj:h,align:(this.props.horiz ? 'D' : (this.props.rtl || window._rtl ? 'L' : 'R')),parent:this});
	},
	schedule_childopen: function(i) {
		if(this.state.destroyed) return;
		if(this.childtimer) clearTimeout(this.childtimer);
		this.childtimer=setTimeout("var m=_uMENU.all["+this.idx+"];if(m)m.childopen("+i+");",100);
	},
	reset_childopen: function() {
		if(this.childtimer) clearTimeout(this.childtimer);
	},
	_initsubmenus: function() {
	  with(this) {
		for(var i=0;i<toinit.length;i++) {toinit[i].init1(true);tocalcsize[tocalcsize.length]=toinit[i];}
		toinit.length=0;
	  }
	},
	_calcsizesubmenus: function() {
	  with(this) {
		for(var i=0;i<tocalcsize.length;i++) tocalcsize[i]._setsize();
		tocalcsize.length=0;
	  }
	},
	createsubmenus: function() {
		var i,was=false;
		for(i=0;i<this.add_elems.length;i++) {
			var el=this.add_elems[i];
			var n=el.length;
			for(var j=0;j<n;j++) {
				if(el[j] && el[j].constructor==Array && el[j][1] && el[j][1].constructor==Array) { //create submenu
					var o={},pos,opts,s;
					if(el[j][2] && (typeof el[j][2])=='object') o=el[j][2];
						else if((typeof el[j][2])=='number') o={hl:el[j][2]};
						else if((typeof el[j][2])=='string') o={id:el[j][2]};
					el[j][2]=o;
					pos=jQuery.extend({
						parent:this,
						dx:this.props.horiz ? this.pos.childdx : 0,
						dy:this.props.horiz ? this.pos.childdy : 0
						},o.pos || {});
					opts=jQuery.extend({
						shadow:this.props.shadow,
						rtl:this.props.rtl ? 1 : 0,
						parentnode:this.props.wnd ? this.props.wnd.top : this.props.parentnode,
						wnd:this.props.wnd,
						onitem: this.props.onitem,
						thispar: this.props.thispar
						},o.opts || {});
					s=new _uMENU('',pos,opts,el[j][1],true);
					el[j][1]=s;
					this.toinit[this.toinit.length]=s;
					was=true;
				}
			}
		}
		return was;
	},
	indexById: function(id) { //find index by string id
		id=String(id);
		for(var i=0;i<this.elems.length;i++)
			if(this.elems[i][2].id==id) return i;
		return -1;
	},
	removeItems: function(idx,nodestroy,norecalc) {
		var i,p,e;
		if(idx==undefined || idx==null) { //remove all
			idx=[];
			for(i=0;i<this.elems.length;i++)idx[i]=this.elems.length-1-i;
		} else if(idx.constructor!=Array) idx=[idx];
		for(i=0;i<idx.length;i++)
			if(idx[i]==undefined || idx[i]==null || idx[i].constructor!=Number) idx[i]=this.indexById(idx[i]);
		idx.sort(function(a,b){return b-a;});
		p=-1;
		for(i=0;i<idx.length;i++) {
			if(idx[i]==p || idx[i]<0 || idx[i]>=this.elems.length) continue;
			e=this.elems[idx[i]];
			if(!nodestroy && e && e.constructor==Array && e[1] && e[1].constructor==_uMENU) e[1].destroy();
			this.elems.splice(idx[i],1);
			this.parts.elems[idx[i]].parentNode.removeChild(this.parts.elems[idx[i]]);
			this.parts.elems.splice(idx[i],1);
			p=idx[i];
		}
		if(!norecalc) this.appendItems(null,0);
	},
	appendItems: function(el,idx,nocalcsize) {
		if(this.state.destroyed) return;
		if(el && el.constructor==Array && el.length>0)this.add_elems[this.add_elems.length]=el;
		if(!this.state.init)return;
//alert('in appendItems of '+this.idx);
		if(this.createsubmenus()) { //
			setTimeout("var m=_uMENU.all["+this.idx+"];if(m){m._initsubmenus();m.appendItems(null,0,"+nocalcsize+");}",10);
			return;
		}

		if(this.appendtimer)clearTimeout(this.appendtimer);
		this.appendtimer=null;
   		jQuery(this.top).css("visibility",'hidden').css("display",'block');
		if(this.props.horiz) {
			if(!this.props.noabs) jQuery(this.menu).css("width","2100px").css("height","auto");
				else jQuery(this.menu).css("width",this.props.width==0 ? "auto" : this.props.width=='auto' ? 'auto' : this.props.width+"px");
   			jQuery(this.parts.content).css("width","2000px").css("height","auto");
   		} else {
	   		jQuery(this.menu).css("width","auto").css("height","auto");
   			jQuery(this.parts.content).css("width",jQuery.browser.msie ? "50px" : "auto").css("height","auto");
   		}
		var i;
		for(i=0;i<this.add_elems.length;i++) {
			el=this.add_elems[i];
			var n=el.length;
			for(var j=0;j<n;j++) {
				if(!el[j] || el[j].constructor!=Array) el[j]=[''+el[j]];
				var o={};
				if(el[j][2] && (typeof el[j][2])=='object') o=el[j][2];
					else if((typeof el[j][2])=='number') o={hl:el[j][2]};
					else if((typeof el[j][2])=='string') o={id:el[j][2]};
				el[j][2]=o;
				this.design.append_item(this,el[j],this.props.highlight);
			}
		}
		this.add_elems.splice(0,i);
//		if(onfinish && this.props.wnd)this.onsetsize=onfinish;
		if(!nocalcsize)this.appendtimer=setTimeout("var m=_uMENU.all["+this.idx+"];if(m){m.appendtimer=null;m._setsize();}",10);
	},
	_setsize: function() {
		var d=this.design.calc_size(this);
		this.resizeTo(d.w+this.decor.w,d.h+this.decor.h);

//alert('in setsize of '+this.idx);
		this._calcsizesubmenus();

   		jQuery(this.top).css("display",'none').css("visibility",'visible');
		if(this.pend_show || this.state.visible)this.show(this.pend_show);
//	alert('setsize');
		if(this.onsetsize) {
			var a=this.onsetsize;
			this.onsetsize=null;
			if(this.props.wnd)a.apply(this.props.wnd);
		}
	},
	destroy: function() {
		if(this.state.destroyed) return;
	    this.top.parentNode.removeChild(this.top);
	    _uMENU.all[this.idx]=null;
	    this.state.destroyed=true;
    	if(this.props.ondestroy) this.props.ondestroy.apply(this.props.thispar,[this,this.idx]);
	}
};
//vals - [[val1,icon1,issel1,text11,text12,...],[val2,icon2,issel2,text21,text22,...]]
//cols - number of text columns (0 if valX is used as displayed text), place for icons is reserved always
function _uComboBox(name,inputId,opts,cols,vals) {
	this.constructor=_uComboBox;
	this.name=name;
	this.obj=document.getElementById(inputId);
	if(!this.obj) return null;
	this.props=jQuery.extend({
//		parentnode: null, //parent node for drop-down list
		design: 'std',
		readonly: false,
		noicons: -1,
		deficon: null,
//		width: 'auto',
//		height: 'auto',
		maxlistheight: 'auto',
		colwidth: null,
//		hidden: 0,
//		onshow: null,
//		onhide: null,
//		ondestroy: null,
		onchange: null,
//		wnd:null,
		rtl:0
	},opts || {});
	this.textvals=cols > 0 ? cols : 0;
	this.tablecols=cols<=0 ? 1 : cols;
	this.colwidth=this.props.colwidth || [];
	this.destroyed=false;
    this.design=this.props.design && _uComboBox.designs[this.props.design] ? _uComboBox.designs[this.props.design] : _uComboBox.designs['std'];
    this.idx=_uComboBox.nextidx++;
    _uComboBox.all[this.idx]=this;
//    if(this.props.width=='auto') {
//    	this.width=this.obj.offsetWidth || parseInt(this.obj.style.width);
//    	if(!this.width>0) this.width=100;
//    } else this.width=this.props.width;
//    if(this.props.height=='auto') {
//    	this.height=this.obj.offsetHeight || parseInt(this.obj.style.height);
//    	if(!this.height>0) this.height=100;
//    } else this.height=this.props.height;
//	this.zpos=this.props.wnd ? 5 : _uComboBox.defz;
	this.data=vals || [];
	var defIdx=-1;
	for(var i=0;i<this.data.length;i++) if(this.data[i][2]) {defIdx=i;break;}
	this.userInput=this.prevInput=this.obj.value;
	if(this.props.readonly) {
		this.obj.readOnly=true;
		this.valobj=jQuery('<input type="hidden" name="'+this.obj.name+'" value="">')[0];
		this.obj.removeAttribute('name');
		if(this.obj.form) this.obj.form.appendChild(this.valobj);
		if(defIdx<0 || defIdx>=this.data.length) defIdx=0;
	} else {
		this.obj.readOnly=false;
		this.valobj=this.obj; //object which holds form value
		if(defIdx<0 || defIdx>=this.data.length) defIdx=-1;
	}
	this.selected=this.userIdx=defIdx;
	this.changetimer=null;


	this.haveicons=this.props.noicons>0;
	if(this.props.noicons<0) for(var i=0;i<this.data.length;i++) if(this.data[i][1]) {this.haveicons=true;break;}


	this.frame=null;
	this.opened=false;
	this.updated=true;
	this.showtimer=null;
	this.blurtimer=null;
	this.cancelblur=false;
//	var c=document.createElement("div");
//	c.id="_ucombo"+this.idx;
//	this.obj.parentNode.insertBefore(c,this.obj);
	this.combo=null;

	var t=document.createElement("div");
	t.id="_ucombolist"+this.idx;
//	this.combo.appendChild(t);
//	if(!this.props.parentnode) jQuery(jQuery("body")[0]).prepend(t);
//		else this.props.parentnode.appendChild(t);
	this.toplist=t;

   	jQuery(t).css({position:'absolute',zIndex:5,display:'none'});//zIndex:this.zpos,
    if(jQuery.browser.msie && parseFloat(jQuery.browser.version)<7){
		    var html = '<iframe tabindex="-1" '
    		    +'style="display:block; position:absolute; '
			+'filter:Alpha(Opacity=\'0\'); '
			+'width:1px;height:1px;border:0"/>';

	    	this.frame=document.createElement(html);
			t.appendChild(this.frame);
	}

    this.parts=this.design.combo_init(this);

    jQuery(this.obj).attr("autocomplete", "off")
	.bind("focus",this,_uComboBox._onobjfocus)
	.bind("blur",this,_uComboBox._onobjblur)
	.bind("beforedeactivate",this,_uComboBox._onobjdeact)
	.bind("keydown",this,function(e) {return e.data.onkeydown(e);})
	.bind("keyup",this,function(e) {return e.data.onkeyup(e);});

	jQuery(this.combo).bind("mousedown",this,_uComboBox._oncombomousedown);
	jQuery(this.toplist).bind("mousedown",this,_uComboBox._onlistmousedown);
    for(var i=0;i<this.data.length;i++) this.appendItem(this.data[i]);
	if(!_uComboBox.globalset) {
		_uComboBox.globalset=true;
	    jQuery(document).bind("mousedown",_uComboBox.hideall);
	    jQuery(window).bind("resize",_uComboBox.hideall);
	}
	if(defIdx>=0) this.select(defIdx,false,true);
//	setTimeout("var m=_uComboBox.all["+this.idx+"];if(m)m.showlist();",10);
//	this.showlist();
//	if(!this.props.hidden) this.show();
//	if(!noinit)setTimeout("var m=_uMENU.all["+this.idx+"];if(m)m.init1();",10);
}


_uComboBox.all=[];
_uComboBox.nextidx=0;
_uComboBox.defz=20015;
_uComboBox.globalset=false;
_uComboBox.ignoreclick=null;

_uComboBox.getbyname=function(name) {
    var a=this.all;
    for(var i=0;i<a.length;i++) if(a[i] && a[i].name==name) return a[i];
    return null;
};
_uComboBox.hideall=function() {
    var a=_uComboBox.all;
    for(var i=0;i<a.length;i++) if(a[i] && !a[i].destroyed && _uComboBox.ignoreclick!=a[i]) a[i].hidelist();
	if(_uComboBox.ignoreclick)setTimeout("_uComboBox.ignoreclick=null;",10);
};
_uComboBox.designs={
    std: {
	combo_init: function(o) {
	    var p={};
		o.combo=jQuery('<table id="_ucombo'+o.idx+'" style="position:relative" cellspacing="0" cellpadding="0" border="0" class="x-unselectable u-combo" align="left">'
				+'<tr><td class="u-comboeditcell"></td><td class="u-combobutcell"><div class="u-combobut"></td></tr>'
				+'</table>')[0];
		o.obj.parentNode.insertBefore(o.combo,o.obj);
		o.obj.parentNode.insertBefore(o.toplist,o.obj);
//		jQuery(o.combo).attr("class","x-unselectable u-combo").css({position:'relative'}).prepend('<img border="0" class="u-combobut" src="http://src.ucoz.net/img/1px.gif">');
		p.editcell=jQuery(o.combo).find(".u-comboeditcell")[0];
		p.button=jQuery(o.combo).find(".u-combobut")[0];
		p.butcell=jQuery(o.combo).find(".u-combobutcell")[0];
		p.editcell.appendChild(o.obj);
		jQuery(o.obj).attr("class","x-selectable u-comboedit"+(o.haveicons ? " u-comboeditimg" : "")+" "+jQuery(o.obj).attr("class"));
//		if(jQuery.browser.msie) jQuery(o.obj).css({marginTop:'-1px',marginBottom:'-1px'});

	    jQuery(o.toplist).append('<div class="u-combolist"><div style="zoom:1"><table border="0" cellspacing="0" class="x-unselectable u-combocont" width="100%"></table></div></div>');
		p.list=jQuery(o.toplist).find(".u-combolist")[0];
		p.content=jQuery(o.toplist).find(".u-combocont")[0];

		if(!o.props.readonly) jQuery(p.button).bind("mousedown",o,_uComboBox._onbutclick);
			else {
				jQuery(o.obj).bind("mousedown",function(e){e.preventDefault();return 0;});
			}
		jQuery(p.button).bind("mouseover",o.design._onbutmouseover).bind("mouseout",o.design._onbutmouseout);

		p.items=[];
		jQuery(o.toplist).find("div,span,table").andSelf().attr("unselectable","on");
	    return p;
	},
	append_item: function(o,el) {
		var row,cell,t=o.parts.content,i=t.rows.length,txt;
		row=o.parts.items[i]=t.insertRow(i);
		jQuery(row).attr("class","u-comborow").bind("mouseover",{item:i,obj:o},_uComboBox._onitemmouseover).bind("mouseout",{item:i,obj:o},_uComboBox._onitemmouseout)
			.bind("click",{obj:o,item:i},_uComboBox._onitemclick);
		for(var j=0;j<o.tablecols;j++) {
			cell=row.insertCell(j);
			txt= j+3<o.data[i].length ? o.data[i][j+3] : (j==0 ? o.data[i][0] : '&nbsp;');
			if(j==0 && o.data[i][1]) txt='<img class="u-comborowicon" border="0" src="'+o.data[i][1]+'">'+txt;
			jQuery(cell).attr("class","u-combocell"+j).html(txt);
			if(o.colwidth[j]) jQuery(cell).attr("width",o.colwidth[j]);
		}
		jQuery(row).find("*").andSelf().attr("unselectable","on");
	},
	calc_size: function(o) {
		var w=0,h=0;
		if(!o.props.horiz) {
			for(var i=0;i<o.parts.elems.length;i++) {
				w=Math.max(w,Math.max(o.parts.elems[i].offsetWidth,o.parts.elems[i].scrollWidth));
				h+=o.parts.elems[i].offsetHeight;
			}
		} else {  //horiz
			for(var i=0;i<o.parts.elems.length;i++) {
				w+=Math.max(o.parts.elems[i].offsetWidth,o.parts.elems[i].scrollWidth);
				h=Math.max(h,o.parts.elems[i].offsetHeight);
			}
		}
		return {w:w,h:h};
	},
	_onitemmouseover: function(e) {
		jQuery(this).addClass("u-comborowhl");
	},
	_onitemmouseout: function(e) {
		jQuery(this).removeClass("u-comborowhl");
	},
	_onbutmouseover: function() {
		jQuery(this).addClass("u-combobuthl");
	},
	_onbutmouseout: function() {
		jQuery(this).removeClass("u-combobuthl");
	},
	_onlistopen: function(o) {
		jQuery(o.combo).addClass("u-comboopen");
	},
	_onlisthide: function(o) {
		jQuery(o.combo).removeClass("u-comboopen");
	},
	_onfocus: function(o,e) {
		jQuery(o.combo).addClass("u-combofocus");
	},
	_onblur: function(o,e) {
		jQuery(o.combo).removeClass("u-combofocus");
	},
	_select: function(o,i) {
		jQuery(o.parts.items[i]).addClass("u-comborowsel");
	},
	_deselect: function(o,i) {
		jQuery(o.parts.items[i]).removeClass("u-comborowsel");
	},
	seticon: function(o,icon) {
		if(icon) jQuery(o.obj).css("background-image","url("+icon+")");
			else jQuery(o.obj).css("background-image",o.props.deficon ? "url("+o.props.deficon+")" : "none")
	}
    }
};

_uComboBox._onitemmouseover=function(e) {
		var d=e.data;
		d.obj.design._onitemmouseover.apply(this,[e]);
};
_uComboBox._onitemmouseout=function(e) {
		var d=e.data;
		d.obj.design._onitemmouseout.apply(this,[e]);
};
_uComboBox._onitemclick=function(e) {
		var d=e.data;
		d.obj.select(d.item);
		d.obj.hidelist();
		d.obj.obj.focus();
		e.stopPropagation();
		e.preventDefault();
};
_uComboBox._onbutclick=function(e) {
		var o=e.data;
//		_uWnd.globalmousedown();
		if(o.opened) o.hidelist(); else o.showlist();
//		_uComboBox.ignoreclick=e.data;
		o.obj.focus();
		if(jQuery.browser.msie && !e.data.cancelblur) {
			e.data.cancelblur=true;
			setTimeout("var c=_uComboBox.all["+e.data.idx+"];if(c)c.cancelblur=false;",10);
		}
//		e.stopPropagation();
		e.preventDefault();
};
_uComboBox._onlistmousedown=function(e) {
	_uComboBox.ignoreclick=e.data;
	e.data.obj.focus();
	if(jQuery.browser.msie && !e.data.cancelblur) {
		e.data.cancelblur=true;
		setTimeout("var c=_uComboBox.all["+e.data.idx+"];if(c)c.cancelblur=false;",10);
	}
//	e.stopPropagation();
	e.preventDefault();
};
_uComboBox._oncombomousedown=function(e) {
	_uComboBox.ignoreclick=e.data;
	if(e.which!=1) return;
	var o=e.data;
	if(o.props.readonly) if(o.opened) o.hidelist(); else o.showlist();
	o.obj.focus();
	if(jQuery.browser.msie && !o.cancelblur) {
		o.cancelblur=true;
		setTimeout("var c=_uComboBox.all["+o.idx+"];if(c)c.cancelblur=false;",10);
	}
//	e.stopPropagation();
	if(e.target!=o.obj) e.preventDefault();
};
_uComboBox._onobjfocus=function(e) {
	var o=e.data;
	if(o.blurtimer) clearTimeout(o.blurtimer);
	o.blurtimer=null;
	o.design._onfocus(o,e);
};
_uComboBox._onobjblur=function(e) {
	e.data.onblur();
};
_uComboBox._onobjdeact=function(e) {
	var o=e.data;
	if(o.cancelblur) e.preventDefault();
};

_uComboBox.isUpKey=function (code) {
    return code==38 || code == 63232;
};
_uComboBox.isDownKey=function (code) {
    return code==40 || code == 63233;
};

_uComboBox.prototype={
	_setvalue: function(i) {
	  with(this) {
		if(i>=0 && i<data.length) {
			valobj.value=prevInput=data[i][0];
			if(props.readonly) obj.value=data[i].length>3 ? data[i][3] : data[i][0];
			if(haveicons) design.seticon(this,data[i][1]);
		} else {
			if(props.readonly) {valobj.value='';obj.value=userInput;}
				else {valobj.value=prevInput=userInput;}
			if(haveicons) this.design.seticon(this,null);
		}
	  }
	},
	_selectitem: function(i) {
	  with(this) {
		if(selected>=0 && selected<data.length) {
			design._deselect(this,selected);
			selected=-1;
		}
		if(i>=0 && i<data.length) {
			design._select(this,i);
			selected=i;
		}
	  }
	},
	setvalue: function (v) {
	  with(this) {
	  	var ch=false;
		if(changetimer) clearTimeout(changetimer);
		if(props.readonly) return;
		if(valobj.value!=v) ch=true;
		valobj.value=prevInput=userInput=v;
		if(selected!=-1) ch=true;
		_selectitem(-1);
		userIdx=-1;
		if(haveicons) this.design.seticon(this,null);
		if(props.onchange && ch) props.onchange.apply(this,[selected,v]);
	  }
	},
	select: function (i,soft) { //
	  with(this) {
		var ch=false;
		if(changetimer) clearTimeout(changetimer);
		changetimer=null;
	  	_selectitem(i);
		_setvalue(selected);
		if(!soft) {
			if(selected!=userIdx) ch=true;
			userIdx=selected;
			if(props.onchange && ch) props.onchange.apply(this,[selected,valobj.value]);
		}
	  }
	},
	onblur: function (e) {
		if(this.blurtimer) clearTimeout(this.blurtimer);
		this.blurtimer=setTimeout("var c=_uComboBox.all["+this.idx+"];if(c)c._onblur2();",10);
	},
	_onblur2: function (e) {
		this.blurtimer=null;
		this.design._onblur(this,e);
	},
	onkeydown: function (e) {
	  var i;
	  with(this) {
    	var c=e.keyCode;
    	if(c==27 && opened) {
			select(userIdx,true);
			hidelist();
			return false;
    	}
    	if(data.length==0) return;
	    if(c==13) {
	    	select(selected);
			hidelist();
			obj.focus();
			e.preventDefault();
			e.stopPropagation();
			return false;
	    }
		if(c==9) {
			if(changetimer) select(selected);
			return;
		}
	    if(_uComboBox.isDownKey(c) || _uComboBox.isUpKey(c)) {
			i=selected+(_uComboBox.isDownKey(c) ? 1 : -1);
			if(props.readonly) {
	    		if(i>=data.length) i=0;
					else if(i<0) i=data.length-1;
			} else {
    			if(i>=data.length) i=-1;
					else if(i<-1) i=data.length-1;
			}
			select(i,true); //select clears changetimer
			if(!opened) changetimer=setTimeout("var c=_uComboBox.all["+this.idx+"];if(c)c.select("+i+");",500);
			return false;
    	}
  	  }
	},
	onkeyup: function (e) {
  	  with(this) {
    	if(props.readonly || obj.value==prevInput) return;
		if(changetimer) clearTimeout(changetimer);
    	prevInput=userInput=obj.value;
		_selectitem(-1);
		userIdx=-1;
		if(haveicons) this.design.seticon(this,null);
		if(props.onchange) props.onchange.apply(this,[-1,obj.value]);
  	  }
	},
	appendItem: function(elem) { //0 - id, 1 - optional icon, 2... - text labels
		this.design.append_item(this,elem);
		this.updated=true;
	},
	hidelist: function() {
	    this.toplist.style.display='none';
	    this.opened=false;
		this.design._onlisthide(this);
	},
	showlist: function () {
    	var w=this.combo.offsetWidth;
		jQuery(this.toplist).css({left:this.combo.offsetLeft+'px',top:this.combo.offsetTop+this.combo.offsetHeight+'px',width:w+'px'});
	    if(this.frame) jQuery(this.frame).css({width:w+'px'});
		if(this.updated) {
			jQuery(this.parts.list).css({height:'auto',overflow:'hidden'});
			jQuery(this.toplist).css({visibility:'hidden'}).css({display:'block'});
			if(this.showtimer) clearTimeout(this.showtimer);
			this.showtimer=setTimeout("var c=_uComboBox.all["+this.idx+"];if(c)c._showlist();",10);
		} else {
		    this.toplist.style.display='block';
		}
		this.design._onlistopen(this);
		this.opened=true;
	    this.updated=false;
	},
	_showlist:function(){
		this.showtimer=null;
		var o=this.parts.list,h,maxh,pos,d=_uWnd.getdims();
		h=Math.max(o.scrollHeight,o.offsetHeight);
		pos=jQuery(this.toplist).offset();
		if(this.props.maxlistheight>0) maxh=Math.max(50,Math.min(this.props.maxlistheight,d.clientH-pos.top));
			else maxh=Math.max(50,d.clientH-pos.top);
		if(h>maxh) {
			jQuery(this.parts.list).css({height:maxh+'px',overflow:'auto'});
			h=maxh;
		}
	    if(this.frame) jQuery(this.frame).css({height:h+'px'});

		jQuery(this.toplist).css({visibility:'visible'});
	}
};

//vals in form:
//{'word1':[['word11',col2],['word12',col2]],'word2':[['word21',col2],['word22',col2]]}

//function _uSuggestList(editId,cachegroup,tblClass,normalclass,highclass,minlength,url,vals) {
function _uSuggestList(name,inputId,opts,vals) { //inputId can be ID or object
	this.constructor=_uSuggestList;
	this.name=name;
	this.obj=typeof inputId=='string' ? document.getElementById(inputId) : inputId;
	if(!this.obj) return null;
	this.props=jQuery.extend({
		design: 'std',
		maxlistheight: 'auto',
		colwidth: null,
		cachegroup: 'def',
		minlen: 2,
		url: null,
		separator: null
//		hidden: 0,
//		onshow: null,
//		onhide: null,
//		ondestroy: null,
//		onchange: null,
//		wnd:null,
//		rtl:0
	},opts || {});
	this.colwidth=this.props.colwidth || [];
//	this.destroyed=false;
    this.design=this.props.design && _uSuggestList.designs[this.props.design] ? _uSuggestList.designs[this.props.design] : _uSuggestList.designs['std'];
    this.idx=_uSuggestList.nextidx++;
    _uSuggestList.all[this.idx]=this;
    this.cacheGroup=this.props.cachegroup;
    if(!this.queryCache[this.cacheGroup]) this.queryCache[this.cacheGroup]=[];
    if(vals) this.queryCache[this.cacheGroup]=vals;

    this.visible=true;
    this.hlIndex=-1; //highlighted item
    this.hlRow=null; //highlighted row
    this.blockMouseOver=false;

    this.userInput=this.obj.value; //saved value
    this.previousInput=this.obj.value; //to track changes
    this.resultInput=""; //value for which we have result if result is not empty
    this.requestedInput=""; //to track value which will be requested remotely
    this.ignoreInput=""; //value which must be ignored
	this.sep_pos=-1;

    this.remoteReqTimer=null;
    this.hideTimer=null;
    this.AJAXretries=0;
    this.AJAXTimer=null;


	this.frame=null;


	var t=document.createElement("div");
	t.id="_usuggest"+this.idx;
	this.top=t;

	var wnd;
	if(wnd=_uWnd.findparent(this.obj)) {
		this.parent=wnd.top;
		this.parent.appendChild(t);
	} else {
		this.parent=this.obj.parentNode;
		this.parent.insertBefore(t,this.obj);

	}

   	jQuery(t).css({position:'absolute',zIndex:5,display:'none',zoom:1});//zIndex:this.zpos,
    if(0 && jQuery.browser.msie && parseFloat(jQuery.browser.version)<7){
		    var html = '<iframe tabindex="-1" '
    		    +'style="display:block; position:absolute;'
			+'filter:Alpha(Opacity=\'100\'); '
			+'width:1px;height:20px;border:0"/>';

	    	this.frame=document.createElement(html);
			t.appendChild(this.frame);
	}

    this.parts=this.design.suggest_init(this);

    jQuery(this.obj).attr("autocomplete", "off").css("position","relative")
//	.bind("focus",this,_uComboBox._onobjfocus)
	.bind("blur",this,function(e) {return e.data.onblur(e);})
//	.bind("beforedeactivate",this,_uComboBox._onobjdeact)
	.bind("keydown",this,function(e) {return e.data.onkeydown(e);})
	.bind("keyup",this,function(e) {return e.data.onkeyup(e);});

//	jQuery(this.combo).bind("mousedown",this,_uComboBox._oncombomousedown);
//	jQuery(this.toplist).bind("mousedown",this,_uComboBox._onlistmousedown);
	if(!_uSuggestList.globalset) {
		_uSuggestList.globalset=true;
	    jQuery(document).bind("mousedown",_uSuggestList.hideall);
	    jQuery(window).bind("resize",_uSuggestList.hideall);
	}


    this.hide();
//    jQuery(window).bind("resize",this,function(e) {return e.data.positionResult();});

    //attach event to parent form
    if(this.obj.form) {
	jQuery(this.obj.form).bind("submit."+this.idx,this,function(e) {return e.data.onsubmitform(e);});
    }
}

_uSuggestList.all=[];
_uSuggestList.nextidx=0;
_uSuggestList.defz=20015;
_uSuggestList.globalset=false;
_uSuggestList.ignoreclick=null;

_uSuggestList.getbyname=function(name) {
    var a=this.all;
    for(var i=0;i<a.length;i++) if(a[i] && a[i].name==name) return a[i];
    return null;
};
_uSuggestList.hideall=function() {
    var a=_uSuggestList.all;
    for(var i=0;i<a.length;i++) if(a[i] && !a[i].destroyed && _uSuggestList.ignoreclick!=a[i]) a[i].hide();
	if(_uSuggestList.ignoreclick)setTimeout("_uSuggestList.ignoreclick=null;",10);
};

_uSuggestList.designs={
	std: {
	suggest_init: function(o) {
	    var p={};
		jQuery(o.obj).attr("class","x-selectable u-suggedit "+jQuery(o.obj).attr("class"));
//		if(jQuery.browser.msie) jQuery(o.obj).css({marginTop:'-1px',marginBottom:'-1px'});

	    jQuery(o.top).append('<div class="u-sugglist" style="zoom:1"><div style="zoom:1"><table border="0" cellspacing="0" class="x-unselectable u-suggcont" width="100%"></table></div></div>');
		p.list=jQuery(o.top).find(".u-sugglist")[0];
		p.content=jQuery(o.top).find(".u-suggcont")[0];
//		p.items=[];
		jQuery(o.top).find("div,span,table").andSelf().attr("unselectable","on");
	    return p;

		},
	append_row: function(o,item,cols,key) {
		var row=o.parts.content.insertRow(-1);
		jQuery(row).bind("mousedown",o,o._onrowmousedown)
	      .bind("mousemove",o,o._onrowmousemove)
	      .bind("mouseover",o,o._onrowmouseover).addClass('u-suggrow').attr("usuggeststr",item[0]);
		var v=String(item[0]);
	    if(v.toLowerCase().substr(0,key.length)==key.toLowerCase()) v='<span class="u-suggmark">'+v.substr(0,key.length)+'</span>'+v.substr(key.length);
		for(var j=0;j<cols;j++) {
		    jQuery(row).append("<td unselectable='on' class='u-suggcell"+j+"'>"+(j==0?v:item[j])+"</td>");
		}
	},
//	_onlistopen: function(o) {
//		jQuery(o.combo).addClass("u-comboopen");
//	},
//	_onlisthide: function(o) {
//		jQuery(o.combo).removeClass("u-comboopen");
//	}
	_select: function(o,row) {
		jQuery(row).addClass("u-suggrowhl");
	},
	_deselect: function(o,row) {
		jQuery(row).removeClass("u-suggrowhl");
	}

	}

};

_uSuggestList.prototype = {
queryCache: [],
onsubmitform: function (e) {
    if(this.visible) {
	if(this.resultInput!="") this.obj.value=this.userInput;
	this.hide();
    }
},
hide: function () {
  with(this) {
    top.style.display='none';
	visible=false;
	if(hlRow) design._deselect(this,hlRow);
	hlRow=null;
	hlIndex=-1;
  }
},
show: function () {
  with(this) {
    if(!visible && numItems()>0) {
	   	var w=obj.offsetWidth,x,y,off,offp;
	   	off=jQuery(obj).offset();
	   	offp=jQuery(parent).offset();
		jQuery(top).css({left:off.left-offp.left+'px',top:off.top-offp.top+obj.offsetHeight+'px',width:w+'px'});
	    if(frame) jQuery(frame).css({width:w+'px'});
	    top.style.display='block';
		visible=true;
		blockMouseOver=true;
    }
  }
},
numItems: function () {
    return this.parts.content ? this.parts.content.rows.length : 0;
},
onblur: function (e) {
  with(this) {
    if(visible) {
	if(hlIndex>=0) obj.value=userInput;
	hide();
    }
  }
},
onkeydown: function (e) {
  with(this) {
    var c=e.keyCode;
    if(c==27 && visible) {
	if(resultInput!="") _setvalue_sep(userInput);
	hide();
	return false;
    }
    if(resultInput=="") return;
    if(c==13 && hlIndex>=0 && visible) {
	previousInput=obj.value;
	userInput=_getvalue_sep();
	resetRequest(userInput);
	hide();
	if(userInput != resultInput) clearResult();
	obj.focus();
	e.preventDefault();
	e.stopPropagation();
	return false;
    }
    if(isDownKey(c)) {
	moveSelection(hlIndex+1);
	return false;
    }
    if(isUpKey(c)) {
	moveSelection(hlIndex-1);
	return false;
    }
  }
},
onkeyup: function (e) {
  with(this) {
    if(ignoreInput!="" && _getvalue_sep()==ignoreInput) return;
    if(obj.value==previousInput) return;
    ignoreInput=resultInput="";
    previousInput=obj.value;
    userInput=_getvalue_sep();
    if(hideTimer) clearTimeout(hideTimer);
    hideTimer=setTimeout("var c=_uSuggestList.all["+idx+"];if(c)c.clearResult(true);",2000);

    procRequest(userInput);
  }
},
_setvalue_sep: function(v) {
	with(this){
		if(sep_pos>=0) obj.value=obj.value.substr(0,sep_pos)+props.separator+' '+v;
			else obj.value=v;
	}
},
_getvalue_sep: function() {
  with(this){
  	if(props.separator) sep_pos=obj.value.lastIndexOf(props.separator);
	if(sep_pos>=0) {
		var t=obj.value.substr(sep_pos+props.separator.length);
	    t=t.replace(/^\s+/,"");
	    return t;
	} else return obj.value;
  }
},
moveSelection: function (newi) {
  with(this) {
    if(resultInput=="" && ignoreInput!="" && _getvalue_sep()==ignoreInput) {
	procRequest(_getvalue_sep(),true);
	return;
    }
    if(!visible && resultInput.length>0 && resultInput==_getvalue_sep()) {
	show();
	return;
    }
    if(!visible) return;
    if(hlRow) design._deselect(this,hlRow);
    hlRow=null;
    var cnt=numItems();
    if(newi>=cnt) newi=-1;
	else if(newi<-1) newi=cnt-1;
    if(newi==-1) {
	hlIndex=-1;
	_setvalue_sep(userInput);
	obj.focus();
	return;
    }
    hlIndex=newi;
    hlRow=parts.content.rows[newi];
    design._select(this,hlRow);
    ignoreInput=jQuery(hlRow).attr("usuggeststr");
    _setvalue_sep(ignoreInput);
  }
},
isUpKey: function (code) {
    return code==38 || code == 63232;
},
isDownKey: function (code) {
    return code==40 || code == 63233;
},
resetRequest: function(txt) {
  with(this) {
    if(remoteReqTimer && requestedInput==txt) return;
    clearTimeout(remoteReqTimer); 	remoteReqTimer=null;
    requestedInput=txt;
    clearTimeout(AJAXTimer); AJAXTimer=null;
    try{if(AJAXObj) AJAXObj.abort(); AJAXObj=null;}catch(e){};
  }
},
procRequest: function (txt,nopause) {
  with(this) {
    resetRequest(txt);

    if(txt.length<props.minlen) {
	clearResult(true);
	return;
    }
    if(queryCache[cacheGroup][txt]) {
	setResult(txt,queryCache[cacheGroup][txt]);
	return;
    }
    AJAXretries=0;
    if(!props.url) return;
    if(nopause) remoteRequest();
	else remoteReqTimer=setTimeout("var c=_uSuggestList.all["+this.idx+"];if(c)c.remoteRequest();",350);
  }
},
remoteRequest: function () {
  with(this) {
    clearTimeout(remoteReqTimer);
    remoteReqTimer=null;
    try{if(AJAXObj) AJAXObj.abort(); AJAXObj=null;}catch(e){};

    if(AJAXretries>1) return;
    clearTimeout(AJAXTimer);
    AJAXTimer=setTimeout("var c=_uSuggestList.all["+this.idx+"];if(c){c.AJAXretries++;c.remoteRequest();}",12000);

    AJAXObj=jQuery.ajax({
	type: "GET",
	dataType: "text",
	cache: false,
	url: props.url,
	data: {tag:requestedInput},
	success: new Function("resp","status","var c=_uSuggestList.all["+this.idx+"];if(c)c.parseRequest(resp,status);"),
	timeout: 10000
    });
  }
},
parseRequest: function (resp,status) {
    clearTimeout(this.AJAXTimer);
    this.AJAXTimer=null;
    this.AJAXretries=0;
    var res=[];
    try {
	res=eval("res="+resp);
    } catch(e) {}
    this.AJAXObj=req=null;
    if(!res || res.length<2 || res[1]<1 || res[1]>10) {
	this.clearResult();
	return;
    }
    var n=res[1],idx=0;
    var data=[];
    for(var i=2;i<res.length;i+=n,idx++) {
	data[idx]=[];
	for(var j=0;j<n;j++) {
	    data[idx][j]=res[i+j];
	}
    }
    this.queryCache[this.cacheGroup][res[0]]=data;
    if(res[0]==this.requestedInput) this.setResult(res[0],this.queryCache[this.cacheGroup][res[0]]);
},
_onrowmousemove: function(e) {
    return e.data.onrowmousemove(e);
},
_onrowmouseover: function(e) {
    return e.data.onrowmouseover(e);
},
_onrowmousedown: function(e) {
    return e.data.onrowmousedown(e);
},
onrowmousemove: function(e) {
    if(this.blockMouseOver) { //mouseOver is disable right after showing results
	this.blockMouseOver=false;
	this.onrowmouseover(e);
    }
},
onrowmouseover: function(e) {
  with(this) {
    if(blockMouseOver) return;
    if(hlRow) design._deselect(this,hlRow);
    hlRow=null;
    hlIndex=-1;
    for(var i=0;i<parts.content.rows.length;i++) {
	if(parts.content.rows[i]==e.target || jQuery.inArray(e.target,jQuery(parts.content.rows[i]).contents())>=0) {
	    hlIndex=i;
	    hlRow=parts.content.rows[i];
	    design._select(this,hlRow);
	    break;
	}
    }
  }
},
onrowmousedown: function(e) {
  with(this) {
    if(numItems()<=0 || !hlIndex<0 || !hlRow) return;
    ignoreInput=userInput=jQuery(hlRow).attr("usuggeststr");
    _setvalue_sep(userInput);
    previousInput=obj.value;
    resetRequest(userInput);
    hide();
    if(userInput != resultInput) clearResult();
    obj.focus();
  }
},

setResult: function (phrase,table) { //array of arrays
  with(this) {
    if(hideTimer) clearTimeout(hideTimer);
    hideTimer=null;
    clearResult();
    hlIndex=-1;
    hlRow=null;
    resultInput=phrase;
    var cnt=table.length;
    if(cnt<=0) {hide();return;}
    var cols=table[0].length; //determine num cols by first item
    for(var i=0;i<cnt;i++) {
	    design.append_row(this,table[i],cols,phrase);
    }
    show();
  }
},
clearResult: function (hide) {
  with(this) {
    if(hide) hide();
    resultInput="";
    hlRow=null;
    hlIndex=-1;
    while(parts.content.rows.length > 0)parts.content.deleteRow(-1);
  }
}
};

function _uDraggable(obj,onmove,oninitdrag,onstartdrag,onstopdrag) {
	this.par=obj;
	this.x=this.y=this.w=this.h=this.m=0;
	this.moved=false;
	this.active=false;
	this.onmove=onmove || _uDraggable.dummy;
	this.oninitdrag=oninitdrag || _uDraggable.dummy;
	this.onstartdrag=onstartdrag || _uDraggable.dummy;
	this.onstopdrag=onstopdrag || _uDraggable.dummy;
    if(!_uDraggable.globalset) {
		_uDraggable.globalset=true;
		jQuery(document).bind("mouseup",_uDraggable.onmouseup);
		jQuery(document).bind("mousemove",_uDraggable.onmousemove);
//		if(jQuery.browser.msie)jQuery(document).bind("mouseout",function(e) {if(!e.relatedTarget && !e.toElement)_uWnd._dragging=null});
	}
}
_uDraggable.dummy=function(){};
_uDraggable.obj=null;
_uDraggable.clkX=0;
_uDraggable.clkY=0;
_uDraggable.scrL=0;
_uDraggable.scrT=0;
_uDraggable.globalset=false;
_uDraggable.onmousemove=function(e) {
  with(_uDraggable) {
    var o=obj;
    if(!o) return;
	if(e.which!=1) {o.stop();obj=null;return;}
	e.stopPropagation();
	e.preventDefault();
    var d=_uWnd.getdims();
	o.event=e;
	if(!o.moved && (e.clientX!=clkX || e.clientY!=clkY)) {o.onstartdrag.apply(o.par,[o.x,o.y,o.w,o.h,o.m]);o.moved=true;}

	o.onmove.apply(o.par,[e.clientX-clkX-(scrL-d.clientLeft),e.clientY-clkY-(scrT-d.clientTop),o.x,o.y,o.w,o.h,o.m]);
	o.event=null;
	return false;
  }
};
_uDraggable.onmouseup=function(e) {
    if(e.which!=1) return;
  with(_uDraggable) {
    var o=obj;
    if(!o) return;
  	if(o.moved)onmousemove(e);
	o.event=e;
  	o.stop();
  	o.event=null;
  	obj=null;
  }
};
_uDraggable.prototype={
	start: function(e,x,y,w,h,m) {
		var r=_uDraggable;
		if(r.obj) r.obj.onstopdrag.apply(r.obj.par);
		this.x=x;
		this.y=y;
		this.w=w;
		this.h=h;
		this.m=m;
		this.active=true;
		this.moved=false;
		r.obj=this;
	    var d=_uWnd.getdims();
	    r.clkX=e.clientX;
	    r.clkY=e.clientY;
	    r.scrL=d.clientLeft;
	    r.scrT=d.clientTop;
	    this.oninitdrag.apply(this.par,[x,y,w,h,m]);
//window.dump("drag start\n");

	},
	stop: function() {
		var r=_uDraggable;
		if(r.obj==this) r.obj=null;
		if(this.active) {
			this.onstopdrag.apply(this.par,[this.x,this.y,this.w,this.h,this.m]);
			this.active=false;
//window.dump("drag stop \n");
		}
	}

};

function _uTabCtrl (name,ntabs,opts,titles,datas,topts) {
	this.constructor=_uTabCtrl;
	this.name=name;
	this.ntabs=ntabs;

	this.props=jQuery.extend({
		parentnode: null, //if null, then just append child
		wnd:null, //use wnd as parent node. window must be created
		app:opts && opts.wnd && opts.wnd.app || null, //parent app and 'this' for all handlers
		width: 'auto', //outer width
		height: 'auto', //outer height
		min_height: 50, //content height
		active_tab: -1, //if 'auto' then check current url for active tab
		close: 0, //default availability of close button
		design: 'std',
		noinit: false,
		markload: '<div align="left"><div class="myWinLoad"></div></div>', //default mark load text
		emptycontent: '', //content when no active tabs


		onload: null, //(tabctrl,idx,tabid) after tab content is loaded (reloaded)for the first time (called before onshow)
		onshow: null, //(tabctrl,idx,tabid) after tab content is loaded into DOM
		onhide: null, //(tabctrl,idx,tabid) when tab looses active state (if tab was closed then this event is called after onbeforeclose if closing was allowed)
		onbeforechange: null, //(tabctrl,idx,tabid) before tab is changed to idx. if false, than ignore click
		onchange: null, //(tabctrl,idx,tabid) after tab is changed to idx. if false, than do not load tab contents
		onbeforeclose: null, //(tabctrl,idx,tabid) before tab is closed. if false, than ignore close
		onclose: null, //(idx,tabid) after tab is closed.
		ondestroy: null, //(tabctrl,name)
		onresize: null, //(cont_width,cont_height,tabctrl,name)
		rtl:0
	},opts || {});

	this.app=this.props.app;
	this.state={init:false,destroyed:false};
    this.design=this.props.design && _uTabCtrl.designs[this.props.design] ? _uTabCtrl.designs[this.props.design] : _uTabCtrl.designs['std'];
    this.idx=_uTabCtrl.nextidx++;
    _uTabCtrl.all[this.idx]=this;
	this.width=parseInt(this.props.width) || 0; //outer width
	this.height=parseInt(this.props.height) || 0;	//outer height
	this.data=[];
	this.pend_show=null;
	this.decor={cdw:0,cdh:0,pdw:0,pdh:0,ph:0}; //
	this.maxid=0;
	this.wnd=null;

	this.active_tab=this.props.active_tab;
	this.scrollpos={tabswidth:0,havewidth:0,pos:null};

	for(var i=0;i<ntabs;i++) {
		var opt=(topts && topts[i]) || {};
		var id=opt.id || '';
		if(!id || id.length==0) id='_tc'+this.idx+'tb'+(this.maxid++);
		this.data[i]={
			id:id,
			title:(titles && titles[i]) || '.',
			dat:(datas && datas[i]) || '',
			cont:null,
			markloadcont:null,
			obj:null,
			ishidden: opt.hidden,
			clbut:null,
			link:null,
			href:opt.href,
			target:opt.target,
			label:null,
			close:opt.close==undefined ? this.props.close : opt.close,
			icon:opt.icon,
			markload:opt.markload,
			firstload:0,
			onload:opt.onload==undefined ? this.props.onload : opt.onload,
			onshow:opt.onshow==undefined ? this.props.onshow : opt.onshow,
			onhide:opt.onhide==undefined ? this.props.onhide : opt.onhide,
			onbeforechange:opt.onbeforechange==undefined ? this.props.onbeforechange : opt.onbeforechange,
			onchange:opt.onchange==undefined ? this.props.onchange : opt.onchange,
			onbeforeclose:opt.onbeforeclose==undefined ? this.props.onbeforeclose : opt.onbeforeclose,
			onclose:opt.onclose==undefined ? this.props.onclose : opt.onclose
			};
	}

	if(!_uTabCtrl.globalset) {
		_uTabCtrl.globalset=true;
//	    jQuery(document).bind("mousedown",_uMENU.hideallmenus);
//	    jQuery(window).bind("resize",_uMENU.hideallmenus);
	}
	this.butdown=new _uDraggable(this,null,null,null,function(but,tab){this.design._onbuttonup(this,but,tab);});

	if(!this.props.noinit)this.init();
}


_uTabCtrl.all=[];
_uTabCtrl.nextidx=0;
_uTabCtrl.globalset=false;

_uTabCtrl.getbyname=function(name) {
    var a=this.all;
    for(var i=0;i<a.length;i++) if(a[i] && a[i].name==name) return a[i];
    return null;
};
_uTabCtrl.closeTab=function(name,idx) {
    var w=this.getbyname(name);
    if(w) w.closeTab(idx);
}
_uTabCtrl.content=function(name,idx,c) {
    var w=this.getbyname(name);
    if(w)w.content(idx,c);
}
_uTabCtrl.setTitle=function(name,idx,t) {
    var w=this.getbyname(name);
    if(w)w.setTitle(idx,t);
}

_uTabCtrl.designs={
    std: {
//    tab_height:'25px',
	tabctrl_init: function(o) {
	    var p={};
		jQuery(o.top).attr('class',"x-unselectable u-tabc").html(
 '<div class="u-tabc-p"><div class="u-tabc-listp"><div class="u-tabc-list"></div><div class="u-tabc-pbot"></div></div><div class="u-tabc-scrbut"><div class="u-tabc-tabl"><div class="u-tabc-label"><div class="u-tabc-scrl"></div><div class="u-tabc-scrr"></div></div></div></div></div>'
+'<div class="u-tabc-body"><div class="u-tabc-content" style="height:'+o.props.min_height+'px">'+o.props.emptycontent+'</div></div>'
			);
	    p.pane=jQuery(o.top).find(".u-tabc-p")[0];
	    p.panebot=jQuery(o.top).find(".u-tabc-pbot")[0];
	    p.listp=jQuery(o.top).find(".u-tabc-listp")[0];
	    p.list=jQuery(o.top).find(".u-tabc-list")[0];
	    p.scrbut=jQuery(o.top).find(".u-tabc-scrbut")[0];
	    p.scrl=jQuery(o.top).find(".u-tabc-scrl")[0];
	    p.scrr=jQuery(o.top).find(".u-tabc-scrr")[0];
	    p.body=jQuery(o.top).find(".u-tabc-body")[0];
	    p.emptycontent=p.content=jQuery(o.top).find(".u-tabc-content")[0];
		jQuery(o.top).find("div,span").andSelf().attr("unselectable","on");
		jQuery(p.scrl).bind("click mousedown mouseover mouseout",{obj:o,but:0},_uTabCtrl._onscrbutevent);
		jQuery(p.scrr).bind("click mousedown mouseover mouseout",{obj:o,but:1},_uTabCtrl._onscrbutevent);

	    return p;
	},
	remove_item: function(o,idx) {
		o.parts.list.removeChild(o.data[idx].obj);
	},
	set_title: function(o,idx) {
		jQuery(o.data[idx].label).html(
			(o.data[idx].icon ? '<img class="u-tabc-icon" border="0" src="'+o.data[idx].icon+'">' : (jQuery.browser.msie && jQuery.browser.version<8 ? '<img class="u-tabc-spacer" src="/img/1px.gif" width="1" height="1" border="0">' : ''))
			+o.data[idx].title
		);
	},
	insert_item: function(o,idx) {
		var a=document.createElement('div');
		jQuery(a).attr('class','u-tabc-tab'+(o.data[idx].close ? ' u-tabc-wcl':'')).html(
(o.data[idx].href ?
'<a '+(o.data[idx].target ? 'target="'+o.data[idx].target+'" ':'')+'href="'+o.data[idx].href+'" class="u-tabc-tabl" style="display:block">' :
'<div class="u-tabc-tabl">' )
			+(o.data[idx].close ? '<div class="u-tabc-closebut"></div>' : '')
			+'<div class="u-tabc-tabr"><div class="u-tabc-label">'
			+(o.data[idx].icon ? '<img class="u-tabc-icon" border="0" src="'+o.data[idx].icon+'">' : (jQuery.browser.msie && jQuery.browser.version<8 ? '<img class="u-tabc-spacer" src="/img/1px.gif" width="1" height="1" border="0">' : ''))
			+o.data[idx].title
			+'</div></div>'+(o.data[idx].href ? '</a>' : '</div>')
		);
		o.data[idx].obj=a;
		o.data[idx].label=jQuery(a).find(".u-tabc-label")[0];
		o.data[idx].link=jQuery(a).find(".u-tabc-tabl")[0];
	    if(o.data[idx].close) {
	    	o.data[idx].clbut=jQuery(a).find(".u-tabc-closebut")[0];
			jQuery(o.data[idx].clbut).bind("mouseover",this._onclbutmouseover).bind("mouseout",this._onclbutmouseout).bind("click",{obj:o,tab:o.data[idx]},_uTabCtrl._onclbutclick).bind("mousedown",{obj:o,tab:o.data[idx]},_uTabCtrl._onclbutdown);
	    }
		jQuery(o.data[idx].link).bind("mouseover",this._ontabmouseover).bind("mouseout",this._ontabmouseout).bind("mousedown",{obj:o,tab:o.data[idx]},_uTabCtrl._ontabclick);
		jQuery(a).find("div,span,a,img").andSelf().attr("unselectable","on");
		if(o.data[idx].ishidden) a.style.display='none';

		var nc=o.parts.list.childNodes.length;
//		if(o.props.rtl || window._rtl)
//			o.parts.list.insertBefore(a,nc-idx>=nc ? null : o.parts.list.childNodes[nc-idx]);
//		else
			o.parts.list.insertBefore(a,idx>=nc ? null : o.parts.list.childNodes[idx]);
	},
	_ontabmouseover: function(e) {
		jQuery(this.parentNode).addClass("u-tabc-tab-over");
	},
	_ontabmouseout: function(e) {
		jQuery(this.parentNode).removeClass("u-tabc-tab-over");
	},
	_onclbutmouseover: function(e) {
		jQuery(this).addClass("u-tabc-closebut-over");
	},
	_onclbutmouseout: function(e) {
		jQuery(this).removeClass("u-tabc-closebut-over");
	},
	_onclbutmousedown: function(b,v) {
		if(v) jQuery(b).addClass("u-tabc-closebut-down");
			else jQuery(b).removeClass("u-tabc-closebut-down");
	},
	_ontabactivate: function(o,idx) {
		jQuery(o.data[idx].obj).addClass("u-tabc-tab-act");
	},
	_ontabdeactivate: function(o,idx) {
		jQuery(o.data[idx].obj).removeClass("u-tabc-tab-act");
	},
	_onscrbutactivate: function(o,but,v) { //0-left else right
		if(v) jQuery(!but ? o.parts.scrl : o.parts.scrr).removeClass("u-tabc-scr-dis");
			else jQuery(!but ? o.parts.scrl : o.parts.scrr).addClass("u-tabc-scr-dis");
	},
	_onscrbutover: function(o,but,v) { //0-left else right
		var b=!but ? o.parts.scrl : o.parts.scrr;
		if(v) jQuery(b).addClass("u-tabc-scr-over");
			else jQuery(b).removeClass("u-tabc-scr-over");
	},
	_onscrbutdown: function(o,but,v) { //0-left else right
		var b=!but ? o.parts.scrl : o.parts.scrr;
		if(v) jQuery(b).addClass("u-tabc-scr-down");
			else jQuery(b).removeClass("u-tabc-scr-down");
	},
	_onbuttonup: function(o,but,tab) { //0-left scroll,1-right scroll,2-tab close
		if(but<2) this._onscrbutdown(o,but,0);
			else this._onclbutmousedown(tab.clbut,0);
	}
    }
};
_uTabCtrl._onclbutdown=function(e) {
		if(e.which==1) {
			e.stopPropagation();
			e.data.obj.design._onclbutmousedown(e.data.tab.clbut,1);
			e.data.obj.butdown.start(e,2,e.data.tab);
		}
		_uWnd.globalmousedown();
};
_uTabCtrl._onscrbutevent=function(e) {
		var o=e.data.obj,but=e.data.but;
		if(e.type=='click' && e.which==1) o.scrollTabPane(but ? 40 : -40);
			else if(e.type=='mouseover') o.design._onscrbutover(o,but,1);
			else if(e.type=='mouseout') o.design._onscrbutover(o,but,0);
			else if(e.type=='mousedown' && e.which==1) {
				o.design._onscrbutdown(o,but,1);
				o.butdown.start(e,but);
			}
};
_uTabCtrl._onclbutclick=function(e) {
		var d=e.data,o=d.obj;
		for(var i=0;i<o.data.length;i++)
			if(o.data[i]==d.tab) {
				if(typeof o.data[i].onbeforeclose == 'function') if(!o.data[i].onbeforeclose.call(o.app,o,i,o.data[i].id)) break;
				o.closeTab(i);
				break;
			}
		e.preventDefault();
		e.stopPropagation();
};
_uTabCtrl._ontabclick=function(e) {
		var d=e.data,o=d.obj;
		e.preventDefault();
		for(var i=0;i<o.data.length;i++)
			if(o.data[i]==e.data.tab) {
				if(i==o.active_tab) return;
				if(typeof o.data[i].onbeforechange == 'function') if(!o.data[i].onbeforechange.call(o.app,o,i,o.data[i].id)) break;
				o.activateTab(i);
				break;
			}
};

_uTabCtrl.prototype={
	init: function(noinit) {
		var t=document.createElement("div");
		t.id="_utabctrl"+this.idx;
		if(this.props.parentnode) this.props.parentnode.appendChild(t);
			else if(this.props.wnd) {
				var ww=this.props.wnd.parts.wndcont;
				while(ww.firstChild) ww.removeChild(ww.firstChild);
				ww.appendChild(t);
				this.wnd=this.props.wnd;
				this.wnd.tabctrl=this;
				this.wnd.state.loaded=true;
				}
			else jQuery(jQuery("body")[0]).append(t);

		this.top=t;
	    jQuery(t).css({visibility:'hidden',display:'block'});
		if(this.width>0) jQuery(t).css('width',this.width+'px');
//		if(this.height>0) jQuery(t).css('height',this.height+'px');

	    this.parts=this.design.tabctrl_init(this);
	    this.parts.markloadcont=null;
		this.show();
		if(!noinit)setTimeout("var m=_uTabCtrl.all["+this.idx+"];if(m)m.init1();",10);
	},
	init1: function(noresize) { //noresize used internally by windows
//calculate decor
		var p=this.parts,d=this.decor;
		if(!(this.width>0)) this.width=this.top.offsetWidth;
		if(!(this.height>0)) this.height=this.top.offsetHeight;
		d.cdw=this.top.offsetWidth-p.content.offsetWidth;
		d.cdh=this.top.offsetHeight-p.content.offsetHeight;
		d.pdw=this.top.offsetWidth-p.listp.offsetWidth;
		if(!this.props.wnd && !noresize) {
			jQuery(this.top).css('height',this.height+'px');
			jQuery(p.content).css({width:(this.top.offsetWidth-d.cdw)+'px',height:(this.top.offsetHeight-d.cdh)+'px'});
			jQuery(p.listp).css({width:(this.top.offsetWidth-d.pdw)+'px'});
		}

		jQuery(p.listp).css({overflow:'hidden'});
		jQuery(p.panebot).css('width','4000px');
		jQuery(p.list).css('width','4000px');
		for(var i=0;i<this.ntabs;i++)
			this.design.insert_item(this,i);
		if(this.props.wnd)
			this.resizeTo(this.props.wnd.width-this.props.wnd.decor.w,this.props.wnd.height-this.props.wnd.decor.h);
		var at=this.active_tab;
		this.active_tab=-1;
		if(at=='auto')
			if(this.name && this.name.length>0 && self.location.hash.length>1) {
				var u=self.location.hash.substr(1).split(';');
				var s='T_'+this.name+'=';
				for(var ui=0;ui<u.length;ui++)
					if(u[ui].length>s.length && u[ui].substr(0,s.length)==s) {
						var tb=this.idxbyid(u[ui].substr(s.length));
						if(tb>=0 && tb<this.data.length) {at=tb;break;}
					}
			} else at=-1;
	    jQuery(this.top).css("display",'block').css("visibility",'visible');
	    if(at==-1 && this.data.length>0) at=0;
	    if(at>=0 && at<this.ntabs) {
			for(var i=0;i<this.ntabs;i++) {
				var j=(at+i)%this.ntabs;
				if(!this.data[j].ishidden && (!this.data[j].onbeforechange || !!this.data[j].onbeforechange(this,j,this.data[j].id))) {
					this.activateTab(j,true);
					break;
				}
			}
		} else this.activateTab(-1,true);

	    jQuery(this.top).css("display",'none').css("visibility",'visible');
		this.state.init=true;
	    if(pend_show) this.show(pend_show[0]);
	    if(this.props.wnd) this.props.wnd.onexternalload(); //activate autosize
	},
	scrollTabPane: function(dx) { //>0 - right
		var pos=this.scrollpos.pos+=dx;
		var w=this.scrollpos.tabswidth,havew=this.scrollpos.havewidth;
		if(w<havew) {
			this.design._onscrbutactivate(this,0,0);
			this.design._onscrbutactivate(this,1,0);
			if((this.props.rtl || window._rtl) && this.data.length>0) {
				pos=this.data[this.data.length-1].obj.offsetLeft+havew-w;
			} else pos=0;
			this.scrollpos.pos=pos;
			this.parts.listp.scrollLeft=pos;
		} else {
			if(this.props.rtl || window._rtl) {
				var ol=this.data[this.data.length-1].obj.offsetLeft;
				if(pos<ol) pos=ol;
					else if(pos>ol+w-havew) pos=ol+w-havew;
			} else if(pos<0) pos=0;
					else if(pos>w-havew) pos=w-havew;
			this.scrollpos.pos=pos;
			this.parts.listp.scrollLeft=pos;
			if(pos>0) this.design._onscrbutactivate(this,0,1);
				else this.design._onscrbutactivate(this,0,0);
			if(pos<w-havew) this.design._onscrbutactivate(this,1,1);
				else this.design._onscrbutactivate(this,1,0);
		}
	},
	_setscrolls: function() { //set scroll buttons status accroding to tab widths
		var w=0,havew=this.parts.listp.offsetWidth;
		if(this.parts.listp.clientWidth>0 && this.parts.listp.clientWidth<havew) havew=this.parts.listp.clientWidth;
		if(this.data.length>0) {
			var o=this.data[this.data.length-1];
			if(this.props.rtl || window._rtl) {
				var o2=this.data[0];
				w=o2.obj.offsetLeft+o2.obj.offsetWidth-o.obj.offsetLeft;
			} else w=o.obj.offsetLeft+o.obj.offsetWidth;
		}
		if(havew<w) { //enable scrolls
			this.parts.scrbut.style.display='block';
			havew-=this.parts.scrbut.offsetWidth;
		} else this.parts.scrbut.style.display='none';

		if(this.scrollpos.pos==null) {
			if((this.props.rtl || window._rtl) && this.data.length>0) this.scrollpos.pos=this.data[this.data.length-1].obj.offsetLeft+w-havew;
				else this.scrollpos.pos=0;
		} else if(this.scrollpos.havewidth!=havew)
					if(this.props.rtl || window._rtl) this.scrollpos.pos+=this.scrollpos.havewidth-havew;

		this.scrollpos.havewidth=havew;
		this.scrollpos.tabswidth=w;
		this.scrollTabPane(0);
//		alert(w+','+havew);
	},
	show: function(rel) {
		if(!this.state.init) {pend_show=[rel];return;}
  		jQuery(this.top).show();
	    this.state.visible=true;
//	    if(rel) load();
	},
	resizeTo: function(w,h) {
		this.width=w;
		this.height=h;
		var d=this.decor;
//		jQuery(this.top).css({height:h+'px',width:w+'px'});
		jQuery(this.top).width(w).height(h);
		jQuery(this.parts.content).css({width:(w-d.cdw)+'px',height:(h-d.cdh)+'px'});
		jQuery(this.parts.listp).css({width:(w-d.pdw)+'px'});
		if(this.props.onresize) this.props.onresize(w-d.cdw,h-d.cdh,this,this.name);
		this._setscrolls();
	},
	addTab: function(title,dat,topt,idx) {
		var i= idx!=undefined && idx>=0 && idx<this.data.length ? idx : this.data.length;
		var opt=topt || {};
		var id=opt.id || '';
		if(!id || id.length==0) id='_tc'+this.idx+'tb'+(maxid++);
		var data={
			id:id,
			title:title || '.',
			dat:dat || '',
			cont:null,
			markloadcont:null,
			obj:null,
			ishidden: opt.hidden,
			clbut:null,
			link:null,
			href:opt.href,
			target:opt.target,
			label:null,
			close:opt.close==undefined ? this.props.close : opt.close,
			icon:opt.icon,
			markload:opt.markload,
			firstload:0,
			onload:opt.onload==undefined ? this.props.onload: opt.onload,
			onshow:opt.onshow==undefined ? this.props.onshow : opt.onshow,
			onhide:opt.onhide==undefined ? this.props.onhide : opt.onhide,
			onbeforechange:opt.onbeforechange==undefined ? this.props.onbeforechange : opt.onbeforechange,
			onchange:opt.onchange==undefined ? this.props.onchange : opt.onchange,
			onbeforeclose:opt.onbeforeclose==undefined ? this.props.onbeforeclose : opt.onbeforeclose,
			onclose:opt.onclose==undefined ? this.props.onclose : opt.onclose
			};

		if(i<this.data.length) this.data.splice(i,0,data);
			else this.data[i]=data;
		this.design.insert_item(this,i);
		this._setscrolls();
		return i;
	},
	tabHidden: function(idx,ishidden) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		var a=this.data[idx];
		a.obj.style.display=ishidden ? 'none' : '';
		a.ishidden=!!ishidden;
		this._setscrolls();
	},
	activateTab: function(idx,first) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length || this.active_tab==idx) if(first && this.data.length>0) idx=0; else return;
		this.design._ontabactivate(this,idx);
		if(this.active_tab>=0 && this.active_tab<this.data.length) {
			if(typeof this.data[this.active_tab].onhide == 'function') this.data[this.active_tab].onhide.call(this.app,this,this.active_tab,this.data[this.active_tab].id);
			this.design._ontabdeactivate(this,this.active_tab);
		}
		this.active_tab=idx;
		this._setscrolls();
		if(typeof this.data[idx].onchange == 'function') if(!this.data[idx].onchange.call(this.app,this,idx,this.data[idx].id)) return;
		this.load(idx);
	},
	closeTab: function(idx) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		if(idx==this.active_tab && typeof this.data[idx].onhide == 'function') this.data[idx].onhide.call(this.app,this,idx,this.data[idx].id);

		this.design.remove_item(this,idx);
		var id=this.data[idx].id;
		var f=this.data[idx].onclose;
		this.data.splice(idx,1);
		if(idx==this.active_tab) {
			this.active_tab=-1;
			if(idx==this.data.length)
				if(idx==0) this._assign_content(-1);
					else this.activateTab(idx-1);
				else this.activateTab(idx);
		} else if(idx<this.active_tab) this.active_tab--;
		this._setscrolls();
		if(f) f(this,idx,id);
	},
	setTitle: function(idx,title) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		this.data[idx].title=title;
		this.design.set_title(this,idx);
		this._setscrolls();
	},
	content: function(idx,c) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		if(!this.data[idx].cont) {
			this.data[idx].cont=document.createElement('DIV');
			jQuery(this.data[idx].cont).addClass("u-tabc-content");
		}
		jQuery(this.data[idx].cont).html(c);
		this.data[idx].firstload=1;
		if(idx==this.active_tab) this._assign_content(idx);
	},
	_assign_content: function(idx,altcont) {
		if(altcont) this.parts.content=altcont;
			else if(idx<0) this.parts.content=this.parts.emptycontent;
			else this.parts.content=this.data[idx].cont;
		jQuery(this.parts.content).css({width:(this.width-this.decor.cdw)+'px',height:(this.height-this.decor.cdh)+'px'});
		this.parts.body.replaceChild(this.parts.content,this.parts.body.firstChild);
		if(!altcont && idx>=0 && typeof this.data[idx].onload == 'function' && this.data[idx].firstload) this.data[idx].onload.call(this.app,this,idx,this.data[idx].id);
		if(!altcont && idx>=0 && typeof this.data[idx].onshow == 'function') this.data[idx].onshow.call(this.app,this,idx,this.data[idx].id);
		this.data[idx].firstload=0;
	},
	markload: function(idx,txt) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		var c;
		if(this.data[idx].markload) { //this tab has its own markload page
			if(!this.data[idx].markloadcont) {
				this.data[idx].markloadcont=document.createElement('DIV');
				jQuery(this.data[idx].markloadcont).addClass("u-tabc-content").html(this.data[idx].markload);
			}
			c=this.data[idx].markloadcont;
		} else {
			if(!this.parts.markloadcont) {
				this.parts.markloadcont=document.createElement('DIV');
				jQuery(this.parts.markloadcont).addClass("u-tabc-content").html(this.props.markload);
			}
			c=this.parts.markloadcont;
		}
		this._assign_content(idx,c);
	},
	idxbyid: function(id) {
		if(typeof id=='string') {
			for(var i=0;i<this.data.length;i++) if(this.data[i].id==id) return i;
			return -1;
		} else return id;
	},
	load: function(idx,reload) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		if(this.data[idx].cont!=null && !reload) { //content is already loaded
			this._assign_content(idx);
			return;
		}
	    var c=this.data[idx].dat;
    	if(typeof (c) == 'string') this.content(idx,c);
    	else if(typeof c == 'function') this.content(idx,c());
    	else if(typeof c == 'object') {
			this.markload(idx);
			if(!c.success && c.xml===false) {c.dataType='text';c.success=new Function("data","st","var w=_uTabCtrl.all["+this.idx+"];if(w)w.content('"+this.data[idx].id+"',data);");}
	   			else if(!c.success && c.xml!==false) c.success=new Function("data","st","var w=_uTabCtrl.all["+this.idx+"];_uParseXML(data,w,'"+this.data[idx].id+"');");
			if(!c.error) c.error=new Function("xml","st","er","var w=_uTabCtrl.all["+this.idx+"];if(w)w._onerror('"+this.data[idx].id+"',xml,st,er);");
			try {
			if(c.form && (c.form.length>0 || c.form.nodeType)) //have form
	   			_uPostForm(c.form,c);
	   		else if(c.url) _uAjaxRequest(c.url,c);
			} catch(e) {this._onerror(this.data[idx].id,null,'',e);}
    	}
    	return true;
	},
	_onerror: function(id,xml,st,er) {
		var idx=this.idxbyid(id);
		if(idx<0 || idx>=this.data.length) return;
	    var o=this.props.onerror;
	    if(o && typeof(o)=='function') o.apply(this.app,arguments);
			else this.content(idx,'Error during load. Try to <a href="javascript://" onclick="var w=_uTabCtrl.all[\''+this.idx+'\'];if(w)w.load(\''+this.data[idx].id+'\',1);">reload</a>.');
	},
	destroy: function() {
		//remove items
		this.data.splice(0,this.data.length);
		this.parts=null;
		this.top.parentNode.removeChild(this.top);
		this.top=null;
		if(this.props.ondestroy) this.props.ondestroy(this,this.name);
	}
};

function _uWnd (name,title,width,height,opts,content,menuitems,app) {
    if(name && name.length>0) {
		var t=_uWnd.getbyname(name);
		if(t) {t.reload(content);return false;}
    }
    this.desktop=this.opts && this.opts.desktop || _uWnd.defdesktop;
//opts:
//	header - whether window has header
//	min - show minimize button
//	max - show maximize/restore button
//	close - show close button
//	hidden - whether initially hidden
//	modal - whether window is modal
//	alert - window has z-index above modal windows
//	popup - whether window is closed when clicked outside
//	nomove - window cannot be moved
//	resize - whether window can be resized
//  fixed - whether window is fixed to viewport
    this.props=jQuery.extend({
	x: 'auto',
	y: 'auto',
	header: title ? 1 : 0,
	min: this.desktop ? 1 : 0,
	max: this.desktop ? 1 : 0,
	session: null,
	close: 1,
	center: 0, //center window even for desktop (not cascaded)
	customButtons: null, //{ 'name': [init_visible,actionfunc(wnd,'name'),thispar]... }  'xt-name' class, 'xt-name-over' will be used when mouseover
	hidden: 0,
	modal: 0,
	nomove: 0,
	resize: 1,
	fixed: _uWnd.defdesktop || opts.desktop ? 0 : 1,
	autosize: 1,
	autosizewidth: 0,
	autosizeonimages: 0, //restart auto size on every image load if content has images
	hideonresize: 0, //make content invisible during autosize
	waitimages: 0, //if >0, then do not show content until all images are loaded (timeout is specified value), only during autosize
	markload: '<div align="left"><div class="myWinLoad"></div></div>', //default mark load text
	markdisablecont: '<div class="myWinLoad"></div>', //default content of disabling layer (grided mode)
	markdisableclass: 'myWinGrid', //default class for disabling layer

	popup: 0,
	alert: 0,
	align: 'center',
	shadow: 1,
	design: 'std',
	fadetype: 1, //0 - no fade, 1 - animate opacity, 2 - move down and opacity
	fadespeed: 800,
	fadeclosetype: 1, //0 - no fade, 1 - animate opacity, 2 - move down and opacity
	fadeclosespeed: 250,
	minh: 50,
	minw: 0,
	maxh: 0,
	maxw: 0,
	icon: '',
	havemenu: menuitems ? 1 : 0,
	menuopts: null, //object with menu options, will be passed to menu constructor
	desktop: null,
	onerror: null,
	onclose: null, //(wnd,wndidx) called after window is destroyed
	onbeforeclose: null, //(wnd) called after user 'close' event appears (button or taskbar). if true, then ignore close
	oninit: null, //called when window finished its initialization and content can be loaded, if returns false, no default content is assigned to window (can be used to assign already created tab control)
	oncontent: null, //(wnd,contElem) called after content is loaded into window and its object became accessible
	onposchange: null, //(wnd) called when window position, size of min/max state is changed
	notaskbar: 0,
	trayicon: null, //just string with icon image URL or object with all optional fields (image must be if window have no icon){title:title, img:image, param:param, thisobj:thisobj, ondown:handler,onclick:handler,onrdown:handler} if thisobj redefined, no standard handlers will be set. param is true for animated show/hide
	traymenu: null, //tray menu which will be set by standard onrdown handler (array with items)
	notabdestroy:0
    }, opts || {});
	if(this.props.modal) this.props.min=0;
	if(this.props.session) {
		this.props.x=this.props.session.x;
		this.props.y=this.props.session.y;
	}
//content is string, function returning string or object:
//  url - load window content (on show) by using request to this url, if xml=true, content should be set by _uWnd.content(name,content) or wnd.content(content), otherwise result assumed to be plain html
//  form - send request (for 'url' option) using data from this form ID. if no 'url', use 'action'
//  xml - whether result of remote request is raw html or parsed XML
//  type - 'get' or 'post' methods when 'form' is specified, otherwise use form's 'method' attribute
//  cache - whether to allow browser to cache result of remote request
//  async - whether to do async remote request
//  success - alternative function(data,status) to process successful request (default depends on 'xml')
//  error - handler of error requests.
//  dataType - data type to return to 'success' function
    jQuery.extend(this,
	{
	name: name,
	title: title ? title : '',
	letsize: 1, //average width of letters in title
	width: width && width>10 ? width : 300,
	height: height && height>10 ? height : 200,
	decor: {w:0, h:0, th:0}, //width of window decoration (it is added to content width to get window width)
	_content: content,
	state: {visible:false,minimized:false,maximized:false,loaded:false,init:false,disabled:false,grided:false,noshadow:false,resizing:false,destroyed:false},
	grid: null, //grid object for modal windows
	frame: null, //background iframe for IE
	sh: null,//array of shadow objects
	sh_sz: [4,2], //shadow outdent and indent in pixels
	xpos: 0,
	ypos: 0,
	zpos: this.props.modal || this.props.alert ? _uWnd.getModalTopZ() : _uWnd.getTopZ(),
	_drag: new _uDraggable(this,this._ondragmousemove,null,this.onstartdrag,this.onstopdrag),
	_resize: new _uDraggable(this,this._onrsmousemove,null,this.onstartrs,this.onstoprs),
	restRect: null,
//		rsBut: {},
	minheight: this.props.minh,
	minwidth: this.props.minw,
	maxheight: this.props.maxh,
	maxwidth: this.props.maxw,
	pend_show: null,
	autosz: {active:false},
	imgloader: {timer:null,active:false},
	menu: null,
	app: app || null, //parent application. if assigned then all event handlers and content function are called in context of app
	tabctrl: null
	});
    this.design=this.props.design && _uWnd.designs[this.props.design] || _uWnd.designs['std'];
    this.idx=_uWnd.nextidx++;
    _uWnd.all[this.idx]=this;
    if(!_uWnd.globalset) {
	_uWnd.globalset=true;
//		jQuery(document).bind("click",_uMenu.allmenushide);
//	jQuery(document).bind("mouseup",_uWnd._onmouseup);
	jQuery(document).bind("mousedown",_uWnd.closepopup);
//	jQuery(document).bind("mousemove",_uWnd._onmousemove);
//		if(jQuery.browser.msie)jQuery(document).bind("mouseout",function(e) {if(!e.relatedTarget && !e.toElement)_uWnd._dragging=null});
	jQuery(window).bind("scroll",_uWnd._onscroll);
	jQuery(window).bind("resize",_uWnd._onresize);
    }
    this.init(menuitems);
}

_uWnd.all={};
_uWnd.nextidx=0;
_uWnd.zchilds=[];
_uWnd.lastz=0;
_uWnd.minz=10000;
_uWnd.maxz=20000;
_uWnd.lastmodalz=0;
_uWnd.minmodalz=21000;
_uWnd.maxmodalz=25000;
_uWnd.globalset=false;
_uWnd.defdesktop=null;
_uWnd.activewnd=null;
_uWnd.globalmousedown=function(){
	_uMENU.hideallmenus();
	_uSuggestList.hideall();
	_uComboBox.hideall();
	_uWnd.closepopup();
};
_uWnd.alerts=null;
_uWnd.alert=function(txt,title,opts) {
    opts=jQuery.extend({w:150,h:100,tm:5000,close:1,align:'center',icon:'',name:''},opts || {});
    var d,x,y,by,p,maxy;
    if(!(d=_uWnd.defdesktop)) {
    	d=_uWnd.getdims();
    	x=d.clientW-opts.w-5;
    	by=d.clientH-opts.h-5;//bottom y
    	p=_uWnd.alerts;
    	maxy=0;
    	d=null;
    } else {
		x=d.width-d.calcexclude(1)-opts.w-5;
		by=d.height-d.calcexclude(3)-opts.h-5;
		p=d.alerts;
		maxy=d.calcexclude(2);
    }
   	y=by;
    if(p) {
		if(p.y-(opts.h+5)>=0) y=p.y-(opts.h+5);
		while(p) {if(p.y>maxy) maxy=p.y;p=p.prev;}
		if(maxy>0 && by-maxy>=opts.h+5)y=by;
    }
    var w=new _uWnd(opts.name,title,opts.w,opts.h,{close:opts.close,min:0,max:0,icon:opts.icon,align:opts.align,x:x,y:y,alert:1,autosize:0,fixed:1,shadow:0,resize:0,nomove:1,hidden:0,notaskbar:1,fadetype:2,fadespeed:500,fadeclosetype:2,fadeclosespeed:500,onclose:function(w,idx){_uWnd.rmalert(w,idx);}},txt);
    if(!d)_uWnd.alerts={prev:_uWnd.alerts,wnd:w,y:y};
    	else d.alerts={prev:d.alerts,wnd:w,y:y};
    if(opts.tm>0) setTimeout("var w=_uWnd.all["+w.idx+"];if(w)w.close();",opts.tm);
    return w;
};
_uWnd.rmalert=function(w,idx) {
    var a=w.desktop ? w.desktop.alerts : _uWnd.alerts,p=null;
    while(a && a.wnd!==w) {p=a;a=a.prev;}
    if(a && a.wnd===w) if(p) p.prev=a.prev; else {
    	if(w.desktop) w.desktop.alerts=a.prev; else _uWnd.alerts=a.prev;
    }
};
_uWnd._onscroll=function(e) {
    if(!jQuery.browser.msie) return;
    var d=_uWnd.getdims(),a=_uWnd.all;
    for(var i in a)
	if(a[i]) if(a[i].props.fixed || a[i].grid) a[i].moveTo(a[i].xpos,a[i].ypos);
};
_uWnd._onresize=function(e,dsk) { //if dsk then select by desktop, otherwize without desktop
    var d=_uWnd.getdims(),a=_uWnd.all;
    for(var i in a) if(a[i])  if((!dsk && !a[i].desktop) || a[i].desktop==dsk) a[i]._onresize(d);
};
_uWnd.closepopup=function() {
    var a=_uWnd.all;
    for(var i in a)	if(a[i] && a[i].props.popup) a[i].closeevent();
};
_uWnd.findparent=function(elem){ //find parent window for specified element
	var p=elem;
	while(p && p!=document.body) {
		if(p.id && p.id.indexOf('_uwndTop')==0 && p._uwndobj) return p._uwndobj;
		p=p.parentNode;
	}
	return null;
};
_uWnd.getbyname=function(name) {
    var a=this.all;
    for(var i in a) if(a[i] && a[i].name==name) return a[i];
    return null;
};
_uWnd.getTopZ=function() {
  with(_uWnd) {
    var z=lastz;
    if(z<minz) z=minz; else z+=5;
    if(z+5>maxz) {
		var x=minz;
		var ar=[];
		for(var i in all) if(all[i]) ar[ar.length]=all[i];
		for(var i=0;i<zchilds.length;i++) if(zchilds[i]) ar[ar.length]=zchilds[i];
		ar.sort(function(a,b){return a.zpos-b.zpos});
		for(var i=0;i<ar.length;i++) {
		    ar[i].setZ(x);x+=5;
		}
		z=x;
    }
    lastz=z;
    return z;
  }
};
_uWnd.getModalTopZ=function() {
  with(_uWnd) {
    var z=lastmodalz;
    if(z<minmodalz) z=minmodalz; else z+=5;
    if(z+5>maxmodalz) {
		var x=minmodalz;
		var ar=[];
		for(var i in all) if(all[i] && all[i].props && (all[i].props.modal || all[i].props.alert)) ar[ar.length]=all[i];
		ar.sort(function(a,b){return a.zpos-b.zpos});
		for(var i=0;i<ar.length;i++) {
		    ar[i].setZ(x);x+=5;
		}
		z=x;
    }
    lastmodalz=z;
    return z;
  }
};
_uWnd.getdims=function() {
    var d=document;
    var s='';
    return {clientW: Math.min(jQuery.browser.opera && window.innerWidth || jQuery(window).width(),jQuery.browser.safari && d.body.clientWidth || jQuery(window).width(),jQuery(window).width()),
	    clientH: Math.min(jQuery.browser.opera && window.innerHeight || jQuery(window).height(),jQuery.browser.safari && d.body.clientHeight || jQuery(window).height(),jQuery(window).height()),
	    clientLeft: jQuery(d).scrollLeft(),
	    clientTop: jQuery(d).scrollTop(),
	    docW: jQuery(d).width(),
	    docH: jQuery(d).height()};
};
_uWnd.csize=function(elem,name) {
    if ( name != "width" && name != "height" ) return 0;
    var val, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
    val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
    var padding = 0, border = 0;
    jQuery.each( which, function() {
	padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
	border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
    });
    val -= Math.round(padding + border);
    return Math.max(0, val);
}
_uWnd.close=function(name) {
    var w=_uWnd.getbyname(name);
    if(w) w.close();
}
_uWnd.content=function(name,c) {
    var w=_uWnd.getbyname(name);
    if(w)w.content(c);
}
_uWnd.reload=function(name,c) {
    var w=_uWnd.getbyname(name);
    if(w)w.reload(c);
}
_uWnd.setTitle=function(name,t) {
    var w=_uWnd.getbyname(name);
    if(w)w.setTitle(t);
}
_uWnd.activatetopwnd=function(dsk) {
    var maxz=0,maxw=null,a=_uWnd.all;
    for(var i in a) {
		if(!a[i] || (dsk && a[i].desktop!=dsk) || !a[i].state.visible || a[i].state.minimized) continue;
		if(a[i].zpos>maxz){maxz=a[i].zpos;maxw=a[i];}
	}
	if(maxw)maxw.activate();
		else if(dsk)dsk.activewnd=null;else _uWnd.activewnd=null;
};
_uWnd.designs={
    std: {
	sh_sz: [4,2], //design specific shadow config
	altcloseclass: 'xt-close2',

	shadow_init: function(top) {
	    var sh=[];
	    for(var i=0;i<3;i++) {
			sh[i]=document.createElement("div");
			top.appendChild(sh[i]);
			jQuery(sh[i]).attr("class","x-sh").css({position:"absolute",zIndex:1});
	    }
	    jQuery(sh[0]).addClass("xsl").css({width:(this.sh_sz[0]+this.sh_sz[1])+"px",left:(-this.sh_sz[0])+"px",top:"0px"}).html('<div class="xstl"><div class="xsml"></div></div>');
	    jQuery(sh[1]).addClass("xsr").css({width:(this.sh_sz[0]+this.sh_sz[1])+"px",top:"0px"}).html('<div class="xstr"><div class="xsmr"></div></div>');
	    jQuery(sh[2]).addClass("xsb").css({height:(this.sh_sz[0]+this.sh_sz[1])+"px",left:(-this.sh_sz[0])+"px"}).html('<div class="xsbl"><div class="xsbr"><div class="xsbc"></div></div></div>');
	    return sh;
	},
	shadow_resize: function(sh,w,h) {
	    jQuery(sh[0]).css({height:(h-this.sh_sz[1])+"px"});
	    jQuery(sh[1]).css({height:(h-this.sh_sz[1])+"px",left:(w-this.sh_sz[1])+"px"});
	    jQuery(sh[2]).css({width:(w+this.sh_sz[0]*2)+"px",top:(h-this.sh_sz[1])+"px"});
	},
	shadow_hide: function(sh) {
	    jQuery(sh[0]).add(sh[1]).add(sh[2]).hide();
	},
	shadow_show: function(sh) {
	    jQuery(sh[0]).add(sh[1]).add(sh[2]).show();
	},
	custButMargin: 5,
	wnd_init: function(o,wnd,title,align,inith,head,icon,resize,menu) {
		jQuery(wnd).addClass("xw-plain").addClass("x-unselectable");
	    if(resize) jQuery(wnd).addClass("xw-resize");
		var custbuts='';
		if(o.props.customButtons) for(var i in o.props.customButtons)
			custbuts+='<div class="xt xt-'+i+'"></div>';
	    jQuery(wnd).html(
		(head ? '<div class="xw-tl"><div class="xw-tr"><div class="xw-tc">'
+ '<div class="xw-sps"></div><div class="xw-hdr">'
+ '<div class="xt xt-close"></div><div class="xt xt-maxi"></div><div class="xt xt-rest"></div><div class="xt xt-mini"></div>'
+ custbuts
+ (icon ? '<img unselectable="on" onmousedown="return false;" class="xw-icon x-unselectable" src="'+icon+'">' : '')
+ '<span class="xw-hdr-text">'+title+'</span></div></div></div></div>' :
		'<div class="xw-tl"><div class="xw-tr"><div class="xw-tc xw-tsps"></div></div></div>')
+ '<div class="xw-ml"><div class="xw-mr"><div class="xw-mc">'
+ (menu ? '<div class="u-wndmenufr"><div class="u-wndmenu" style="position:relative"></div></div>' : '' )
+ '<div class="xw-body">'
+ '<div style="overflow:scroll;height:'+inith+'px">'
+ '<div class="myWinCont" style="display:none;overflow:hidden"'+(align ? ' align="'+align+'"' : '')+'></div><div class="'+o.props.markdisableclass+'" style="display:none;overflow:hidden;position:absolute;z-index:30000"></div><div class="myWinCont" style="overflow:hidden"'+(align ? ' align="'+align+'"' : '')+'></div></div></div></div></div></div>'
+ '<div class="xw-bl"><div class="xw-br"><div class="xw-bc"></div></div></div>'
+ '<div class="xw-bl" style="display:none"><div class="xw-br"><div class="xw-bcm"></div></div></div>'
+ '<div class="xw-blank" style="display:none"></div>'
	    );
	    var p={};
	    p.upper=jQuery(wnd).find(".xw-tl")[0];
	    p.center=jQuery(wnd).find(".xw-ml")[0];
	    p.bottom=jQuery(wnd).find(".xw-bl")[0];
	    p.bottomc=jQuery(wnd).find(".xw-bc")[1];
	    jQuery(wnd).find(".xw-mc").bind("mousedown",o,function(e){e.stopPropagation();e.data.activate(e);_uWnd.globalmousedown();});
	    p.markload=jQuery(wnd).find(".myWinCont")[0];
	    jQuery(p.markload).html(o.props.markload);
	    p.wndcont=jQuery(wnd).find(".myWinCont")[1];
	    p.markdis=jQuery(wnd).find("."+o.props.markdisableclass)[0];
	    jQuery(p.markdis).html(o.props.markdisablecont);
	    p.hwndcont=p.wndcont.parentNode;
	    if(head) {
		p.hdr=jQuery(wnd).find(".xw-hdr")[0];
		p.htitle=jQuery(wnd).find(".xw-hdr-text")[0];
		var buts={cbut:"xt-close",mbut:"xt-mini",xbut:"xt-maxi",rbut:"xt-rest",icon:"xw-icon"};
		for(var i in buts) {
		    p[i]=jQuery(p.hdr).find("."+buts[i])[0];
		}
		p.custom={};
		for(var i in o.props.customButtons) {
			p.custom[i]=jQuery(p.hdr).find(".xt-"+i)[0];
		}
	    } else {
		p.hdr=p.htitle=p.cbut=p.mbut=p.xbut=p.rbut=p.icon=null;
	    }
	    if(menu) p.menu=jQuery(wnd).find(".u-wndmenu")[0]; else p.menu=null;
	    jQuery(wnd).find("div,span").andSelf().attr("unselectable","on");
	    return p;
	},
	onstartautosz: function(o) {
//		o.parts.hwndcont.style.overflow="hidden";
		o.parts.wndcont.style.overflow="hidden";
		o.parts.wndcont.style.height="auto";
	},
	onstopautosz: function(o,onlyscroll) { //onlyscroll true to request restoration if sctool behaivor only
//		o.parts.hwndcont.style.overflowY="auto";
		if(!onlyscroll) o.parts.hwndcont.style.visibility="visible";
		o.parts.wndcont.style.overflow="auto";
		o.parts.wndcont.style.height="100%";
	},
	get_szbuts: function(wnd) {
	    var rs={nw:"xw-tl",n:"xw-sps",ne:"xw-tr",w:"xw-ml",e:"xw-mr",sw:"xw-bl",s:"xw-bc",se:"xw-br"};
	    for(var i in rs) {
			rs[i]=jQuery(wnd).find("."+rs[i])[0];
	    }
	    if(!rs.n) rs.n=jQuery(wnd).find(".xw-tsps")[0];
	    return rs;
	},
	onbuttonover: function(e) {
		var cls=e.data.cls;
		if(e.data.state)
	    	jQuery(this).addClass(cls+'-over');
	    else
	    	jQuery(this).removeClass(cls+'-over');
	},
	onstartdrag: function(o) {
	    if(jQuery.browser.msie) o.parts.upper.style.filter="Alpha(Opacity='70')";
		else o.parts.upper.style.opacity=0.7;
	    if(!o.state.minimized) {
		o.hideSh();
		jQuery(o.parts.center).add(o.parts.bottom).hide();
		jQuery(o.wnd).find(".xw-blank").css('width',o.width+'px').css('height',(o.height-o.decor.th)+'px').show();
	    }
	},
	onstopdrag: function(o) {
	    if(jQuery.browser.msie) o.parts.upper.style.filter="Alpha(Opacity='100')";
		else o.parts.upper.style.opacity=1;
	    if(!o.state.minimized) {
		o.showSh();
		jQuery(o.parts.center).add(o.parts.bottom).show();
		jQuery(o.wnd).find(".xw-blank").hide();
	    }
	},
	onactivate: function(o) {
		jQuery(o.wnd).addClass("xw-active");
	},
	ondeactivate: function(o) {
		jQuery(o.wnd).removeClass("xw-active");
	},
	onstartresize: function(o) {
	},
	onstopresize: function(o) {
	},
	onminimize: function(o) {
	    jQuery(o.parts.center).css("display","none");
	    jQuery(o.parts.bottomc).addClass("xw-bcm");
	    o.hideSh();
	},
	onrestore: function(o) {
	    jQuery(o.parts.bottomc).removeClass("xw-bcm");
	    jQuery(o.parts.center).css("display","block");
	    o.showSh();
	}
    }
};


_uWnd.prototype={
setZ:function(z) {
  with(this){
    zpos=z
    jQuery(top).css("z-index",z);
    if(grid)jQuery(grid).css("z-index",z-1);
  }
},
saveSession: function() { //return data sutable to restore window state
    var r;
    if(this.state.maximized || this.state.minimized) r=this.restRect;
        else r=[this.xpos,this.ypos,this.width,this.height];
    return {
                x:r[0],
                y:r[1],
                w:r[2]-this.decor.w,
                h:r[3]-this.decor.h,
                s:this.state.maximized ? 'max' : (this.state.minimized ? 'min' : '')
	};
},
moveTo:function(_x,_y,frominit) {
    var d=_uWnd.getdims();
  with(this) {
    if(_x=='auto' && _y=='auto' && desktop && !props.fixed && !props.autosize && !props.center) {
    	var p=desktop.getwndcoord(width,height);
    	_x=p.x;
    	_y=p.y;
    } else {
	    if(_x=='auto') {
			if(desktop && !props.fixed) _x=Math.floor((desktop.calcwidth()-width)/2);
				else _x=Math.floor((d.clientW-width)/2)+(props.fixed?0:d.clientLeft);
	    	if(_x<0) _x=0;
	    }
	    if(_y=='auto') {
			if(desktop && !props.fixed) _y=Math.floor((desktop.calcheight()-height)/2);
	    		else _y=Math.floor((d.clientH-height)/2)+(props.fixed?0:d.clientTop);
	    	if(_y<0) _y=0;
	    }
	}
    if(props.fixed && jQuery.browser.msie) jQuery(top).css("left",(d.clientLeft+_x)+'px').css("top",(d.clientTop+_y)+'px');
	else jQuery(top).css("left",_x+'px').css("top",_y+'px');
    if(grid)
	if(jQuery.browser.msie) jQuery(grid).css("left",d.clientLeft+'px').css("top",d.clientTop+'px');
	    else jQuery(grid).css("left",'0px').css("top",'0px');
    xpos=_x;
    ypos=_y;
    if(this.props.onposchange && !frominit) this.props.onposchange.apply(this.app,[this]);
  }
},
setTitle:function(t) {
    if(t!=null)this.title=t;
    if(!this.title)this.title='';
  with(this) {
    if(!props.header) return;
    var ts=width-decor.w,l;
    ts-=_countbuttonwidth();
    l=title.length;
    if(l*letsize>ts) l=Math.floor(ts/letsize)-2;
    if(l<title.length)
	jQuery(parts.htitle).attr("title",title).text(title.substr(0,l)+'...');
	else
	jQuery(parts.htitle).attr("title",'').text(title);
  }
},
resizeTo:function(w,h,center,frominit) {
  with(this) {
    if(center) {
        var d=_uWnd.getdims();
		var _x=xpos,_y=ypos;
	    if(props.x=='auto') {
			if(desktop && !props.fixed) _x=Math.floor((desktop.calcwidth()-w)/2);
				else _x=Math.floor((d.clientW-w)/2)+(props.fixed?0:d.clientLeft);
	    	if(_x<0) _x=0;
	    }
	    if(props.y=='auto') {
			if(desktop && !props.fixed) _y=Math.floor((desktop.calcheight()-h)/2);
	    		else _y=Math.floor((d.clientH-h)/2)+(props.fixed?0:d.clientTop);
	    	if(_y<0) _y=0;
	    }
		if(_x!=xpos | _y!=ypos) moveTo(_x,_y,1);
    }
    jQuery(wnd).css("width",w+'px');
    jQuery(parts.wndcont).css("width",(w-decor.w)+'px');
    jQuery(parts.hwndcont).css("height",(h-decor.h)+'px');
    if(parts.markdis) jQuery(parts.markdis).css({height:(h-decor.h)+'px',width:(w-decor.w)+'px'});

    if(menu) jQuery(parts.menu).css("width",(w-decor.w)+'px');

    if(tabctrl) tabctrl.resizeTo(w-decor.w,h-decor.h);
    if(frame) jQuery(frame).css("width",w+'px').css("height",h+'px');
    width=w;
    height=h;
    if(this.props.onposchange && !frominit && !this.state.maximized && !this.state.minimized) this.props.onposchange.apply(this.app,[this]);
    _resizeSh();

    setTitle();
  }
},
_onresize:function(d) {
    if(this.state.maximized)
		if(this.desktop && !this.props.fixed) {
		    this.moveTo(this.desktop.calcexclude(0),this.desktop.calcexclude(2),1);
	    	this.resizeTo(this.desktop.calcwidth(),this.desktop.calcheight(),0,1);
		} else this.resizeTo(d.clientW,d.clientH);
    if(this.grid) jQuery(this.grid).css("width",d.clientW+'px').css("height",d.clientH+'px');
},
_resizeSh:function() {
    if(this.sh)this.design.shadow_resize(this.sh,this.width,this.height);
},
hideSh:function() {
    if(this.sh)this.design.shadow_hide(this.sh);
},
showSh:function() {
    if(this.sh && !this.state.noshadow)this.design.shadow_show(this.sh);
},
shadow_init:function() {
    this.sh=this.design.shadow_init(this.top);
},
showcustombutton: function(name,state) {
	if(!this.props.customButtons[name]) return;
	this.props.customButtons[name][0]=state;
	if(!this.parts.custom[name]) return; //window not initted yet
	if(!state) jQuery(this.parts.custom[name]).css("display","none");
		else jQuery(this.parts.custom[name]).css("display","block");
},
init: function(menuitems) {
    var p=this.props,t=document.createElement("div"),w;
//top parent for window and optional shadow
	t.id="_uwndTop"+this.idx;
	t._uwndobj=this;
    if(!this.desktop) jQuery(jQuery("body")[0]).prepend(t);
    	else this.desktop.dsk.appendChild(t);
    this.top=t;
    if(!p.fixed || jQuery.browser.msie)	jQuery(t).css("position","absolute"); else jQuery(t).css("position","fixed");
    jQuery(t).css("visibility",'hidden').css("display",'block').css("z-index",this.zpos);
//grid for modal windows
    if (p.modal){
		var g=document.createElement("div"),d=_uWnd.getdims();
		jQuery(g).addClass('myWinGrid').css("width",d.clientW+'px').css("height",d.clientH+'px').css("z-index",this.zpos-1).hide().bind('mousedown',function(e){e.stopPropagation();e.preventDefault();_uWnd.globalmousedown();});
		if(jQuery.browser.msie)	jQuery(g).css("position","absolute"); else jQuery(g).css("position","fixed");
	    if(!this.desktop) jQuery(jQuery("body")[0]).prepend(g);
	    	else this.desktop.dsk.appendChild(g);
		this.grid=g;
    }
    if(jQuery.browser.msie && parseFloat(jQuery.browser.version)<7){
        this.frame=document.createElement("iframe");
        with(this.frame.style) {
            filter="Alpha(Opacity='0')";
            display="block";
            position="absolute";
//            zIndex=0;
            borderWidth=0;
            width=this.width+'px';
            height=this.height+'px';
        }
	t.appendChild(this.frame);
    }

    if(p.shadow && !(jQuery.browser.msie && parseFloat(jQuery.browser.version)<7)) {
		this.shadow_init();
		this._resizeSh();
    }
    this.moveTo(p.x,p.y,1);
//window
    w=document.createElement("div");
    w.id="_uwndWnd"+this.idx;
    t.appendChild(w);
    this.wnd=w;
    jQuery(w).css({position: "absolute",width: this.width+'px',zIndex:2,left:0});

	if(!_uWnd._activateonmousedown) _uWnd._activateonmousedown=function(e){e.stopPropagation();e.data.activate(e);_uWnd.globalmousedown();};
	if(!_uWnd._activateonmousedownign) _uWnd._activateonmousedownign=function(e){e.data.activate(e);_uWnd.globalmousedown();};
    this.parts=this.design.wnd_init(this,w,this.title,p.align,60,p.header,p.icon,p.resize,p.havemenu);
    if(p.header) {
		var bb={cbut:"xt-close",mbut:"xt-mini",xbut:"xt-maxi",rbut:"xt-rest"};
		if(!_uWnd._retfalse) _uWnd._retfalse=function(e){return false;};
		if(!_uWnd._onclickcustom) _uWnd._onclickcustom=function(e){var d=e.data;d.wnd.activate(e);d.func.call(d.thispar,d.wnd,d.name);};
		if(!_uWnd._onbuttonclose) _uWnd._onbuttonclose=function(e){e.data.activate(e);e.data.closeevent();};
		if(!_uWnd._onbuttonmin) _uWnd._onbuttonmin=function(e){e.data.activate(e);e.data.minimize()};
		if(!_uWnd._onbuttonmax) _uWnd._onbuttonmax=function(e){e.data.activate(e);e.data.maximize()};
		if(!_uWnd._onbuttonrest) _uWnd._onbuttonrest=function(e){e.data.activate(e);e.data.restore()};

		for(var i in bb)
		    jQuery(this.parts[i]).bind("dblclick",_uWnd._retfalse).bind("mouseover",{cls:bb[i],state:1},this.design.onbuttonover).bind("mouseout",{cls:bb[i],state:0},this.design.onbuttonover).bind("mousedown",this,_uWnd._activateonmousedown);

		for(var i in p.customButtons) {
		    jQuery(this.parts.custom[i]).bind("dblclick",_uWnd._retfalse).bind("mouseover",{cls:'xt-'+i,state:1},this.design.onbuttonover).bind("mouseout",{cls:'xt-'+i,state:0},this.design.onbuttonover).bind("mousedown",this,_uWnd._activateonmousedown);
			if(!p.customButtons[i][0]) jQuery(this.parts.custom[i]).css("display","none");
			if(p.customButtons[i][1]) jQuery(this.parts.custom[i]).bind("click",{wnd:this,name:i,func:p.customButtons[i][1],thispar:p.customButtons[i][2]},_uWnd._onclickcustom); //e.stopPropagation
		}

		if(!p.close) jQuery(this.parts.cbut).css("display","none");
		jQuery(this.parts.cbut).bind("click",this,_uWnd._onbuttonclose); //e.stopPropagation
		if(!p.min) jQuery(this.parts.mbut).css("display","none");
		jQuery(this.parts.mbut).bind("click",this,_uWnd._onbuttonmin); //e.stopPropagation
		if(!p.max) jQuery(this.parts.xbut).css("display","none");
		jQuery(this.parts.xbut).bind("click",this,_uWnd._onbuttonmax); //e.stopPropagation
		jQuery(this.parts.rbut).css("display","none").bind("click",this,_uWnd._onbuttonrest); //e.stopPropagation
		if(p.close && !p.min && !p.max && this.design.altcloseclass) {//use alternative class
			jQuery(this.parts.cbut).addClass(this.design.altcloseclass);
		}

		if(!p.nomove) jQuery(this.parts.hdr).addClass("xw-draggable");
		jQuery(this.parts.hdr).add(this.parts.htitle).bind("mousedown",this,function(e) {e.stopPropagation();e.data.activate(e);_uWnd.globalmousedown();return e.data._ondragmousedown(e);});
		if(p.max || p.min) jQuery(this.parts.hdr).bind("dblclick",this,function(e){var a=e.data;if(a.state.maximized || a.state.minimized)a.restore();else a.maximize();});
    }

    var rs=this.design.get_szbuts(w);
	if(!_uWnd._onresizebuttondown) _uWnd._onresizebuttondown=function(e){e.stopPropagation();e.data.w.activate(e);_uWnd.globalmousedown();return e.data.w._onrsmousedown(e,e.data.tp);};
    for(var i in rs) {
		jQuery(rs[i]).bind("mousedown",{w:this,tp:i},_uWnd._onresizebuttondown);
    }
    jQuery(this.parts.wndcont).bind("mousedown",this,_uWnd._activateonmousedown);
    jQuery(w).bind("mousedown",this,_uWnd._activateonmousedownign);
	if(p.havemenu) {
		var mopts=jQuery.extend({
				parentnode:this.parts.menu,
				wnd:this,
				noabs:1,
				horiz:1,
				static:1,
				width:'auto'
			},p.menuopts || {});
		this.menu=new _uMENU('',{},mopts,menuitems,true);
	}
    if(typeof this._content == 'object' && this._content.constructor==_uTabCtrl) {
    	this.tabctrl=this._content;
    	this.tabctrl.props.parentnode=this.parts.wndcont;
    	this.tabctrl.wnd=this;
    	this.tabctrl.init(true); //tab must be created with noinit property
    } else this.tabctrl=null;

	if(p.trayicon && this.desktop) {
		var to={};
		if(p.trayicon.contructor==String) to.img=p.trayicon;
			else if(p.trayicon.contructor!=Object) if(p.icon)to.img=p.icon;
		if(to.img) {
			if(!p.trayicon.thisobj) { //set standard handlers
				to.thisobj=this;
				if(!p.trayicon.ondown) to.ondown=this.ontrayicondown;
				if(!p.trayicon.onrdown) to.onrdown=this.ontrayiconrdown;
				to.param=p.trayicon.param;
			} else jQuery.extend(to,p.trayicon);
			if(!to.title) to.title=this.title || '';
			this.trayicon=this.desktop.addTrayIcon(to.img,to.title,to.thisobj,to.ondown,to.onclick,to.onrdown,to.param);
			if(p.traymenu) {
				this.traymenu=new _uMENU('',{align:'U'},{hidden:1},p.traymenu);
			}
		}
	}
    if(!p.hidden) this.show(false);
    if(this.desktop && !p.modal && !p.popup && !p.alert && p.header && !p.notaskbar) this.desktop._addwindow(this);
    if(!p.alert) this.activate();
    if(p.header || this.menu) setTimeout("var w=_uWnd.all["+this.idx+"];if(w)w.init1();",10);
	else setTimeout("var w=_uWnd.all["+this.idx+"];if(w)w.init2();",10);
},
init1: function() {
	if(this.props.header) {
  		if(!this.title) this.letsize=8;
    		else
  			with(this) {
    			if(title.length==0) letsize=8;
				else letsize=parts.htitle.offsetWidth/title.length;
    			parts.htitle.innerHTML='...';
  			}
  	}
	if(this.menu) this.menu.init1(true);
    setTimeout("var w=_uWnd.all["+this.idx+"];if(w)w.init2();",10);
},
init2: function() {
  with(this) {
	decor.sbw=parts.hwndcont.offsetWidth-parts.hwndcont.clientWidth;
	decor.sbh=parts.hwndcont.offsetHeight-parts.hwndcont.clientHeight;
    decor.w=width-_uWnd.csize(parts.wndcont,"width")-decor.sbw;
    decor.h=wnd.offsetHeight-60;
    decor.th=parts.upper.offsetHeight;
	parts.hwndcont.style.overflow='hidden';
	if(tabctrl)tabctrl.init1(true);
	if(props.session)
	    resizeTo(props.session.w+decor.w,props.session.h+decor.h,0,1);
		else
    	resizeTo(width,height,0,1);
	if(menu)menu._setsize();

    state.init=true;
	var rel=pend_show ? pend_show[0] : false;
    if(props.oninit) if(!props.oninit.call(app,this,name)) rel=false;
    jQuery(top).css("display",'none').css("visibility",'visible');
    var s=props.session;
    if(s && s.s=='min') minimize(1);
    	else if(s && s.s=='max') maximize(1);
    	else
    		if(pend_show) show(rel,pend_show[1],pend_show[2]);
  }
},
deactivate: function() {
    var o=this.desktop ? this.desktop : _uWnd;
	if(o.activewnd && o.activewnd==this) o.activewnd=null;
	this.design.ondeactivate(this);
	if(this.desktop)this.desktop._onwnddeactivate(this);
},
activate: function(e) {
    if(this.state.disabled) return;
    var o=this.desktop ? this.desktop : _uWnd;
	if(o.activewnd && o.activewnd!=this) o.activewnd.deactivate();
	o.activewnd=this;
	this.design.onactivate(this);
	if(this.desktop)this.desktop._onwndactivate(this);
	if(this.props.modal || this.props.alert) {
	    if(this.zpos==_uWnd.lastmodalz) return;
    	this.setZ(_uWnd.getModalTopZ());
	} else {
	    if(this.zpos==_uWnd.lastz) return;
    	this.setZ(_uWnd.getTopZ());
	}
},
ontrayicondown:function(anim,icon,e) {
	if(!this.state.visible && !this.state.minimized) if(anim) this.show(false); else this.show(false,0,0);
		else if(this.state.minimized) {
			if(this.state.beforemin=='max')this.maximize();
				else this.restore();
		} else if(this.props.min && !this.props.notaskbar) this.minimize();
			else if(anim) this.hide(); else this.hide(0,0);

},
ontrayiconrdown:function(pp,icon,e) {
	if(!this.traymenu) return;
	this.traymenu.show({pos:{x:e.pageX,y:e.pageY}});
	_uMENU.ignoreclick=this.traymenu;

},
show: function(rel,fadetp,fadesp) {
  if(arguments.length<2 || fadetp==undefined) fadetp=this.props.fadetype;
  if(arguments.length<3 || fadesp==undefined) fadesp=this.props.fadespeed;
  with(this) {
    if(!state.init) {pend_show=[rel,fadetp,fadesp];return;}
    if(grid) jQuery(grid).show();
    if(fadetp==1) {
		state.disabled=true;
		if(jQuery.browser.safari) hideSh();
		if(jQuery.browser.msie) {
		    state.noshadow=true;
		    hideSh();
	    	jQuery(wnd).hide();
	    	jQuery(top).show();
	    	jQuery(wnd).css("opacity","0").show().animate( {opacity: 1} , {duration:fadesp,complete:new Function("var w=_uWnd.all["+idx+"];if(w){w.state.noshadow=false;w.state.disabled=false;w.showSh();}")});
		} else jQuery(top).fadeIn(fadesp,new Function("var w=_uWnd.all["+idx+"];if(w)w.state.disabled=false;if(jQuery.browser.safari)w.showSh();"));
    } else if(fadetp==2) {
		state.disabled=true;
		var endy=parseInt(jQuery(top).css("top"));
		jQuery(top).css("top", (endy+(height>100 ? 100 : height))+'px');
		if(jQuery.browser.msie) {
		    state.noshadow=true;
		    hideSh();
		    jQuery(wnd).hide();
		    jQuery(top).show().animate( {top: endy+"px"} , {duration:fadesp,complete:new Function("var w=_uWnd.all["+idx+"];if(w){w.state.noshadow=false;w.state.disabled=false;w.showSh();}")});
		    jQuery(wnd).css("opacity","0").show().animate( {opacity: 1} , fadesp);
		} else jQuery(top).css("opacity","0").show().animate( {top: endy+"px", opacity: 1} , {duration:fadesp,complete:new Function("var w=_uWnd.all["+idx+"];if(w)w.state.disabled=false;")});
    } else {jQuery(top).show();state.disabled=false;}
    state.visible=true;
    if(!state.loaded || rel) load();
  }
},
hide: function(fadetp,fadesp,doclose) {
    if(arguments.length<1 || fadetp==undefined) fadetp=this.props.fadeclosetype;
    if(arguments.length<2 || fadesp==undefined) fadesp=this.props.fadeclosespeed;
    this.state.disabled=true;
    if(fadetp==1)
		if(jQuery.browser.msie) {
		    this.state.noshadow=true;
		    this.hideSh();
		    jQuery(this.wnd).animate( {opacity: 0} , {duration:fadesp,complete:doclose ? new Function("var w=_uWnd.all["+this.idx+"];if(w)w.close(true);") : null});
		} else jQuery(this.top).fadeOut(fadesp, doclose ? new Function("var w=_uWnd.all["+this.idx+"];if(w)w.close(true);") : null);
    else if(fadetp==2) {
		var endy=parseInt(jQuery(this.top).css("top"))+(this.height>100 ? 100 : this.height);
		if(jQuery.browser.msie) {
		    this.state.noshadow=true;
		    this.hideSh();
		    jQuery(this.top).animate( {top: endy+"px"} , {duration:fadesp,complete:doclose ? new Function("var w=_uWnd.all["+this.idx+"];if(w)w.close(true);") : null});
		    jQuery(this.wnd).animate( {opacity: 0} , fadesp);
		} else jQuery(this.top).animate( {top: endy+"px", opacity: 0} , {duration:fadesp,complete:doclose ? new Function("var w=_uWnd.all["+this.idx+"];if(w)w.close(true);") : null});
    }
    else {jQuery(this.top).hide();doclose=false;}
    if(this.grid) jQuery(this.grid).hide();
    this.state.visible=false;
	_uWnd.activatetopwnd(this.desktop);
    if(doclose)return 1;
    return 0;
},
markload: function() {
    this.parts.wndcont.style.display='none';
    this.parts.markload.style.display='block';
},
showgrid: function() {
	if(this.parts.markdis) this.parts.markdis.style.display='block';
},
hidegrid: function() {
	if(this.parts.markdis) this.parts.markdis.style.display='none';
},
reload: function(c) {
    this._content=c;
    if(typeof c == 'object' && c.constructor==_uTabCtrl)
    	this.tabctrl=c;
    	else
    	this.tabctrl=null;
    this.state.loaded=false;
    this.state.disabled=false;
    this.load();
    if(!this.props.hidden && !this.state.visible) this.show(false);
},
load: function() {
	if(this.tabctrl) return;
    var c=this._content;
	if(typeof (c) == 'string') this.content(c);
    else if(typeof c == 'function') this.content(c.apply(this.app,[]));
    else if(typeof c == 'object') {
	this.markload();
	if(!c.success && c.xml===false) {c.dataType='text';c.success=new Function("data","st","var w=_uWnd.all["+this.idx+"];if(w)w.content(data);");}
	    else if(!c.success && c.xml!==false) c.success=new Function("data","st","var w=_uWnd.all["+this.idx+"];_uParseXML(data,w);");
	if(!c.error) c.error=new Function("xml","st","er","var w=_uWnd.all["+this.idx+"];if(w)w._onerror(xml,st,er);");
	try {
	if(c.form && c.form.length>0) //have form
	    _uPostForm(c.form,c);
	    else if(c.url) _uAjaxRequest(c.url,c);
	} catch(e) {this._onerror(null,'',e);}
    }
},
_onerror: function(xml,st,er) {
    var o=this.props.onerror;
    if(o && typeof(o)=='function') o.apply(this,arguments);
	else this.close();
},
_checkimgload: function(load) {
	var im=this.imgloader;
	var i;
	if(!im.active) return;
	if(load) im.count++;
	if(im.images) for(i=0;i<im.images.length;i++)	if(!im.images[i].complete) break;
	if(i>=im.images.length){this._stopimgload(true);return;}

	if(im.count>=im.images.length) { //after some events complete was not updated
		if(im.timer) clearTimeout(im.timer);
    	im.timer=setTimeout("var w=_uWnd.all["+this.idx+"];if(w){w.imgloader.timer=null;w._checkimgload();}",100);
	}
	if(jQuery.browser.opera && im.images2) {
		for(i=0;i<im.images2.length;i++) if(!im.images2[i].complete) return;
		jQuery(im.images2).unbind();
		im.images2=null;
		this.parts.hwndcont.style.visibility='hidden';
    	this.parts.markload.style.display='none';
    	jQuery(this.parts.wndcont).css("display","block");
	}
},
_stopimgload: function(start) {
	var im=this.imgloader;
	if(im.active) {
		im.active=false;
		if(im.stoptimer) {clearTimeout(im.stoptimer);im.stoptimer=null;}
		if(im.timer) {clearTimeout(im.timer);im.timer=null;}
		if(im.images) {im.images.unbind();im.images=null;}
		if(im.images2) {jQuery(im.images2).unbind();im.images2=null;}

		if(start) {
			if(this.props.hideonresize) this.parts.hwndcont.style.visibility='hidden';
    		this.parts.markload.style.display='none';
    		jQuery(this.parts.wndcont).css("display","block");
	    	this.autosz.load=true;
	    	this.delaychecksize();
	    }
	}
},
content: function(c) {
	this._stopimgload();
	this.stopautosize();
    var a=this.autosz,w=this.parts.wndcont,p=this.props,im=this.imgloader;

    this.state.loaded=true;
	if(p.autosize && p.waitimages>0) { //hide content until all images are loaded
		this.markload();
    	jQuery(w).html(c);
	    if(this.props.oncontent) this.props.oncontent(this,w);

    	im.active=true;
		im.stoptimer=setTimeout("var w=_uWnd.all["+this.idx+"];if(w)w._stopimgload(true);",p.waitimages);
		if(!_uWnd.waitimagesfunc) _uWnd.waitimagesfunc=function(e) {
				var im=e.data.imgloader;
				if(im.timer) clearTimeout(im.timer);
		    	im.timer=setTimeout("var w=_uWnd.all["+e.data.idx+"];if(w){w.imgloader.timer=null;w._checkimgload(1);}",10);
		    	};
		im.count=0;
    	im.images=jQuery(w).find("img").bind('error',this,_uWnd.waitimagesfunc).bind('load',this,_uWnd.waitimagesfunc);
		if(jQuery.browser.opera && im.images.length>0) { //opera does not preload hidden images
			im.images2=[];
			for(var i=0;i<im.images.length;i++) im.images2[i]=jQuery("<img>").attr("src",im.images[i].src).bind('load',this,_uWnd.waitimagesfunc)[0];
		}
    	this._checkimgload();
	} else {
		if(p.autosize && p.hideonresize)this.parts.hwndcont.style.visibility='hidden';
    	this.parts.markload.style.display='none';
    	jQuery(w).css("display","block").html(c);
	    if(this.props.oncontent) this.props.oncontent(this,w);
	    a.load=true;
	    if(p.autosize)this.delaychecksize();
	    	else this.design.onstopautosz(this);
    }

},
onexternalload: function() {
	this._stopimgload();
	this.stopautosize();

    this.state.loaded=true;
    this.autosz.load=true;
    if(this.props.autosize)this.delaychecksize();

},
stopautosize: function() {
	var a=this.autosz;
	if(a.inittimer) {clearTimeout(a.inittimer);a.inittimer=null;}
	if(a.timer){clearTimeout(a.timer);a.timer=null;}
	if(a.images) {jQuery(a.images).unbind();a.images=null;}
	if(a.active)this.design.onstopautosz(this);
	a.active=false;
},
delaychecksize: function(d) { //true if called due to autosizeonimages, delay
	d=d || 10;
	var a=this.autosz;
	if(a.inittimer) clearTimeout(a.inittimer);
    a.inittimer=setTimeout("var w=_uWnd.all["+this.idx+"];if(w);w.checksize();",d);

},
_countbuttonwidth: function() {
	var w=0;
	var buts={cbut:1,mbut:1,xbut:1,rbut:1,icon:1};
	for(var i in buts) if(this.parts[i])w+=this.parts[i].offsetWidth;
	for(var i in this.props.customButtons) w+=this.parts.custom[i].offsetWidth+this.design.custButMargin;
	return w;
},
checksize: function(autoload) { //true if called due to autosizeonimages
    var a=this.autosz,w=this.parts.wndcont;
	a.inittimer=null;
    if(this.state.maximized || this.state.minimized) return;
    this.stopdrag();
    this.stopresize();
    if(a.load) {
		a.load=false;
		if(a.images) {jQuery(a.images).unbind();a.images=null;}
		if(this.props.autosizeonimages) {
			if(!_uWnd.autosizeonimagesfunc) _uWnd.autosizeonimagesfunc=function(e) {e.data.delaychecksize();};
			a.images=jQuery(w).find("img").bind('load',this,_uWnd.autosizeonimagesfunc);
		}
    }
    a.active=true;
	this.design.onstartautosz(this);
	if(a.timer){clearTimeout(a.timer);a.timer=null;}

    var d=_uWnd.getdims(),minw=10,minh=10,maxw,maxh;
    if(this.props.header) {
		minw+=this._countbuttonwidth();
    }
    minw=Math.max(minw,this.minwidth);
    minh=Math.max(minh,this.minheight);
    maxw=this.maxwidth;
    if(maxw==0) maxw=d.clientW-this.decor.w;
    maxh=this.maxheight;
    if(maxh==0) maxh=d.clientH-this.decor.h;

    var contW,contH; //scrollwidth and height
	if(this.props.autosizewidth) {
		jQuery(this.parts.wndcont).css("width",'10px');
		contW=w.scrollWidth;
		jQuery(this.parts.wndcont).css({width:(this.width-this.decor.w)+'px'});
	} else contW=w.scrollWidth;
    contH=w.scrollHeight;
//    a.tw=Math.min(Math.max(w.scrollWidth+scrW,w.offsetWidth,minw),maxw);
//    a.th=Math.min(Math.max(w.scrollHeight+scrH,w.clientHeight ? w.clientHeight : w.offsetHeight,minh),maxh);
	a.tw=Math.max(contW,minw);
	a.th=Math.max(contH,minh);
	var havescroll=false;
	if(a.tw>maxw) {a.tw=maxw;a.th+=this.decor.sbh;havescroll=true;}
	if(a.th>maxh) {
		a.th=maxh;
		if(a.tw+this.decor.sbw<=maxw) {a.tw+=this.decor.sbw;havescroll=true;}
			else a.tw=maxw;
		}
	if(havescroll) this.design.onstopautosz(this,true); //to enable scrolls during resize

    a.timer=setTimeout("try{_uWnd.all["+this.idx+"]._checksize();}catch(e){}",10);
},
_checksize: function() {
    this.stopdrag();
    this.stopresize();
    var a=this.autosz, dw=a.tw-(this.width-this.decor.w), dh=a.th-(this.height-this.decor.h),ws=10,hs=10;
    if(dw!=0) {
		if(dw>0) ws=Math.min(ws,dw);
	    	else if(dw<0) ws=Math.max(-ws,dw);
		this.resizeTo(this.width+ws,this.height,true,1);
    } else if(dh!=0) {
		if(dh>0) hs=Math.min(hs,dh);
	    	else if(dh<0) hs=Math.max(-hs,dh);
		this.resizeTo(this.width,this.height+hs,true,1);
    } else {
    	a.timer=null;
    	a.active=false;
//		if(this.props.hideonresize)
		this.design.onstopautosz(this);
    	return;
    }
    a.timer=setTimeout("try{_uWnd.all["+this.idx+"]._checksize();}catch(e){}",10);
},
closeevent: function() { //close event from user. insertion point for overrides
	if(this.props.onbeforeclose) if(this.props.onbeforeclose.apply(this.app,[this])) return;
	this.close(); //default action
},
close: function(nohide) {
	if(this.state.destroyed) return;
	if(this.desktop) this.desktop._removewindow(this);
    if(!nohide && this.state.visible) {
    	var a=this.hide(this.props.fadeclosetype,this.props.fadeclosespeed,true);
    	if(a==1) return;
    }
    this.top.parentNode.removeChild(this.top);
    if(this.grid) this.grid.parentNode.removeChild(this.grid);
	if(this.tabctrl && !this.props.notabdestroy) this.tabctrl.destroy();
    _uWnd.all[this.idx]=null;
    this.state.destroyed=true;
    this.state.visible=false;
    if(this.props.onclose) this.props.onclose.apply(this.app,[this,this.idx]);
	if(this.app) this.app._ondestroywnd(this);
//	delete this;
},
minimize: function(frominit) {
  with(this) {
    if(autosz.active || !props.min || !props.header || props.modal || props.alert || props.popup) return;
    state.beforemin=state.maximized ? 'max' : '';
    stopdrag();
    stopresize();
    if(!state.maximized && !state.minimized) restRect=[xpos,ypos,width,height,props.fixed];
    if(props.onposchange && !state.minimized && !frominit) props.onposchange.apply(app,[this]);
    state.maximized=false;
    state.minimized=true;
	this.deactivate();
	if(!frominit) _uWnd.activatetopwnd(this.desktop);

    if(!desktop) {
	   	jQuery(parts.mbut).css("display","none");
	   	if(props.max)jQuery(parts.xbut).css("display","block");
	   	jQuery(parts.rbut).css("display","block");
	   	jQuery(wnd).removeClass("xw-resize");

    	if(!props.fixed && !jQuery.browser.msie) jQuery(top).css("position","fixed");
	    design.onminimize(this);
	    props.fixed=true;
	    moveTo(0,0,1);
	    resizeTo(200,30,0,1);
	} else {
		if(!frominit) {
			hide(0);
			desktop._onwndminimize(this,xpos,ypos,width,height);
		}
	}
  }
},
maximize: function(frominit) {
  with(this) {
    if(autosz.active || !props.max || !props.header) return;
    stopdrag();
    stopresize();
    if(!state.maximized && !state.minimized) restRect=[xpos,ypos,width,height,props.fixed];
    if(state.minimized) {this.design.onrestore(this);if(desktop)show(false,0);}
    if(props.onposchange && !state.maximized && !frominit) props.onposchange.apply(app,[this]);
    state.maximized=true;
    state.minimized=false;

    jQuery(parts.hdr).removeClass("xw-draggable");
    jQuery(wnd).removeClass("xw-resize");
    jQuery(parts.xbut).css("display","none");
    if(props.min)jQuery(parts.mbut).css("display","block");
    jQuery(parts.rbut).css("display","block");
    if(!desktop && !props.fixed && !jQuery.browser.msie) jQuery(top).css("position","fixed");

    hideSh();
	if(desktop && !props.fixed) {
	    moveTo(desktop.calcexclude(0),desktop.calcexclude(2),1);
	    resizeTo(desktop.calcwidth(),desktop.calcheight(),0,1);
	} else  {
	    var d=_uWnd.getdims();
	    props.fixed=true;
	    moveTo(0,0,1);
	    resizeTo(d.clientW,d.clientH,0,1);
	}
	if(frominit) {show(false,0);}
  }
},
restore: function() {
  with(this) {
    if(!props.header) return;
    stopdrag();
    stopresize();
    if(this.props.onposchange && (state.minimized || state.maximized)) props.onposchange.apply(app,[this]);

    jQuery(parts.rbut).css("display","none");
    if(state.maximized) jQuery(parts.xbut).css("display","block");
    if(state.minimized) jQuery(parts.mbut).css("display","block");
    if(!props.nomove)jQuery(parts.hdr).addClass("xw-draggable");
    if(props.resize)jQuery(wnd).addClass("xw-resize");

    if(!desktop) {
	    if(state.minimized) design.onrestore(this);
	} else {
		if(state.minimized) show(false,0);
//		desktop.onwndrestore(this);
	}
    showSh();
    state.maximized=state.minimized=false;
    var r=restRect;
    if(r) {
		props.fixed=r[4];
		if(!props.fixed && !jQuery.browser.msie) jQuery(top).css("position","absolute");
		moveTo(r[0],r[1],1);
		resizeTo(r[2],r[3],0,1);
    }
  }
},
_ondragmousemove: function(dx,dy,x,y) {
    var d=_uWnd.getdims();
	x+=dx;
	y+=dy;
    if(x+this.width<30) x=30-this.width;
    if(y<-5) y=-5;
	if(this.desktop && !this.props.fixed) {
	if(x>this.desktop.width-20) x=this.desktop.width-20;
	if(y>this.desktop.height-20) y=this.desktop.height-20;
	} else if(this.props.fixed) {
	if(x>d.clientW-20) x=d.clientW-20;
	if(y>d.clientH-20) y=d.clientH-20;
    } else {
	if(x>d.docW-20) x=d.docW-20;
	if(y>d.docH-20) y=d.docH-20;
    }
    this.moveTo(x,y);
},
onstartdrag: function() {
	this.design.onstartdrag(this);
},
onstopdrag: function() {
	this.design.onstopdrag(this);
},
_ondragmousedown: function(e) {
  with(this){
    if(props.nomove || state.resizing || state.maximized || state.disabled || e.which!=1) return;
	_drag.start(e,xpos,ypos);
    props.x=xpos;
    props.y=ypos;
  }
},
stopdrag: function() {
	this._drag.stop();
},
_onrsmousemove: function(dx,dy,tx,ty,tw,th,m) {
    var x,y,w,h,d=_uWnd.getdims(),minw=10,minh=10,maxw,maxh;
    x=tx;
    y=ty;
    w=tw;
    h=th;
    if(this.props.header) {
		minw+=this._countbuttonwidth();
    }
    minw=Math.max(minw,this.minwidth)+this.decor.w;
    minh=Math.max(minh,this.minheight)+this.decor.h;
    maxw=this.maxwidth;
    if(maxw==0) maxw=d.clientW; else maxw+=this.decor.w;
    maxh=this.maxheight;
    if(maxh==0) maxh=d.clientH; else maxh+=this.decor.h;
//	self.status=minw;
    if(m.indexOf('n')>=0){
	y=ty+dy;
	if(y<0) y=0;
	h=ty+th-y;
	if(h<minh) {h=minh;y=ty+th-h;}
	    else if(h>maxh) {h=maxh;y=ty+th-h;}
    }
    if(m.indexOf('s')>=0){
	h=th+dy;
	if(h<minh) h=minh;
	    else if(h>maxh) h=maxh;
    }
    if(m.indexOf('w')>=0){
	x=tx+dx;
	if(x<0) x=0;
	w=tx+tw-x;
	if(w<minw) {w=minw;x=tx+tw-w;}
	    else if(w>maxw) {w=maxw;x=tx+tw-w;}
    }
    if(m.indexOf('e')>=0){
	w=tw+dx;
	if(w<minw) w=minw;
	    else if(w>maxw) w=maxw;
    }
    this.moveTo(x,y);
    this.resizeTo(w,h);
},
_onrsmousedown: function(e,b) {
  with(this) {
    if(_drag.active || state.disabled || state.maximized || state.minimized ||
	autosz.active || !props.resize || e.which!=1) return;
    props.x=xpos;
    props.y=ypos;
	this.stopautosize();
	_resize.start(e,xpos,ypos,width,height,b);
  }
},
onstartrs: function() {
	this.design.onstartresize(this);
},
onstoprs: function() {
	this.design.onstopresize(this);
},
stopresize: function() {
	this._resize.stop();
}

};

function _txt(sign) {
		var lng=window._uDeflang,a,p=arguments;
		if(!lng) a=sign;
			else {
				var db=window._uSigns;
				if(!db || !db[lng])a=sign;
					else {
						if(sign in db[lng]) a=db[lng][sign];
							else a=sign;
					}
			}
		function _txtproc(str,param) {
			return p[param];
		}

		if(p.length>1) {
			a=a.replace(/%([1-9])/g,_txtproc);
		}
		return a;
}

function _uColorBox(did,fid){
	var hex_Red=new Array("00","33","66","99","CC","FF");
	var hex_Green=new Array("00","33","66","99","CC","FF");
	var hex_Blue=new Array("00","33","66","99","CC","FF");
	var hex_Gray=new Array("909090","939393","969696","999999","9C9C9C","9F9F9F","C0C0C0","C3C3C3","C6C6C6","C9C9C9","CCCCCC","CFCFF","F0F0F0","F3F3F3","F6F6F6","F9F9F9","FCFCFC","FFFFFF");
	var hexred="00", hexgreen="00", hexblue="00", hexgray="00";
	var red=0, green=0, blue=0;
	var x=0, y=0, z=0;
	var xyz=0;
	var ctable='<table border="0" cellpadding="0" cellspacing="1" bgcolor="#000000">';
	while (y<6){
		ctable+='<tr>';
		var x=0;
		var hexblue=hex_Blue[blue];
		while (x<6){
			var z=0;
			var hexgreen=hex_Green[green];
			while (z<6){
				var hexred=hex_Red[red];
				var hexadecimal=""+hexred+hexgreen+hexblue;
				ctable+='<td style="width:8px;height:8px;cursor:pointer;" onclick="jQuery(\'#'+did+'\').hide(); getElementById(\''+fid+'\').value=\''+hexadecimal+'\'" bgcolor="'+hexadecimal+'"></td>';
				z++;red++;
				if (red==6){red=0;}
			}
			x++;green++;
			if (green==6)green=0;
			xyz++;
			if (xyz==3){ctable+='</tr>'; xyz=0;}
		}
		y++; blue++
		if (blue==6)blue=0;
	}
	for (var i=0;i<hex_Gray.length;i++){
		ctable+='<td style="width:8px;height:8px;cursor:pointer;" onclick="jQuery(\'#'+did+'\').hide(); getElementById(\''+fid+'\').value=\''+hex_Gray[i]+'\'" bgcolor="'+hex_Gray[i]+'"></td>';
	}
	ctable+='</table>';
	jQuery('#'+did).html(ctable);
}

//ucoz specific
//wnd can be _uWnd _uTabCtrl or _uApp
function _uParseXML(xml,wnd,tabid) {xml = xml.documentElement;
var tabctrl=null,app=null;

if(typeof wnd=='object' && wnd.constructor==_uTabCtrl) {tabctrl=wnd;wnd=null;}
	else if(typeof _uApp!='undefined' && typeof wnd=='object' && wnd.appname) {app=wnd;wnd=null;}

if (xml == null) { alert("Server connection Error. Sorry."); }
for (var i = 0; i < xml.childNodes.length; i++) {
if (xml.childNodes[i].nodeName == "cmd"){ var cmd=''; var target=''; var data;
for (var j=0; j<xml.childNodes[i].attributes.length; j++) {
if (xml.childNodes[i].attributes[j].name == "p")cmd = xml.childNodes[i].attributes[j].value;
if (xml.childNodes[i].attributes[j].name == "t")target = xml.childNodes[i].attributes[j].value;}
if (xml.childNodes[i].firstChild && xml.childNodes[i].firstChild.data ) data = xml.childNodes[i].firstChild.data; else data = '';
if (cmd=='innerHTML' && target.match(/^layerContent(.+)/)) _uWnd.content(RegExp.jQuery1,data);
if (cmd=='innerHTML' && target.match(/^layerTitle(.+)/)) _uWnd.setTitle(RegExp.jQuery1,data);
if (cmd=='innerHTML') jQuery('#'+target).html(data);
else if (cmd=='+innerHTML') jQuery('#'+target).prepend(data);
else if (cmd=='innerHTML+') jQuery('#'+target).append(data);
else if (cmd=='innerHTMLspanAll') jQuery("span."+target).html(data);
else if (cmd=='innerHTMLdivAll') jQuery("div."+target).html(data);
else if (cmd=='value') jQuery('#'+target).val(data);
else if (cmd=='jsa') includeJSfile(data,target);
else if (cmd=='js') eval(data);
else if (cmd=='content' && target.length>0) {
	var r=target.match(/^([^:]+):(.+)/);
	if(r) _uTabCtrl.content(r[1],r[2],data);
	else _uWnd.content(target,data);
}
else if (cmd=='title' && target.length>0) {
	var r=target.match(/^([^:]+):(.+)/);
	if(r) _uTabCtrl.setTitle(r[1],r[2],data);
	else _uWnd.setTitle(target,data);
}
else if (cmd=='close' && target.length>0) {
	var r=target.match(/^([^:]+):(.+)/);
	if(r)
		if(!data || parseInt(data)==NaN)_uTabCtrl.closeTab(r[1],r[2]);else setTimeout("_uTabCtrl.closeTab('"+r[1]+"','"+r[2]+"');",parseInt(data));
	else
		if(!data || parseInt(data)==NaN)_uWnd.close(target);else setTimeout("_uWnd.close('"+target+"');",parseInt(data));
}
else if(wnd) {
    if(cmd=='content') wnd.content(data);
    else if(cmd=='title') wnd.setTitle(data);
    else if(cmd=='close') if(!data || parseInt(data)==NaN)wnd.close();else setTimeout("var w=_uWnd.all["+wnd.idx+"];if(w)w.close();",parseInt(data));
    }
else if(tabctrl && tabid) {
    if(cmd=='content') tabctrl.content(tabid,data);
    else if(cmd=='title') {tabctrl.setTitle(tabid,data);}
    else if(cmd=='close') if(!data || parseInt(data)==NaN)tabctrl.closeTab(tabid);else setTimeout("var w=_uTabCtrl.all["+tabctrl.idx+"];if(w)w.closeTab('"+tabid+"');",parseInt(data));
    }
}}
}

var _defAjaxError=function(xmlreq, status, err) {
//this - options for request
//typically only one of status or err (exception) will have info
	try {
		_show_log_form();return;
	} catch(e){}
	window.location.reload();
}
var _hookAjaxError=null; //function(xmlreq, status, err)
//this - options for request

function _uAjaxRequest(url,options) {
    if(!url) return null;
    var o = jQuery.extend({
//noerrorhook:1   - can be used to prevent error hook from being used
		app: 0, //application PID
		async: 1,
		cache: true,
		dataType: 'xml',
		error: _defAjaxError,
	    type: 'GET',
		success: _defAjaxSuccess,
		timeout: 25000
// 		data: {f1: val1, f2: val2, f3: [val4,val5]}
    }, options || {});
    if(_hookAjaxError && !o.noerrorhook) {o.prev_error=o.error;o.error=_hookAjaxError;}
    o.url=url;
//    if(o.app>0 && !o.nosuccesshook) {o.prev_success=o.success;o.success=_hookAjaxSuccess;}
    return jQuery.ajax(o);
}
//by default use app in options
var _hookAjaxSuccess=function(data, status) {
	if(!this.prev_success) return;
	if(this.app>0 && typeof _uApp!='undefined' && _uApp.all[this.app] && !_uApp.all[this.app].exited && this.prev_success!=_defAjaxSuccess) this.prev_success.call(_uApp.all[this.app],data,status);
		else this.prev_success.call(this,data,status);
};

//by default call _uParseXML for xml reply
var _defAjaxSuccess=function(data, status) {
//this - options for request
	if(this.dataType=='xml') {
		if(this.app>0 && typeof _uApp!='undefined' && _uApp.all[this.app] && !_uApp.all[this.app].exited)
			_uParseXML(data,_uApp.all[this.app]);
			else
			_uParseXML(data);
	}
}


//by default try to find onerror attribute and execute it
var _defAjaxFormError=function(xmlreq, status, err) {
//this - options for request
//typically only one of status or err (exception) will have info
	if(!this._formobj) return;
	var a=this._formobj.onerror || this._formobj.getAttribute('onerror');
	if(!a) return;
	if(typeof a == 'string') {
		try {a=new Function(a);} catch(e){return;}
	}
	if(typeof a == 'function' || typeof a=='object') {
		try {a.call(this._formobj,xmlreq, status, err);} catch(e){return;}
	}
}

function _uPostForm(formid,options) {
    if(!formid && options && options.url) { _uAjaxRequest(options.url,options);return;}
    var f;
    if(typeof(formid)!='object') f=jQuery('#'+formid); else f=jQuery(formid);
    if(!f.length) return;
    var o = jQuery.extend({
//noerrorhook:1   - can be used to prevent error hook from being used
		app: 0, //pid of application
		url: f.attr('action') || window.location.toString(),
		type: f.attr('method') || 'GET',
		error: _defAjaxFormError,
		success: _defAjaxSuccess,
		dataType: 'xml',
		semantic: false //true if form contains type=image
    }, options || {});
    if(_hookAjaxError && !o.noerrorhook) {o.prev_error=o.error;o.error=_hookAjaxError;}
    o._formobj=f[0];
    if(o.app>0 && !o.nosuccesshook) {o.prev_success=o.success;o.success=_hookAjaxSuccess;}
    f.ajaxSubmit(o);
}


function includeJSfile(src,id){
if (id && document.getElementById(id)){return;}
var js = document.createElement('script');
js.setAttribute('type','text/javascript');
if(id) js.setAttribute('id',id);
js.setAttribute('src',src);
document.getElementsByTagName('head').item(0).appendChild(js);
}


var _entrRm={};
function _entrRem(bID,u,imgurl,text){
    if (!text){text='Are you sure?';}
    if (!_entrRm[bID] && confirm(text)){_entrRm[bID]=1;
	document.getElementById(bID).src=imgurl+'/img/fr/EmnAjax.gif';
	_uPostForm('',{url:u});
    }
}


function _coloredTDs(r,c){
    var cl='';
    if (typeof(r)!='object'){r=document.getElementById(r);}
    if (typeof(document.getElementsByTagName)!='undefined'){cl=r.getElementsByTagName('td');}
    else if (typeof(r.cells)!='undefined') {cl=r.cells;}
    else {return false;}
    for (var i=0;i<cl.length;i++) {
	cl[i].className=c;
    }
}

function openLayerB(n,f,url,t,w,h,resize,anyVar2,grid,multypart,align){
    new _uWnd(n,t,w,h,{autosize: resize ? 1 : 0,modal: grid ? 1 : 0,align:align ? align : 'center'},{url:url,form:f,cache:1});
}

function _showOnTop(n,f){
	var z=_uWnd.getTopZ();
        if (f){
                document.getElementById(n).style.zIndex=z+1;
        }
        else {
                document.getElementById('outLayer'+n).style.zIndex=z+1;
        }
}

function encodeHtmlVal(s) {
	return String(s).replace(/&/g,'&'+'amp;').replace(/'/g,'&'+'#39;').replace(/"/g,'&'+'quot;').replace(/</g,'&'+'lt;').replace(/>/g,'&'+'gt;');
}

//recursively dump SIMPLE objects  (numbers, strings, bool, simple arrays, simple objects)
function dumpObject(o,depth,ex) {
	var tp=typeof o,s;
	if(arguments.length<2) depth=10;
	function hexencode(n,s) {
		var j,d=[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'],v='';
		for(j=0;j<s;j++) {v=''+d[n%16]+v;n>>>=4;}
		return v;
	}
	if(tp=='object')
		if(!o) tp='null';
		else if (o.constructor==String) tp='string';
		else if (o.constructor==Number) tp='number';
		else if (o.constructor==Boolean) tp='boolean';
		else if (o.constructor==Array) tp='array';
	switch(tp) {
		case 'number': case 'boolean': case 'null': case 'undefined': return String(o);
		case 'string':
			return '"'+o.replace(/([\\"])/g,"\\jQuery1").
				replace(/\n/g,"\\n").
				replace(/([\x00-\x1f])/g,function(s,c){return '\\x'+hexencode(c.charCodeAt(0),2);}).
				replace(/([\u2028\u2029])/g,function(s,c){return '\\u'+hexencode(c.charCodeAt(0),4);})+'"';
		case 'array':
			if(depth<=0) return '[?]';
			s='';
			for(var i=0;i<o.length;i++) {
				if(i>0) s+=',';
				s+=dumpObject(o[i]);
			}
			return '['+s+']';
		case 'object':
			if(depth<=0) return '{?}';
			s='';
			for(var i in o) {
				if(ex && ex[i]) continue;
				if(s) s+=',';
				try {
				s+=dumpObject(i)+':'+dumpObject(o[i],depth-1);
				} catch(e) {s+=dumpObject(i)+':?';}
			}
			return '{'+s+'}';
	}
}

function _uHighlightA(parent,url,hlclass) {
	var ls=jQuery(parent).find("a").get(),o=null,l=0;
	for(var j in ls) {
		if (ls[j].href && url.indexOf(ls[j].href)>=0) {
			if (!o || l<ls[j].href.length){
				o=ls[j];
				l=ls[j].href.length;
			}
		}
	}
	if(o) jQuery(o).addClass(hlclass);
}
function _uBuildMenu(id,ishoriz,hlurl,hlclass,alignclass,hidetm){
		var p,i,subs,m,al,t,it,f;
		p=jQuery(id)[0];
		if(!p) return;
		hidetm=hidetm || 2000;
		f=function(e){_uMENU.hideallmenus();this.__umenu.show();};
		if(jQuery.browser.msie) p.style.zoom='1';
		subs=jQuery(id + ">ul").children("li").children("ul");
		for(i=0;i<subs.length;i++) {
			m=_ubuild_submenus(subs[i]);
			al=it=subs[i].parentNode;
			if(!ishoriz && alignclass && (t=jQuery(al).children("."+alignclass)[0]) )al=t;
			it.__umenu=new _uMENU('',{alignObj:al,align:ishoriz ? 'D' : (window._rtl ? 'L' : 'R')},{parentnode:p,hidetimer:hidetm},m);
			jQuery(it).bind("mouseover",f);
			it.removeChild(subs[i]);
		}
		if(!hlurl || !hlclass) return;
		setTimeout("_uHighlightA(jQuery('"+id+"')[0],'"+hlurl+"','"+hlclass+"');",100);
	}

function _uReplaceMenu(id,ishoriz,hlurl,hlclass,removeclass){
		var p,m,mm;
		p=jQuery(id)[0];
		if(!p) return;
		if(jQuery.browser.msie) p.style.zoom='1';
		mm=jQuery(id).children("ul")[0];
		if(!mm) return;
		if(removeclass)jQuery(mm).find("."+removeclass).remove();
		m=_ubuild_submenus(mm);
		mm.parentNode.__umenu=new _uMENU('',{},{width:'auto',horiz: ishoriz, static:1,parentnode:p,noabs:1},m);
		mm.parentNode.removeChild(mm);
		if(!hlurl || !hlclass) return;
		setTimeout("_uHighlightA(jQuery('"+id+"')[0],'"+hlurl+"','"+hlclass+"');",100);
	}


function _ubuild_submenus(ul) {
		var ch=jQuery(ul).children("li"),i,res=[],subul,m,ls;
		for(i=0;i<ch.length;i++) {
			subul=jQuery(ch[i]).children("ul")[0];
			if(subul) {
				m=_ubuild_submenus(subul);
				subul.parentNode.removeChild(subul);
				ls=jQuery(ch[i]).find("a").get();
				res[res.length]=[jQuery(ch[i]).html(),m,ls.length>0 ? {action:'a'} : null];
			} else {
				ls=jQuery(ch[i]).find("a").get();
				res[res.length]=[jQuery(ch[i]).html(),ls.length>0 ? 'a' : ''];
			}
		}
		return res;
}

function _uColorBox(did,fid){
var hex_Red=new Array("00","33","66","99","CC","FF");
var hex_Green=new Array("00","33","66","99","CC","FF");
var hex_Blue=new Array("00","33","66","99","CC","FF");
var hex_Gray=new Array("909090","939393","969696","999999","9C9C9C","9F9F9F","C0C0C0","C3C3C3","C6C6C6","C9C9C9","CCCCCC","CFCFCF","F0F0F0","F3F3F3","F6F6F6","F9F9F9","FCFCFC","FFFFFF");
var hexred="00";var hexgreen="00";var hexblue="00";var hexgray="00";
var red=0;var green=0;var blue=0;
var x=0;var y=0;var z=0;
var xyz=0;
var ctable='<table border="0" cellpadding="0" cellspacing="1" bgcolor="#000000">';
while (y<6){
ctable+='<tr>';
var x=0;
var hexblue=hex_Blue[blue];
while (x<6){
var z=0;
var hexgreen=hex_Green[green];
while (z<6){
var hexred=hex_Red[red];
var hexadecimal=""+hexred+hexgreen+hexblue;
ctable+='<td style="width:8px;height:8px;cursor:pointer;" onclick="jQuery(\'#'+did+'\').hide(); getElementById(\''+fid+'\').value=\''+hexadecimal+'\'" bgcolor="'+hexadecimal+'"></td>';
z++;red++;
if (red==6){red=0;}
}
x++;green++;
if (green==6){green=0;}
xyz++;
if (xyz==3){ctable+='</tr>'; xyz=0;}
}
y++; blue++
if (blue==6){blue=0;}
}
for (var i=0;i<hex_Gray.length;i++){
ctable+='<td style="width:8px;height:8px;cursor:pointer;" onclick="jQuery(\'#'+did+'\').hide(); getElementById(\''+fid+'\').value=\''+hex_Gray[i]+'\'" bgcolor="'+hex_Gray[i]+'"></td>';
};
ctable+='</table>';
jQuery('#'+did).html(ctable);
}

function _uButton(frm,type,opts){ // formID, type['s','b','r'], options
	var props = jQuery.extend({
	text:'Ok',
	content:'',
	style:0		//0,1
	},opts || {});

	var tp = {
		's':'onclick="if (this.dis){return;} this.className=\'myBtnCont x-unselectable myBtnDis\'; this.dis=true; document.getElementById(\'subm'+frm+'\').click();"',
		'r':'onclick="document.getElementById(\''+frm+'\').reset();"'
	};
    var t = (tp[type]!='undefined') ? tp[type] : '';
	var s = (props.style==1) ? ['myBtnLeft','myBtnCenter','myBtnRight'] : ['myBtnLeftA','myBtnCenterA','myBtnRightA'];

	var hid = (type=='s') ? '<input type="image" src="/.s/img/1px.gif" style="width:1px;" name="subm'+frm+'" id="subm'+frm+'" />' : '';
	var dis = (props.style==2) ? 'myBtnCont x-unselectable myBtnDis' : 'myBtnCont x-unselectable';

	var bt = '<table border="0" cellpadding="0" cellspacing="0" onmousedown="this.className=\'downBtn\'" onmouseover="this.className=\'overBtn\'" onmouseout="this.className=\'outBtn\'">'
+'<tr><td class="'+s[0]+'"><img border="0" src="/.s/img/1px.gif"></td>'
+'<td class="'+s[1]+'"><div class="'+dis+'" unselectable="on" '+t+' '+props.content+'><a href="javascript://" onclick="return false;">'+props.text+'</a></div></td>'
+'<td class="'+s[2]+'"><img border="0" src="/.s/img/1px.gif"></td>'
+'<td style="visibility:hidden;">'+hid+'</td></tr></table>'
	return bt;
}
