var LoadingDialog = {
	containerId: 'ajaxLoading',
	innerTextId: 'ajaxLoadingText',
	ie6PeriodilalUpdater: null,
	setText: function (text) {
		$(this.innerTextId).update(text);
	},
	reset: function () {
		$(this.innerTextId).update(Messages.DEFAULT_SAVING);
		$(this.containerId).hide();
	},
	show: function () {
		if(navigator.appVersion.match(/\bMSIE[^a-zA-Z0-9]*6/))  // emulate IE6
			this.ie6PeriodilalUpdater = new PeriodicalExecuter(LoadingDialog.ie6update, 0.1);
		$(this.containerId).show();		
	}, 
	
	hide: function () {
		$(this.containerId).hide();
		if(this.ie6PeriodilalUpdater!=null)
			this.ie6PeriodilalUpdater.stop();
	},
	
	ie6update: function(pe) {
		var ps=Position.page(document.body);
		Element.setStyle($(LoadingDialog.containerId), {top: Math.abs(parseInt(ps[1]))+"px"});
	}
};

var DialogManager = {
	objectCounter: 0,
	settings: {
		overlayDuration: 0.2,
		overlayOpacity: 0.6	
	},
	initialize: function () {
		if(typeof this.alreadyCreated!="undefined")
			return;
		this.dialogStack = new Array();
		this.alreadyCreated=true;
		this.preloadItems();
	},	
	
	createDialog: function (settings) {
		var dialog = new ModalDialog(settings, this.objectCounter++);
		this.dialogStack.push(dialog);
		this.checkModals();
		return dialog;
	},

	checkModals: function ()  {
		var modals=0;
		for(var i=0, len=this.dialogStack.length; i<len; i++) {
			if(this.dialogStack[i]!=null && this.dialogStack[i].settings.isModal)
				modals++;
		}
		if(modals>0)
			this.showOverlay();
		else
			this.hideOverlay();
	},

	moveInFront: function (currentDialog) {
		for(var i=0, len=this.dialogStack.length; i<len; i++) {
			if(this.dialogStack[i]!=null) {
				if(!currentDialog.equals(this.dialogStack[i]))
					this.dialogStack[i].deactivate();
				else
					this.dialogStack[i].activate();
			}
		}
	},

	removeFrom: function(currentDialog) {
		for(var i=0, len=this.dialogStack.length; i<len; i++) {
			if(currentDialog.equals(this.dialogStack[i])) {
				this.dialogStack[i]=null;
			}
		}
		this.checkModals();
	},
	
	getDialogByComponent: function (DOMElement) {
		var current=DOMElement;
		while(current!=null) {
			if(current!=null && current.id!=null && current.id!='') {
				for(var i=0, len=this.dialogStack.length; i<len; i++) {
					if(this.dialogStack[i]!=null && this.dialogStack[i].equalsToId(current.id)) {
						return this.dialogStack[i];
					}
				}
			}
			current=current.parentNode?current.parentNode:null;
		}
		return null;
	},
	
	getDialogs: function() {
		var a=new Array();
		for(var i=0, len=this.dialogStack.length; i<len; i++) {
			if(this.dialogStack[i]!=null)
				a.push(this.dialogStack[i]);
		}
		return a;
	},

	showOverlay: function() {
		if(this.alreadyShowed)
			return;
		this.alreadyShowed=true;
		this.overlayId='dialogOverlay';
		hideSelectBoxes();
		hideFlash();
		if($(this.overlayId)==null) {
			var iDocumentBody = document.getElementsByTagName("body").item(0);
			var iOverlay = document.createElement("div");
			iOverlay.setAttribute('id', this.overlayId);
			Element.setStyle(iOverlay, 
				{display: "none", position: "absolute", top: 0, left: 0, zIndex: 90, width: "100%", height: "500px", backgroundColor: "#000"}
			);
			iDocumentBody.appendChild(iOverlay);
		}
		this.updateOverlay();
		new Effect.Appear(this.overlayId, 
			{duration: this.settings.overlayDuration, from: 0.0, to: this.settings.overlayOpacity}
		);	
	},

	updateOverlay: function() {
		if($(this.overlayId)!=null) {
			var arrayPageSize=getPageSize();
			Element.setStyle($(this.overlayId), {height: arrayPageSize[1]+"px"});
		}
	},

	hideOverlay: function() {
		if(!this.alreadyShowed)
			return;
		this.alreadyShowed=false;
		if($(this.overlayId)!=null)
			new Effect.Fade(this.overlayId, 
				{duration: this.settings.overlayDuration, from: this.settings.overlayOpacity, to: 0.0}
			);
		setTimeout(showSelectBoxes, 1000*this.settings.overlayDuration);
		setTimeout(showFlash, 1000*this.settings.overlayDuration);
	},

	preloadItems: function() {
		this.toPreload = [
			"/i/mail/actions/delete.gif", 
			"/i/mail/actions/edit.gif", 
			"/i/mail/actions/stop.gif",
			"/i/loading.gif"
		];
		this.preloadedImages=new Array();
		for(var i=0, len=this.toPreload.length;i<len;i++) {
			var img=new Image();
			img.src=this.toPreload[i];
			this.preloadedImages.push(img);
		}
	},
	
	toString: function () {
		var str='';
		for(var i=0, len=this.dialogStack.length; i<len; i++) {
			if(this.dialogStack[i]!=null)
				str+=i+" ::: "+this.dialogStack[i].toString()+"\r\n";
		}
		return str;
	}	
};

