__currentModal = null;

__modalsOrder = [];

__modalsCache = [];

//these options will be used for all modals
__modalsOptions = {};

if(typeof Element.setOpacity != 'function') {
    include(JS_PATH + '/effects/builder.js');
    include(JS_PATH + '/effects/effects.js');
    include(JS_PATH + '/effects/dragdrop.js');
    include(JS_PATH + '/dimension.js');
}

var ModalWin = Class.create();

ModalWin.open = function(url, title, params) {

 openMWin( url, title, params['width'], params['height']);

//var w = new ModalWin(url, title, params) ;
return false;
}

function closeWin(){

  closeMWin();
return false; 
}


ModalWin.window = Dimension.window.getDimensions();

ModalWin.__createdModals = 0;

ModalWin.prototype = {

	name: '',

	initialised: false,

	options: {
				width:200,
				height:100,
				evalScripts: true,
				draggable: true,
				allowHTMLTitle: true,
				buttonClose: true,
				buttonMax: false,
				buttonMin: false,
				cacheURLs: false,
				onBeforeOpen: Prototype.emptyFunction,
				onOpen: Prototype.emptyFunction,
				onAfterOpen: Prototype.emptyFunction,
				onBeforeLoad: Prototype.emptyFunction,
				onLoad: Prototype.emptyFunction,
				onAfterLoad: Prototype.emptyFunction,
				onBeforeClose: Prototype.emptyFunction,
				onClose: Prototype.emptyFunction,
				onAfterClose: Prototype.emptyFunction,
				onBeforeMinimize: Prototype.emptyFunction,
				onMinimize: Prototype.emptyFunction,
				onAfterMinimize: Prototype.emptyFunction,
				onBeforeMaximize: Prototype.emptyFunction,
				onMaximize: Prototype.emptyFunction,
                onAfterMaximize: Prototype.emptyFunction,
                onFocus: Prototype.emptyFunction,
				onBlur: Prototype.emptyFunction,
				titleOnDblClick: null
			},

	container: null,

	windowState: 'closed',//can be closed, minimized, opened

	title: null,

	body: null,

	veil: null,

	controlls: null,

	classNamePrefix: 'ModalContainer',

	initialize: function(urlOrHtml, title, options) {
        
	      
        if(  ModalWin.__createdModals )
	{
	    __currentModal.close();
	}
	
        this.name = 'ModalWin' + ModalWin.__createdModals;
        
        this.setButtons = typeof $(this.name) == 'undefined';
//		if(typeof $(this.name) == 'undefined') {

        
		    this.tabIndexes = [];

		    // Pre-defined list of tags we want to disable/enable tabbing into
		    this.tabbableTags = ["A","BUTTON","TEXTAREA","INPUT","IFRAME", "SELECT"];
            
            this.__id = ModalWin.__createdModals;
             
		    this.zIndex = 100 + ModalWin.__createdModals;

            __modalsCache.push(this);

		    var holder = document.getElementsByTagName('BODY')[0] || document.getElementsByTagName('HEAD')[0] || document;
             
		    //create the container
		    this.container = $((!this.setButtons)?this.name:document.createElement('DIV'));
            
		    if(this.setButtons) {
                this.container.id = this.name;

                this.container.className = this.classNamePrefix;
                
		        this.container.setStyle({zIndex: this.zIndex,position:'absolute'});
            }
		    
            if(((document.all && BrowserDetect.version <= 6) || (BrowserDetect.OS == 'Mac' && BrowserDetect.browser == 'Firefox' && BrowserDetect.version <= 2)) && document.getElementsByTagName('select').length > 0) {
			    if(this.setButtons) {
                    this.cover = document.createElement('iframe');
			        Element.setStyle(this.cover, {left: '0px', position: 'absolute', top: '0px', filter:'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'});
			        this.cover.frameBorder = 0;
			        this.cover.scrolling = 'no';
			        this.cover.id = this.name + 'IFRAME';
			        this.container.appendChild(this.cover);
                } else {
                    this.cover = $(this.name + 'IFRAME');
                }
		    }

		    //create the title
            if(this.setButtons) {
                this.title = document.createElement('DIV');
                this.title.id = this.name + 'Title';
                this.title.className = this.classNamePrefix + 'Title';
                this.title.innerHTML = '&nbsp;';
                Element.setStyle(this.title, {zIndex: this.zIndex, position:'relative'});

                this.container.appendChild(this.title);
            } else {
                this.title = $(this.name + 'Title');
            }
		    

		    //create the body
            if(this.setButtons) {
		        this.body = $(document.createElement('DIV'));
		        this.body.id = this.name + 'Body';
		        this.body.className = this.classNamePrefix + 'Body';
		        Element.setStyle(this.title, {zIndex: this.zIndex, position: 'relative'});

		        this.body.makeClipping();

		        this.body.innerHTML = 'Loading ...';

		        this.container.appendChild(this.body);
            } else {
                this.body = $(this.name + 'Body');
            }
            
		    //create the veil
		    if(!(this.veil = $('_ModalWinVeil'))) {

			    this.veil = document.createElement('DIV');
			    this.veil.id = '_ModalWinVeil';
			    this.veil.className = this.classNamePrefix + 'Veil';
			    this.veil.innerHTML = '&nbsp;';

			    Element.setStyle(this.veil, {
											    zIndex: 9999,
											    cursor: 'not-allowed',
											    position: 'absolute'
										    });

			    Element.setOpacity(this.veil, 0.2);

			    Element.hide(this.veil);

			    holder.insertBefore(this.veil, holder.childNodes[0]);

		    }

            if(this.cover && !(this.veilCover = $(this.veil.id + 'IFRAME'))) {
                if(this.setButtons) {
                    this.veilCover = document.createElement('iframe');
                    Element.setStyle(this.veilCover, {zIndex: this.veil.style.zIndex - 1,left: '0px', position: 'absolute', top: '0px', filter:'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'});
                    this.veilCover.frameBorder = 0;
                    this.veilCover.scrolling = 'no';
                    this.veilCover.id = this.veil.id + 'IFRAME';
                    holder.insertBefore(this.veilCover, this.veil);
                } else {
                    this.veilCover = this.veil.id + 'IFRAME';
                }
            }
            
		   Element.hide(this.container);

		    if(this.setButtons) {
                holder.insertBefore(this.container, this.veil);
                Position.absolutize(this.container);
            }
            
		    //check whether anything has to be done on double clicking the title
		    var onDblClick = this.options.titleOnDblClick || Prototype.emptyFunction;

		    switch(onDblClick) {
			    case 'close':
				    onDblClick = (function(){this.close();}).bind(this);
				    break;
			    case 'toggleState':
			    case 'minimize':
			    case 'maximize':
				    onDblClick = (function() {if(this.windowState == 'minimized'){this.maximize();} else {this.minimize();}}).bind(this);
				    break;
			    default:
    //				onDblClick = ().bind();
				    break;
		    }
            
		    this.title.ondblclick = onDblClick;
            
//		}
        
        ModalWin.__createdModals++;
        
        this.initialised = true;
        
        if(urlOrHtml && title) {
            this.open(urlOrHtml, title, options);
        }
	},
    
	open: function(urlOrHtml, title, options) {
        
		this.setOptions(Object.extend(__modalsOptions, options));
        
		if(!this.initialised) {
            
			this.initialize();

		}
        
		if(this.options.onBeforeOpen.apply(this, arguments) !== false) {
            
            //Element.show(this.veil);
            
            this.disableTabIndexes();

			this.setContent(urlOrHtml);

            this.setTitle(title);
			
            this.show();

             var veilHeight = (document.documentElement || document.body).scrollHeight;

            var winH = ModalWin.window.height;

            if(veilHeight < winH) {

                veilHeight = winH;

            }
            
            Element.setStyle(this.veil, {
                                                zIndex: 9999,
                                                width: (document.documentElement || document.body).scrollWidth + 'px',
                                                height: (veilHeight) + 'px',
                                                cursor: 'not-allowed',
                                                position: 'absolute',
                                                top: (0-(document.documentElement || document.body).scrollTop) + 'px',
                                                left: '0px'//(0-(document.documentElement || document.body).scrollLeft) + 'px'
                                            });
            
            if(this.cover) {

                Element.setStyle(this.veilCover, {
                                                width: (document.documentElement || document.body).scrollWidth + 'px',
                                                height: veilHeight + 'px',
                                                position: 'absolute',
                                                top: (0-(document.documentElement || document.body).scrollTop) + 'px',
                                                left: (0-(document.documentElement || document.body).scrollLeft) + 'px'
                                            });

            }
            
		}

		this.options.onAfterOpen.apply(this, arguments);
	},

	close: function() {

		var test = this.onClose.apply(this, arguments);

		if(test !== false) {

			if(this.loadingUrl && this.transport && this.transport.readyState > 0) {
				this.transport.options.onSuccess =
				this.transport.options.onFailure =
				this.transport.options.onComplete = Prototype.emptyFunction;
				this.transport.transport.abort();
			}

			Element.hide(this.container);

            __modalsCache.splice(this.__id, 1);
            
            ModalWin.__createdModals--;
            
            if(ModalWin.__createdModals < 0) {
                ModalWin.__createdModals = 0;
            }
            
            if(!(__currentModal = ((__modalsCache.length)?__modalsCache[this.__id-1]:null)) || !__currentModal.container.visible()) {

                this.veil.hide();
                this.container = this.container.parentNode.removeChild(this.container);
                
                Event.stopObserving(window, 'resize', onResizeForWindow, false);
                Event.stopObserving(window, 'scroll', onScrollForWindow, false);

                onScrollForWindow = onResizeForWindow = null;
//			    this.restoreTabIndexes();
            }
			this.options.onAfterClose.apply(this, arguments);
		}

	},



	minimize: function() {

		if(this.windowState == 'minimized') {
			return;
		}

		var test = this.onMinimize.apply(this, arguments);

		if(test !== false) {

			Element.makeClipping(this.container);

			this.lastHeight = this.container.offsetHeight;

			Element.hide(this.body);

			Element.hide(this.veil);

			if(this.cover) {
				Element.hide(this.cover);
				Element.hide(this.veilCover);
			}

			this.lastPos = Position.find(this.container);

			var h, closeBut = $(this.name + 'Close');

			if(closeBut) {
				h = (closeBut.offsetTop + closeBut.offsetHeight);
			} else {
				h = (Element.getHeight(this.title));
			}

			Element.setStyle(this.container, {
											height: h,
											minHeight:h//Element.getHeight(this.title) + 'px'
											});

			this.container.style.left = '0px';

			this.container.style.top = (parseInt(Dimension.window.height,10)-parseInt((h),10))+'px';

//			this.container.style.position = 'fixed';

			this.windowState = 'minimized';

			this.options.onAfterMinimize.apply(this, arguments);

		}

	},

	maximize: function() {

		if(this.windowState == 'opened') {

			return;

		}

		var test = this.onMaximize.apply(this, arguments);

		if(test !== false) {

			Element.setStyle(this.container, {
											height: this.lastHeight + 'px',
											minHeight: this.options.height + 'px',
											top: this.lastPos.top + 'px',
											left: this.lastPos.left + 'px',
											position: 'absolute'
											});

			Element.removeClipping(this.container);

			Element.show(this.body);

			Element.show(this.veil);

			if(this.cover) {
				Element.show(this.veilCover);
			}

			__currentModal = this;

			this.windowState = 'opened';

			this.options.onAfterMaximize.apply(this, arguments);
		}

	},

	setContent: function(urlOrHtml) {

		if(!this.initialised) {

			this.init();

		}
        
		urlOrHtml = (urlOrHtml || '&nbsp;').toString();

		//check if url or html
		if((this.loadingUrl = /((f|ht)tp([s]{0,1}):\/\/|\.\/)([\d\w_.])/.test(urlOrHtml)) && !__modalsCache[urlOrHtml]) {//it's a url

			Element.update(this.body, '<span>Loading ...</span>');

			//this.setWidth();

			var ajaxOpts = Object.extend({evalScripts: this.options.evalScripts}, this.options);

            var onComp = ajaxOpts.onComplete || Prototype.emptyFunction;
            
			ajaxOpts.onComplete = (function(trans, json, div){
										if(this.options.cacheURLs){
											__modalsCache[urlOrHtml] = trans.responseText;
										}
										this.onLoad.apply(this, arguments);
										this.setWidth();                                        
                                        onComp(trans, json, div);
									}).bind(this);

			this.transport = new Ajax.Updater(this.body.childNodes[0], urlOrHtml, ajaxOpts);

		} else {

			this.body.innerHTML = '<span>' + (__modalsCache[urlOrHtml] || urlOrHtml) + '</span>';

			this.setWidth();

		}

	},

	setTitle: function(title) {
        
		if(!this.initialised) {

			this.initialize();

		}

        if(!this.setButtons) {
            return;
        }
        
//        bNoButtons = this.setButtons;
        
        //if((this.options.buttonClose || this.options.buttonMax || this.options.buttonMin) 
//            &&
//            ($(this.name+'Minimize') || $(this.name + 'Maximize') || $(this.name + 'Close'))
//        ) {
//            bNoButtons = true;
//        }
        
		var imagesTypes = ['.jpg','jpeg','.bmp','.png','.gif'];

		Element.update(this.title, (title || '').toString());

		if(!this.options.allowHTMLTitle) {

			Element.update(this.title, (title || '').toString().escapeHTML());

		}
        
		if(this.setButtons && (this.options.buttonClose || this.options.buttonMax || this.options.buttonMin)) {

			this.title.innerHTML += '<span style="text-align: right; width:100%;">';
			this.title.innerHTML += (!this.options.buttonMin)?'':'<span id="'+this.name+'Minimize" class="ModalWinMin ' + this.classNamePrefix + 'Button" title="minimize">_</span>';
			this.title.innerHTML += (!this.options.buttonMax)?'':'<span id="'+this.name+'Maximize" class="ModalWinMax ' + this.classNamePrefix + 'Button" title="maximize">[]</span>';
			this.title.innerHTML += (!this.options.buttonClose)?'':'<span id="'+this.name+'Close" class="ModalWinClose ' + this.classNamePrefix + 'Button" title="close">X</span>';
			this.title.innerHTML += '</span>';

			var offset = 	Number((Element.getStyle(this.title, 'padding-right') || '0').replace(/[^\d]+/i, '')) +
							Number((Element.getStyle(this.container, 'padding-right') || '0').replace(/[^\d]+/i, '')) +
							Number((Element.getStyle(this.title, 'border-right-width') || '0').replace(/[^\d]+/i, '')) +
							Number((Element.getStyle(this.container, 'border-right-width') || '0').replace(/[^\d]+/i, ''));
            
			offset = this.options.width - offset;
            
			var close = $(this.name+'Close')
			var max = $(this.name+'Maximize')
			var min = $(this.name+'Minimize')

			var sizer = close || max || min;
            
			var top = Element.getStyle(close, 'top') || (Number((Element.getStyle(this.title, 'padding-top') || '0').replace(/[^\d]+/i, '')) +
												Number((Element.getStyle(this.container, 'padding-top') || '0').replace(/[^\d]+/i, '')) +
												Number((Element.getStyle(this.title, 'border-top-width') || '0').replace(/[^\d]+/i, '')) +
												Number((Element.getStyle(this.container, 'border-top-width') || '0').replace(/[^\d]+/i, ''))) -
												(
												Number((Element.getStyle(sizer, 'top') || '0').replace(/[^\d]+/i, '')) +
												Number((Element.getStyle(sizer, 'border-top') || '0').replace(/[^\d]+/i, '')) +
												Number((Element.getStyle(sizer, 'padding-top') || '0').replace(/[^\d]+/i, '')) +
												Number((Element.getStyle(sizer, 'border-bottom') || '0').replace(/[^\d]+/i, '')) +
												Number((Element.getStyle(sizer, 'padding-bottom') || '0').replace(/[^\d]+/i, ''))
												) +
												'px';

			var safariOffset = BrowserDetect.OS == 'Mac' && BrowserDetect.browser == 'Safari'?15:0;

			if(close) {
                
                var img = '';
				
                if((img = Element.getStyle(close, 'background-image')) != 'none' && (img = img.match(/http(s?):\/\/[^\s\)]{1,}/gim)[0] || false)) {
                   var i = new Image();
                   i.src = img;
                   i.onload = (function() {
                        Element.setStyle(this, {backgroundColor: 'white'});

                        Element.update(this, '&nbsp;');
                   }).bind(close);
					

				}

				img = new String(this.options.buttonClose);

				if(imagesTypes.indexOf(img.substr(img.lastIndexOf('.'), 4)) != -1) {

					close.update('<img src="' + img + '">');

				}

				Element.setStyle(close, {
														position: 'absolute',
														left: (offset -= Number((close.getStyle('width') || '0').replace(/[^\d]+/i, ''))) + 'px',
														top: top
														});
                //space between buttons
                offset -= 15;
                
				Event.listen(close, 'mouseover', function(){close.addClassName('ModalContainerButtonHover')}, false)
				Event.listen(close, 'mouseout', function(){close.removeClassName('ModalContainerButtonHover')}, false)
				Event.listen(close, 'mousedown', function(){close.addClassName('ModalContainerButtonPress')}, false)
				Event.listen(close, 'mouseup', function(){close.removeClassName('ModalContainerButtonPress'); __currentModal.close()}, false)

			}

			if(max) {

				if(window.console){

					offset = offset - safariOffset;

				}

				Element.setStyle(max, {
														position: 'absolute',
														left: (offset -= Number((Element.getStyle(max, 'width') || '0').replace(/[^\d]+/i, ''))) + 'px',
														top: top
													});

				offset -= 5;

				Event.listen(max, 'mouseover', function(){Element.addClassName(max, 'ModalContainerButtonHover')})
				Event.listen(max, 'mouseout', function(){Element.removeClassName(max, 'ModalContainerButtonHover')})
				Event.listen(max, 'mousedown', function(){Element.addClassName(max, 'ModalContainerButtonPress')})
				Event.listen(max, 'mouseup', function(){Element.removeClassName(max, 'ModalContainerButtonPress'); __currentModal.maximize();})

				var img = '';
                
                if((img = Element.getStyle(close, 'background-image')) != 'none' && (img = img.match(/http(s?):\/\/[^\s\)]{1,}/gim)[0] || false)) {
                   var i = new Image();
                   i.src = img;
                   i.onload = (function() {
                        Element.setStyle(this, {backgroundColor: 'white'});

                        Element.update(this, '&nbsp;');
                   }).bind(max);
                    

                }

				img = new String(this.options.buttonMax);

				if(imagesTypes.indexOf(img.substr(img.lastIndexOf('.'), 4)) != -1) {

					Element.update(max, '<img src="' + img + '">');

				}

			}

			if(min) {

				if(window.console){

					offset = offset - safariOffset;

				}

				Element.setStyle(min, {
														position: 'absolute',
														left: (offset -= Number((Element.getStyle(min, 'width') || '0').replace(/[^\d]+/i, ''))) + 'px',
														top: top
													});

				Event.listen(min, 'mouseover', function(){Element.addClassName(min, 'ModalContainerButtonHover')})
				Event.listen(min, 'mouseout', function(){Element.removeClassName(min, 'ModalContainerButtonHover')})
				Event.listen(min, 'mousedown', function(){Element.addClassName(min, 'ModalContainerButtonPress')})
				Event.listen(min, 'mouseup', function(){Element.removeClassName(min, 'ModalContainerButtonPress'); __currentModal.minimize();})

				var img = '';
                
                if((img = Element.getStyle(close, 'background-image')) != 'none' && (img = img.match(/http(s?):\/\/[^\s\)]{1,}/gim)[0] || false)) {
                   var i = new Image();
                   i.src = img;
                   i.onload = (function() {
                        Element.setStyle(this, {backgroundColor: 'white'});

                        Element.update(this, '&nbsp;');
                   }).bind(min);
                    

                }
                
                img = new String(this.options.buttonMin);

				if(imagesTypes.indexOf(img.substr(img.lastIndexOf('.'), 4)) != -1) {

					Element.update(min, '<img src="' + img + '">');

				}

			}

		}

	},

	setOptions: function(options) {

		Object.extend(this.options, (typeof options == 'object')?options:{});

	},

	show: function() {
    
        __currentModal = this; 
        
        if(this.setButtons) {
		this.onLoad = (this.options.onLoad).bind(this);
		this.onOpen = (this.options.onOpen).bind(this);
		this.onMaximize = (this.options.onMaximize).bind(this);
		this.onMinimize = (this.options.onMinimize).bind(this);
        this.onClose = (this.options.onClose).bind(this);
        this.onFocus = (this.options.onFocus).bind(this);
		this.onBlur = (this.options.onBlur).bind(this);
                             
		Element.addClassName(this.container, this.classNamePrefix);
		Element.addClassName(this.title, this.classNamePrefix + 'Title');

		if(this.options.draggable) {

			this.title.style.cursor = 'move';

			new Draggable(this.container, {zindex:this.zIndex, handle: this.title, endeffect:Prototype.emptyFunction})

		}

		

		Event.listen(this.container, 'mouseover', (function(){
                                                        var tmp;
                                                        if(tmp = (this != __currentModal)) {
                                                            //switch the order of the modals
                                                            var switch_id = __currentModal.__id;
                                                            var tmp = __modalsCache[switch_id];
                                                            __modalsCache[switch_id] = this;
                                                            tmp.__id = this.__id;
                                                            __modalsCache[tmp.__id] = tmp;
                                                            this.__id = switch_id;
                                                        }
                                                        
                                                        __currentModal = this;
                                                        
                                                        if(tmp) {
                                                            __currentModal.focus();
                                                        }
                                                        
                                                    }
                                                  ).bind(this), false);

        }
        this.focus();
        
		this.onOpen.apply(this, arguments);

		this.windowState = 'opened';

	},
    focus: function() {
        if(this.setButtons) {
//        Event.listen(this._blurrer, 'blur', function(){alert("FCK")}, false);
            Event.listen(document, 'keydown', (onEscapeForDocument = (this.hideOnEscape).bind(this)), false);
            Event.listen(window, 'resize', (onResizeForWindow = (this.updatePosDim).bind(this)), false);
            Event.listen(window, 'scroll', (onScrollForWindow = (this.updatePosDim).bind(this)), false);
        }
        this.onFocus(); 
    },
    blur: function() {
        alert("BLURRED")
    },
	updatePosDim: function(e) {
            ModalWin.window = Dimension.window.getDimensions();
			if(this.windowState != 'opened') {
            
				return;

			}

			if(!e) {
				var e = window.event;
			}
                     
			switch(e.type) {
				case 'scroll':
                     
					/*
					var dim = Element.getDimensions(this.veil);
					var h = dim.height;
					var h2 = (document.documentElement || document.body).scrollHeight;

					var w = dim.width;
					var w2 = (document.documentElement || document.body).scrollWidth;

					if(h != h2 || w != w2) {

						Element.setStyle(this.veil, {
											height: Math.max(h, h2) + 'px',
											left: Math.max(w, w2) + 'px'
										});

					}

					*/

					break;
				case 'resize':
                    
					Element.setStyle(this.veil, {
											height: (document.documentElement || document.body).scrollHeight + 'px',
											width: (document.documentElement || document.body).scrollWidth + 'px'
										});
                    this.centerWin();                                        
					break;
			}			
	},

	setWidth: function() {
                               
	//	Element.show(this.veil);

		if(this.veilCover) {
			Element.show(this.veilCover);
		}
        
		this.container.show();

        if (this.options.width == null || isNaN(this.options.width)) {
            this.options.width = this.container.offsetWidth;
        }
        
        if (this.options.height == null || isNaN(this.options.height)) {
            this.options.height = this.container.offsetHeight;
        }
        
		if(this.loadingUrl && this.transport && this.transport.transport.readyState < 4) {
            if(typeof centered == 'undefined') {
                this.centerWin();
                centered = true;
            }
			return;
		}

		var w = 0, h = 0, width, height;
        
        if(typeof centered != 'undefined') {
            delete(centered);
        }
        
        this.container.style.width = (width = Math.max(((isNaN(this.options.width))?0:this.options.width), w)) + 'px';
        this.container.style.height = (height = Math.max(((isNaN(this.options.height))?0:this.options.height), h)) + 'px';
        
        var lb=0, rb=0, tb=0, bb=0, bords = [this.container, this.body, this.title];
        
        bords.each(
            function(b){
                if(!isNaN(b._bord = parseInt((b.getStyle('border-left-width') || '').replace(/[^\d]/gim, ''))) && b._bord > lb) {
                    lb = b._bord;
                }
                
                if(!isNaN(b._bord = parseInt((b.getStyle('border-right-width') || '').replace(/[^\d]/gim, ''))) && b._bord > rb) {
                    rb = b._bord;
                }
                
                if(!isNaN(b._bord = parseInt((b.getStyle('border-top-width') || '').replace(/[^\d]/gim, ''))) && b._bord > tb) {
                    tb = b._bord;
                }
                
                if(!isNaN(b._bord = parseInt((b.getStyle('border-bottom-width') || '').replace(/[^\d]/gim, ''))) && b._bord > bb) {
                    bb = b._bord;
                }
                
                if(b._bord) {
                    b._bord = null;
                };
            }
        );
        
        width -= lb + rb;
        
        height -= tb + bb;
        
        this.title.style.minWidth =
        this.body.style.minWidth = width + 'px';
        
        if(document.all) {
			this.title.style.width = '100%';
            this.body.style.width = (width + 6) + 'px';
			this.body.style.height = '100%';
		}

		this.body.style.verticalAlign = 'bottom'

		Element.show(this.container);

		if(this.cover) {
			this.cover.style.height = (this.container.offsetHeight - 5) + 'px';
			this.cover.style.width = (this.container.offsetWidth - 5) + 'px';

			this.cover.style.left = this.body.offsetLeft + 'px';
			this.cover.style.zIndex = this.body.style.zIndex - 1;
			this.cover.style.display = 'block';
		} else {
            this.body.style.height = (height - this.title.offsetHeight - tb - bb) + 'px';
        }
        
        var compare = $(this.body.childNodes[0]);
        
        if(compare) {

            if(compare.offsetWidth != this.body.offsetWidth) {
                if(this.options.width && this.options.width == 'auto') {
                    w = Math.min(compare.offsetWidth, ModalWin.window.width);
                    this.container.style.width = w + 'px';
                    if(compare.offsetWidth > ModalWin.window.widt) {                    
                        this.body.style.width = '100%';    
                        this.body.style.overflowX = 'auto';
                        this.container.style.overflowX = 'hidden';
                    }
                    
                } else {
                    this.body.style.overflowX = 'auto';
                }
            }
            
            if(compare.offsetHeight != this.body.offsetHeight) {
                if(this.options.height && this.options.height == 'auto') {
                    h = Math.min(compare.offsetHeight, ModalWin.window.height);
                    
                    this.body.style.height = h + 'px';

                    if(compare.offsetHeight > ModalWin.window.height) {
                        var stop=1000;
                        var stop1 = ModalWin.window.height - 20;                        
                        this.container.style.height = (stop1) + 'px';
                        this.body.style.height = (this.container.offsetHeight - this.title.offsetHeight - bb - tb) + 'px';                        
                        this.container.style.overflowY = 'hidden';
                        this.body.style.overflowY = 'auto';    
                        this.body.scrollTop = 0;
                    } 
                    
                } else {                
                    this.body.style.overflowY = 'auto';
                    this.body.scrollTop = 0;
                }
            }
            
        }
        
        this.centerWin();

	},

	centerWin: function() {

		if ((this.options.width && this.options.height) || this.container.style.display != 'none') {

//            width = (this.container.style.display != 'none')?parseInt(this.container.getStyle('width')):this.options.width;
//			height = (this.container.style.display != 'none')?parseInt(this.container.getStyle('height')):this.options.height;
            width = this.options.width;
			height = this.options.height;

			if (width == null || isNaN(width)) {
				this.options.width = width = this.container.offsetWidth;
			}
			if (height == null || isNaN(height)) {
				this.options.height = height = this.container.offsetHeight;
			}

			var win = Dimension.window.getDimensions();

			var fullHeight = win['y'];
			var fullWidth = win['x'];

			var theBody = (document.documentElement || document.body);
			
			
			if( document.documentElement && document.documentElement.scrollTop )
			{
			    var theBody = document.documentElement;
			}
			else if(  document.body && document.body.scrollTop )
			{
			    var theBody = document.body;
			}
			else
			{
			    var theBody = document.documentElement;
			}

			
            
			//theBody.style.overflow = "hidden";

			var scTop = parseInt(theBody.scrollTop,10);
			var scLeft = parseInt(theBody.scrollLeft,10);
            
			this.veil.style.top = scTop + "px";

			this.veil.style.left = scLeft + "px";

			var titleBarHeight = parseInt(this.title.offsetHeight);
            
			this.container.style.top = (scTop + (this.options.y || ((fullHeight - (height+titleBarHeight)) / 2))) + "px";

			this.container.style.left =  (scLeft + (this.options.x || ((fullWidth - width) / 2))) + "px";

		}
	},

	hideOnEscape: function(e) {

		Event.getEvent((e = e || window.event));

  		var key = Event.key(e);

		if(key.code == Event['KEY_ESC'] && __currentModal == this) {
            
			this.close();
            
			if(__modalsCache.length == 0) {

				Event.stopListen(document, 'keydown', onEscapeForDocument, false);

				onEscapeForDocument = null;

			}

		}
	},

	disableTabIndexes : function() {
		var i = 0;
		for (var j = 0; j < this.tabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(this.tabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				this.tabIndexes[i] = tagElements[k].tabIndex;
				tagElements[k].tabIndex="-1";
				i++;
			}
		}
	},
	restoreTabIndexes : function() {

			var i = 0;
			for (var j = 0; j < this.tabbableTags.length; j++) {
				var tagElements = document.getElementsByTagName(this.tabbableTags[j]);
				for (var k = 0 ; k < tagElements.length; k++) {
					tagElements[k].tabIndex = this.tabIndexes[i];
					tagElements[k].tabEnabled = true;
					i++;
				}
			}

	}
}

var ModalAlert = function(){

		    var oldApply = window.alert.apply;

		    window.alert.apply = this;

		    ModalWin.open(arguments[0], arguments[1] || 'Alert', Object.extend({draggable: true}, (typeof arguments[2] == 'object'?arguments[2]:{})));

		    window.alert.apply = oldApply;
}

var ModalConfirm = function(text, title, options){

	options = Object.extend({draggable: true, butYes: 'Yes', butNo: 'No', buttonMax:0, buttonMin:0, onConfirm: Prototype.emptyFunction}, (typeof arguments[2] == 'object'?arguments[2]:{}));

	returnStatus = false;

    options.onClose = function() {

    	var ret = arguments[0] || false;

    	if(ret) {

			options.onConfirm.apply(window, $A(arguments));

    	}
    }

    var html = '<div style="width:100%;height:100%;vertical-align:bottom;" align="center">' + text.toString() + '<br>' +
    		   '	<input type="button" value="' + options.butYes + '" onclick="__currentModal.close(true);">' +
    		   '&nbsp;' +
    		   '	<input type="button" value="' + options.butNo + '" onclick="__currentModal.close(false);">' +
    		   '</div>';


    ModalWin.open(html, title || 'Confirm', options);

}