DialogManager.initialize();

var ModalDialog = Class.create();

ModalDialog.prototype = {
	
	initialize: function (settings, time) {
		var prefix='modalDialog';
		if(time==null)
			time=(new Date()).getTime();
		this.containerId = prefix+time;
		this.innerContainerId = prefix+'Inner'+time;
		this.titleId = prefix+'Text'+time;
		this.titleContainerId = prefix+'TextContainer'+time;
		this.titleControllerId = prefix+'TextController'+time;
		this.bodyId = prefix+'Body'+time;
		this.settings = {
			isModal: true,
			withTitle: true,
			dialogWidth: "650px",
			titlePadding: "5px",
			bodyPadding: "5px",
			titleBackgroundColor: "#93B5DF",
			titleMargin: "2px",			
			dialogInnerClassName: "dialog-styles",
			dialogBodyClassName: "dialog-innerstyles",
			//bodyBackgroundColor: "#FFF",
			//borderLeft: "solid 3px #CFCFCF",
			//borderRight: "solid 3px #AFAFAF",
			//borderTop: "solid 3px #CFCFCF",
			//borderBottom: "solid 3px #AFAFAF",
			closeImage: "/i/mail/actions/delete.gif",
			openRollImage: "/i/mail/actions/edit.gif",
			closeRollImage: "/i/mail/actions/stop.gif",
			withRollButton: true
		};
		this.setSettings(settings);
		this.createDialog();
	},

	equals: function (dialog) {
		return (dialog!=null && dialog.containerId!=null && this.containerId==dialog.containerId);
	},
	
	equalsToId: function (componentId) {
		return (
			componentId==this.containerId || 
			componentId==this.bodyId || 
			componentId==this.innerContainerId || 
			componentId==this.titleId || 
			componentId==this.titleContainerId || 
			componentId==this.titleControllerId 
		);
	},
	
	setSettings: function (settings) {
		if(typeof settings=="object")
			Object.extend(this.settings, settings);
	},
	
	createDialog: function() {
		if($(this.containerId)==null) {
			var iDocumentBody = document.getElementsByTagName("body").item(0);

			var iContainer = document.createElement("div");
			iContainer.setAttribute('id', this.containerId);
			Element.setStyle(iContainer,
				{display: "none", position: "absolute", width: this.settings.dialogWidth, zIndex: 100}
			);
			iDocumentBody.appendChild(iContainer);			
			

			var iInnerContainer = document.createElement("div");
			iInnerContainer.setAttribute('id', this.innerContainerId);
			Element.setStyle(iInnerContainer,
				{
					position: "relative" 
					//backgroundColor: "#fff", 
					//borderLeft: this.settings.borderLeft, 
					//borderRight: this.settings.borderRight, 
					//borderTop: this.settings.borderTop, 
					//borderBottom: this.settings.borderBottom
				}
			);
			iContainer.appendChild(iInnerContainer);

			if(this.settings.withTitle) {
				var iTitleContainer = document.createElement("div"), self=this;
				iTitleContainer.setAttribute('id', this.titleContainerId);
				Element.setStyle(iTitleContainer,
					{padding: this.settings.titlePadding, backgroundColor: this.settings.titleBackgroundColor, cursor: "pointer", margin: this.settings.titleMargin}
				);
				iInnerContainer.appendChild(iTitleContainer);

				var iTitleController = document.createElement("span");
				iTitleController.setAttribute('id', this.titleControllerId);
				Element.setStyle(iTitleController, 
					{"float": "right"}
				);
				iTitleContainer.appendChild(iTitleController);
				
				if(this.settings.withRollButton) {
					var iRollImage=document.createElement("img");
					iRollImage.setAttribute('id', this.titleContainerId+'roll');
					iRollImage.setAttribute('src', this.settings.openRollImage);
					Element.setStyle(iRollImage, {margin: "2px"});
					iTitleController.appendChild(iRollImage);
					Event.observe(iRollImage, 'click', function() {self.toggle();});
				}
				
				var iCloseImage=document.createElement("img");
				iCloseImage.setAttribute('src', this.settings.closeImage);
				Element.setStyle(iCloseImage, {margin: "2px"});
				iTitleController.appendChild(iCloseImage);
				Event.observe(iCloseImage, 'click', function() {self.destroy();});
				
				var iTitle = document.createElement("span");
				iTitle.setAttribute('id', this.titleId);
				iTitleContainer.appendChild(iTitle);
			}

			var iBody = document.createElement("div");
			iBody.setAttribute('id', this.bodyId);
			Element.setStyle(iBody,
				{padding: this.settings.bodyPadding, backgroundColor: this.settings.bodyBackgroundColor}
			);
			if(typeof this.settings.dialogBodyClassName!="undefined" && this.settings.dialogBodyClassName!=null) {
				iBody.className = this.settings.dialogBodyClassName;
			}

			if(typeof this.settings.dialogInnerClassName!="undefined" && this.settings.dialogInnerClassName!=null) {
				iInnerContainer.className = this.settings.dialogInnerClassName;
			}

			iInnerContainer.appendChild(iBody);

			var self=this;
			Event.observe($(this.bodyId), 'mousedown', function(e){if(DialogManager!=null) DialogManager.moveInFront(self);});
			//Event.observe($(this.bodyId), 'mousemove', function(e){Event.stop(e);});		
			// if dialog has title - moveable!
			if(this.settings.withTitle) {
				Event.observe($(this.titleContainerId), 'mousedown', function(e){if(DialogManager!=null) DialogManager.moveInFront(self);});	
				new Draggable($(this.containerId), {revert:false, change:this.updatePosition});
			}
		}
	},
	
	activate: function() {
		if($(this.containerId)!=null)
			Element.setStyle(this.containerId, {zIndex: 100});
	},
	
	deactivate: function() {
		if($(this.containerId)!=null)
			Element.setStyle(this.containerId, {zIndex: 99});
	},
	
	updatePosition: function(x) {
		var left=parseInt(Element.getStyle(x.element, ('left'))), top=parseInt(Element.getStyle(x.element, ('top'))), maxLeft=0;
		var arrayPageSize=getPageSize(), arrayPageScroll=getPageScroll();
		maxLeft=arrayPageSize[2]-parseInt(Element.getStyle(x.element, 'width'));
		if(left>maxLeft) {
			Element.setStyle(x.element, {left: maxLeft+"px"});
		}
		else if (left<0) {
			Element.setStyle(x.element, {left: "0px"});
		}
	},
	
	show: function(centered) {

		if(!this.isAlreadyPositioned && centered==null) {
			var arrayPageSize=getPageSize(), arrayPageScroll=getPageScroll(),
				dialogTop=arrayPageScroll[1]+2*(arrayPageSize[3]/10), 
				dialogLeft=arrayPageScroll[0]+(arrayPageSize[2]/2)-(parseInt(this.settings.dialogWidth)/2);

			Element.setStyle($(this.containerId), {top: dialogTop+"px", left: dialogLeft+"px"});
		}
		else if (centered!=null && centered) {
			this.setCentered();
		}

		$(this.containerId).show();
	},

	setTitle: function(title) {
		if($(this.titleId)!=null)
			$(this.titleId).update(title);
	},

	getContainer: function() {
		return $(this.bodyId);
	},
	getContent: function() {
		if($(this.bodyId)!=null)
			return $(this.bodyId).innerHTML;
		return '';
	},
	
	setContent: function(content) {
		if($(this.bodyId)!=null)
			$(this.bodyId).update(content/*+'<br />'+$H(this.settings).inspect().escapeHTML()*/);
	},
	
	setChild: function(child) {
		if($(this.bodyId)!=null && child!=null)
			$(this.bodyId).appendChild(child);
	},

	setPositionTo: function (element, tuneUp) {
		if(element!=null) {
			try {
				var pos=Position.cumulativeOffset(element), x=pos[0], y=pos[1];
				if(tuneUp!=null && typeof tuneUp.dx!="undefined")
					x+=tuneUp.dx;
				if(tuneUp!=null && typeof tuneUp.dy!="undefined")
					y+=tuneUp.dy;
				Element.setStyle($(this.containerId), {left: x+"px", top: y+"px"});
				this.isAlreadyPositioned=true;
			} 
			catch (e) {
				// nothing to do here!
				alert(e);
			}
		}
	},

	setCentered: function() {
		var arrayPageSize=getPageSize(), arrayPageScroll=getPageScroll(), 
			width=Element.getStyle($(this.containerId), 'width'),
			height=Element.getStyle($(this.containerId), 'height'),
			dialogTop=arrayPageScroll[1]+(arrayPageSize[3]/2)-(parseInt(height)/2), 
			dialogLeft=arrayPageScroll[0]+(arrayPageSize[2]/2)-(parseInt(width)/2);
		Element.setStyle($(this.containerId), {top: dialogTop+"px", left: dialogLeft+"px"});
	},

	toggle: function() {
		if($(this.bodyId)!=null) {
			$(this.bodyId).toggle();
			if(this.titleContainerId+'roll'!=null) {
				if($(this.bodyId).visible())
					$(this.titleContainerId+'roll').setAttribute('src', this.settings.openRollImage);
				else
					$(this.titleContainerId+'roll').setAttribute('src', this.settings.closeRollImage);		
			}
		}
	},
	
	destroy: function() {
		if(DialogManager!=null)
			DialogManager.removeFrom(this);
		if($(this.containerId)!=null)
			$(this.containerId).parentNode.removeChild($(this.containerId));
	},
	
	setDimensions: function(width, height) {
		var dimensions = {}, update = false;
		if(width!=null && parseInt(width)>0) {
			dimensions.width = parseInt(width) + "px";
			update=true;
		}
		if(height!=null && parseInt(height)>0) {
			dimensions.height = parseInt(height) + "px";
			update=true;
		}
		if(update)
			Element.setStyle($(this.containerId), dimensions);
	},
	
	loadContentFrom: function(url, post, afterUpdate) {
		var self=this, method='get', options;
		if(post!=null && post.strip()!='')
			method='post';
		options = {
				method: method,
				onComplete: function(response) {
					self.setContent(response.responseText);
					self.show();
					DialogManager.updateOverlay();
					if(afterUpdate!=null)
						afterUpdate(response.responseText);
				}
		};
		if(method=='post')
			Object.extend(options, {parameters: post});
		new Ajax.Request(url, options);
	},
	
	toString: function () {
		return '[DOM container: ' + this.containerId + ', settings: ' + $H(this.settings).inspect() + ']'   ;
	}	
};

var LightBoxDialog = {
	dialog: null,
	initialize: function (options) {
		this.options = {
			defaultDialogWidth: "250px",
			withRollButton: false
		};
		if(typeof options=="object")
			Object.extend(this.options, options);
	},
	
	show: function(bigImageSrc, title, description) {
		if(typeof this.options=="undefined")
			this.options = {defaultDialogWidth: "250px"};
		this.dialog = DialogManager.createDialog(this.options);
		var self = this, html = '<div style="text-align:center;">';
		imgPreloader = new Image();
		imgPreloader.onload = function() {
			self.dialog.setDimensions(imgPreloader.width+20, imgPreloader.height+20);
			html += '<img src="' + imgPreloader.src + '" /><br />' + description + '</div>';
			self.dialog.setContent(html);
			self.dialog.setCentered();
			imgPreloader.onload=function(){};
		}
		this.dialog.setTitle(title);
		this.dialog.setContent(html+'<img src="/i/loading.gif" style="margin:10px;"/></div>');
		this.dialog.setDimensions(this.options.defaultDialogWidth);
		this.dialog.show();
		this.dialog.setCentered();
		imgPreloader.src = bigImageSrc;
	}
};