
var NotsuMail = new Class({

	months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],

	initialize: function() {
		this.images = 'i/send/';
		this.timestamp = new Date();
		this.noteType = '';
		this.newItemRow = null;
		this.sentNote = false;
		this.mask = null;
		this.list = [];
		this.build();
		this.buildNote();
	},

	build: function() {
		var win = window.getSize(),
				winScroll = window.getScroll();
		var bounds = {
			x: 0,
			y: 0,
			w: /*338*/369,
			h: /*256*/283
		};
		bounds.x = Math.round((win.x - bounds.w) / 2);
		bounds.y = Math.round((win.y - bounds.h) / 2);
	
		this.chooser = new Element('div', {
			styles: {
				zIndex: 1500,
				position: 'absolute',
				left: winScroll.x + bounds.x,
				top: winScroll.y + bounds.y,
				width: bounds.w,
				height: bounds.h
			}
		})/*.adopt(
			this.chooserShadow = new Element('div', {
				styles: {
					position: 'absolute',
					left: 0,
					top: 0,
					width: bounds.w,
					height: bounds.h,
					
					background: 'url(' + this.images + 'type-bk.png) no-repeat 0 0',
					opacity: 0.6
				}
			})
		)*/;
		
		this.chooser.adopt(
			new Element('div', {
				styles: {
					position: 'absolute',
					left: 67 + 15,
					top: 33,
					width: 200,
					textAlign: 'center'
				}
			}).adopt(
				this.chooserTitle = new Element('span', {
					styles: {
						/*position: 'absolute',
						left: 67 + 15,
						top: 31 + 13,
						//width: 200,*/
						fontFamily: 'Arial',
						fontSize: '14px',
						fontWeight: 'bold',
						textAlign: 'center',
						color: '#ffffff',
						textShadow: '#000000 0 1px 0',
						
						background: Browser.Engine.trident ? '#000000' : 'rgba(0,0,0,0.4)',
						padding: '2px 8px',
						'border-radius': '11px',
						'-moz-border-radius': '11px',
						'-webkit-border-radius': '11px'					
					},
					text: 'Choose note type'
				})
			),

			this.textChooser = new Element('div', {
				styles: {
					position: 'absolute',
					left: 32 + 15,
					top: 40 + 13,
					width: 142,
					height: 180,
					background: 'url(' + this.images + 'text-note-thumb.png) no-repeat 0 0',
					cursor: 'pointer'
				}
			}).adopt(
				new Element('div', {
					styles: {
						position: 'absolute',
						left: 28,
						top: 127,
						width: 85,
						fontFamily: 'Arial',
						fontSize: '14px',
						fontWeight: 'bold',
						textAlign: 'center',
						color: '#000000'
					},
					text: 'Text'
				})				
			).addEvent('click', this.textNote.bind(this)),
			
			this.listChooser = new Element('div', {
				styles: {
					position: 'absolute',
					left: 161 + 15,
					top: 40 + 13,
					width: 142,
					height: 180,
					background: 'url(' + this.images + 'list-note-thumb.png) no-repeat 0 0',
					cursor: 'pointer'
				}
			}).adopt(
				new Element('div', {
					styles: {
						position: 'absolute',
						left: 28,
						top: 127,
						width: 85,
						fontFamily: 'Arial',
						fontSize: '14px',
						fontWeight: 'bold',
						textAlign: 'center',
						color: '#000000'
					},
					text: 'List'
				})				
			).addEvent('click', this.listNote.bind(this)),
			
			this.closeChooserButton = new Element('div', {
				styles: {
					position: 'absolute',
					//left: 265,
					left: 275,
					top: 10,
					width: 58,
					height: 58,
					background: 'url(' + this.images + 'close-btn.png) no-repeat 0 0',
					cursor: 'pointer'
				}
			}).addEvent('click', this.close.bind(this))

		);
		
		this.chooser.inject(document.body);
	},

	noteBounds: function() {
		var win = window.getSize(),
				winScroll = window.getScroll();
		var bounds = {
			x: 0,
			y: 0,
			w: 375,
			h: 514
		};
		bounds.x = Math.round((win.x - bounds.w) / 2);
		bounds.y = Math.round((win.y - bounds.h) / 2);
		return bounds;
	},

	zoomIn: function(thumb) {
		this.updateNoteUI();

		var nextThumb = (thumb == this.textChooser) ? this.listChooser : this.textChooser;
	
		var bounds = this.noteBounds();

		var thumbBounds = thumb.getCoordinates();
		var clone = new Element('img', {
			styles: {
				position: 'absolute',
				left: thumbBounds.left,
				top: thumbBounds.top,
				width: thumbBounds.width,
				height: thumbBounds.height,
				zIndex: 2000
			},
			src: thumb.getStyle('background-image').replace(/url\("?([^"|\)]*)"?\)/i, '$1')
		}).inject(document.body);
		thumb.hide();

		this.chooserTitle.tween('opacity', 0);
		nextThumb.tween('opacity', 0);
		//this.chooserShadow.tween('opacity', 0);
		this.closeChooserButton.tween('opacity', 0);
		
		(function() {
			
			this.note.setStyles({
				display: 'block',
				opacity: 0
			});
			this.note.tween('opacity', 1);
			
			new Fx.Morph(clone, {
				transitions: Fx.Transitions.Expo.easeOut,
				duration: 200,
				onComplete: function() {
					clone.destroy();
					this.noteDisplayed.delay(80, this);
				}.bind(this)
			}).start({
				'left': bounds.x - 40,
				'top': bounds.y - 40,
				'width': bounds.w + 80,
				'height': bounds.h + 80,
				'opacity': 0
			});
			
		}).delay(200, this);
	},

	zoomOut: function(thumb) {
		var nextThumb = (thumb == this.textChooser) ? this.listChooser : this.textChooser;
	
		var bounds = this.noteBounds();

		thumb.setStyles({
			display: 'block',
			opacity: 0
		});

		var thumbBounds = thumb.getCoordinates();
		var clone = new Element('img', {
			styles: {
				position: 'absolute',
				left: bounds.x - 40,
				top: bounds.y - 40,
				width: bounds.w + 80,
				height: bounds.h + 80,
				zIndex: 2000,
				opacity: 0
			},
			src: thumb.getStyle('background-image').replace(/url\("?([^"|\)]*)"?\)/i, '$1')
		}).inject(document.body);

		this.closeNoteButton.tween('opacity', 0);
		this.note.tween('opacity', 0);
		
		(function() {
			new Fx.Morph(clone, {
				transitions: Fx.Transitions.Expo.easeOut,
				duration: 200,
				onComplete: function() {
					clone.destroy();
					thumb.setStyle('opacity', 1);
					
					this.chooserTitle.tween('opacity', 1);
					nextThumb.tween('opacity', 1);
					//this.chooserShadow.tween('opacity', 1);
					this.closeChooserButton.tween('opacity', 1);
	
					this.noteType = '';
					
					this.note.hide();

				}.bind(this)
			}).start({
				left: thumbBounds.left,
				top: thumbBounds.top,
				width: thumbBounds.width,
				height: thumbBounds.height,
				opacity: 1
			});
		}).delay(100, this);
	},

	textNote: function() {
		this.noteType = 'text';
		this.textEdit.hide();
		this.listEdit.hide();
		this.zoomIn(this.textChooser);
	},
	
	listNote: function() {
		this.noteType = 'list';
		this.textEdit.hide();
		this.listEdit.hide();
		this.zoomIn(this.listChooser);
	},

	noteDisplayed: function() {
		// Show send button hint
		this.sendHint.setStyles({
			display: 'block'
		}).set('tween', {
			transition: Fx.Transitions.Bounce.easeOut,
			duration: 600
		}).tween('left', [150, 228]);
		
		this.closeNoteButton.tween('opacity', 1);
		
		/*try {
			this.toInput.focus();
		} catch(e) {}*/
	},

	confirmCancelIfNeeded: function(message, cb) {
		if (this.sentNote) {
			cb();
			return;
		}
	
		if (this.noteType == 'text') {
			if ((this.toInput.value.trim() != '') ||
					//(this.fromInput.value.trim() != '') ||
					(this.textEdit.value.trim() != '')) {
				this.confirm(message, cb);
				return;
			}
		} else if (this.noteType == 'list') {
			var items = this.listItems.getElements('.notsu-list-item-editor');
			var newItem = this.listItems.getElement('.notsu-list-last-item .notsu-list-item-editor');
			items.erase(newItem);
			items = items.map(function(item) { return item.value; }).filter(function(item) { return item.trim() != ''; });
			if ((this.toInput.value.trim() != '') ||
					//(this.fromInput.value.trim() != '') ||
					(this.listTitle.value.trim() != '') ||
					(items.length > 0)) {
				this.confirm(message, cb);
				return;
			}
		}

		cb();
	},

	switchToChooser: function() {
		this.confirmCancelIfNeeded('You have unsent note, cancel it and create another?', function() {
			new Form.Validator.Callout(this.note).reset();
			
			if (this.noteType == 'text') {
	
				this.zoomOut(this.textChooser);
			}
	
			if (this.noteType == 'list') {
	
				this.zoomOut(this.listChooser);
			}
		}.bind(this));
	},
	
	close: function() {
		this.confirmCancelIfNeeded('You have unsent note, cancel it?', function() {
			new Form.Validator.Callout(this.note).reset();
	
			var fx1 = new Fx.Tween(this.chooser, {
				onComplete: function() {
					this.chooser.hide();
				}.bind(this)
			});
	
			var fx2 = new Fx.Tween(this.note, {
				onComplete: function() {
					this.note.hide();
				}.bind(this)
			});
	
		  new Fx.Tween(this.mask.element, {
		  	onComplete: function() {
		  		this.mask.destroy();
		  	}.bind(this)
		  }).start('opacity', 0);
			
			fx1.start('opacity', 0);
			fx2.start('opacity', 0);
		}.bind(this));
	},

	buildNote: function() {
		var winScroll = window.getScroll();
		var bounds = this.noteBounds();
	
		this.note = new Element('div', {
			styles: {
				display: 'none',
				zIndex: 1500,
				position: 'absolute',
				left: winScroll.x + bounds.x,
				top: winScroll.y + bounds.y,
				width: bounds.w,
				height: bounds.h
			}
		}).adopt(
			new Element('div', {
				styles: {
					position: 'absolute',
					left: 0,
					top: 0,
					width: bounds.w,
					height: bounds.h,
					
					background: 'url(' + this.images + 'note-bk.png) no-repeat 0 0'					
				}
			})
		);
		
		this.note.adopt(
			// text note watermark
			this.watermark = new Element('div', {
				styles: {
					position: 'absolute',
					left: 245,
					top: 28,
					width: 88,
					height: 93,
					background: 'url(' + this.images + 'text-watermark.png) no-repeat 0 0'
				}
			}),
		
			// from: label
			new Element('div', {
				styles: {
					position: 'absolute',
					left: 30,
					top: 42,
					width: 40,
					textAlign: 'right',
					fontFamily: 'Arial',
					fontSize: '14px',
					color: '#000000'
				},
				text: 'from:'
			}),
			// to: label
			new Element('div', {
				styles: {
					position: 'absolute',
					left: 30,
					top: 82,
					width: 40,
					textAlign: 'right',
					fontFamily: 'Arial',
					fontSize: '14px',
					color: '#000000'
				},
				text: 'to:'
			}),
			
			// (your name)
			this.fromPlaceholder = new Element('div', {
				styles: {
					position: 'absolute',
					left: 90,
					top: 42,
					width: 240,
					fontFamily: 'Arial',
					fontSize: '14px',
					color: '#B4B3AC'
				},
				text: 'your name'
			}),
			// (recipient's email)
			this.toPlaceholder = new Element('div', {
				styles: {
					position: 'absolute',
					left: 90,
					top: 82,
					width: 240,
					fontFamily: 'Arial',
					fontSize: '14px',
					color: '#B4B3AC'
				},
				text: 'recipient\'s email'
			}),
			
			// from input
			this.fromInput = new Element('input', {
				'class': 'required',
				styles: {
					position: 'absolute',
					left: 89,
					top: 41,
					width: 245,
					fontFamily: 'Arial',
					fontSize: '14px',
					color: '#000000',
					background: 'none',
					border: 'none',
					outline: 'none'
				},
				maxLength: 34
			}),
			// to input
			this.toInput = new Element('input', {
				'class': 'required validate-email',
				styles: {
					position: 'absolute',
					left: 89,
					top: 81,
					width: 245,
					fontFamily: 'Arial',
					fontSize: '14px',
					color: '#000000',
					background: 'none',
					border: 'none',
					outline: 'none'
				}
			}),

			// month
			this.month = new Element('div', {
				styles: {
					position: 'absolute',
					left: 27,
					top: 123,
					width: 40,
					textAlign: 'right',
					fontFamily: 'Arial',
					fontSize: '12px',
					fontWeight: 'bold',
					color: '#B77D66'
				},
				text: this.months[this.timestamp.getMonth()].substr(0, 3).toLowerCase()
			}),
			// day
			this.day = new Element('div', {
				styles: {
					position: 'absolute',
					left: 29,
					top: 132,
					width: 40,
					textAlign: 'right',
					fontFamily: 'Arial',
					fontSize: '25px',
					fontWeight: 'bold',
					color: '#B77D66'
				},
				text: this.timestamp.getDate()
			}),
			// year
			this.year = new Element('div', {
				styles: {
					position: 'absolute',
					left: 27,
					top: 156,
					width: 40,
					textAlign: 'right',
					fontFamily: 'Arial',
					fontSize: '12px',
					fontWeight: 'bold',
					color: '#B77D66'
				},
				text: this.timestamp.getFullYear()
			}),
			
			// text editor
			this.textEdit = new Element('textarea', {
				styles: {
					display: 'none',
					position: 'absolute',
					left: 89,
					top: 125,
					width: 245,
					height: 315,
					fontFamily: 'Arial',
					fontSize: '14px',
					color: '#000000',
					border: 'none',
					background: 'none',
					outline: 'none',
					resize: 'none'
					/*,
					'::-webkit-scrollbar': {
				    width: 13,
				    height: 13
					}*/
					
				},
				
				'class': 'notsu-note required adviceOffset:22 maxLength:2000'
			}),

			// list editor
			this.listEdit = new Element('div', {
				styles: {
					display: 'none',
					position: 'absolute',
					left: 29,
					top: 125,
					width: 316,
					height: 315,
					fontFamily: 'Arial',
					fontSize: '14px',
					color: '#000000'
				}
			}).adopt(
			
				// list title
				this.listTitlePlaceholder = new Element('div', {
					styles: {
						position: 'absolute',
						left: 60,
						top: 0,
						width: 240,
						fontFamily: 'Arial',
						fontSize: '17px',
						color: '#B4B3AC'
					},
					text: 'list title'
				}),
				this.listTitle = new Element('input', {
					styles: {
						position: 'absolute',
						left: 60,
						top: 0,
						width: 245,
						fontFamily: 'Arial',
						fontSize: '17px',
						color: '#000000',
						background: 'none',
						border: 'none',
						outline: 'none'
					},
					'class': 'required',
					maxLength: 34
				}),
				
				// list items container
				this.listItems = new Element('div', {
					'class': 'notsu-list-items',
					styles: {
						position: 'absolute',
						left: 0,
						top: 60,
						width: 316,
						height: 250,
						overflow: 'auto',
						'overflow-x': 'hidden',

						borderTop: '1px solid #D7D6BF'
					}
				})
			
			),
			
			// send button
			this.sendButton = new Element('div', {
				styles: {
					position: 'absolute',
					left: 303,
					top: 448,
					width: 43,
					height: 38,
					background: 'url(' + this.images + 'send-btn.png) no-repeat 0 0',
					cursor: 'pointer'
				}
			}).addEvent('click', this.sendNote.bind(this)),
			this.sendHint = new Element('div', {
				styles: {
					display: 'none',
					position: 'absolute',
					left: 228,
					//top: 458,
					top: 454,
					height: 13,
					padding: '5px 0',
					paddingRight: 11,
					background: 'url(' + this.images + 'right-arrow.png) no-repeat right center',
					fontFamily: 'Arial',
					fontSize: '12px',
					fontWeight: 'bold',
					color: '#4E4A3F',
					opacity: 0.8,
					cursor: 'pointer'
				},
				text: 'Send note'
			}).addEvent('click', this.sendNote.bind(this)),
			
			this.newNoteButton = new Element('div', {
				styles: {
					position: 'absolute',
					left: 28,
					top: 446,
					width: 41,
					height: 38,
					cursor: 'pointer'
				}
			}).addEvent('click', this.switchToChooser.bind(this)),

			this.closeNoteButton = new Element('div', {
				styles: {
					position: 'absolute',
					left: 335,
					top: -15,
					width: 58,
					height: 58,
					opacity: 0,
					background: 'url(' + this.images + 'close-btn.png) no-repeat 0 0',
					cursor: 'pointer'
				}
			}).addEvent('click', this.close.bind(this)),


			// Sending...
			this.sending = new Element('div', {
				styles: {
					display: 'none',
					position: 'absolute',
					left: 0,
					top: -10,
					width: bounds.w + 20,
					height: bounds.h + 10,
					textAlign: 'center'
				}
			}).adopt(
				new Element('div', {
					styles: {
						position: 'absolute',
						left: 0,
						top: -10,
						width: bounds.w + 20,
						height: bounds.h + 10,
						
						background: '#000000',
						opacity: 0.01
					}
				}),
				new Element('span', {
					styles: {
						position: 'relative',
						top: 260,
						fontFamily: 'Helvetica, Arial, sans-serif',
						fontSize: '14px',
						fontWeight: 'bold',
						color: '#dddddd',
						background: '#000000 url(' + this.images + 'sending.gif) no-repeat 15px center',
						padding: '18px 20px 15px',
						paddingLeft: 50,
						'border-radius': '8px',
						'-moz-border-radius': '8px',
						'-webkit-border-radius': '8px'
					},
					html: 'Sending...'
				})
			),

			// Sent
			this.chooserHint = new Element('div', {
				styles: {
					display: 'none',
					position: 'absolute',
					left: 140,
					top: 451,
					height: 13,
					padding: '5px 0',
					paddingLeft: 11,
					background: 'url(' + this.images + 'left-arrow.png) no-repeat left center',
					fontFamily: 'Arial',
					fontSize: '12px',
					fontWeight: 'bold',
					color: '#4E4A3F',
					opacity: 0.8
				},
				text: 'Send another?'
			}),
			this.sent = new Element('div', {
				styles: {
					display: 'none',
					position: 'absolute',
					left: 0,
					top: -10,
					width: bounds.w - 25,
					height: bounds.h,
					background: '#000000',
					opacity: 0.01
				}
			}).adopt(
				new Element('div', {
					styles: {
						position: 'absolute',
						left: 30,
						top: 450,
						width: 160,
						height: 45,
						cursor: 'pointer'
					}
				}).addEvent('click', function() {
					this.sentState(false);
					this.switchToChooser();
					this.chooserHint.hide();
				}.bind(this))
			),
			this.sentStamp = new Element('img', {
				styles: {
					display: 'none',
					position: 'absolute',
					left: 40,
					top: 50,
					width: 112,
					height: 54
				},
				src: this.images + 'sent-stamp.png'
			})

		);

		if (Browser.Engine.webkit) {
			// Stylize scrollbar for WebKit
			new Element('style', {
				type: 'text/css',
				text: '.notsu-list-items::-webkit-scrollbar, textarea.notsu-note::-webkit-scrollbar { \
					width: 6px; \
				} \
				.notsu-list-items::-webkit-scrollbar-track-piece, textarea.notsu-note::-webkit-scrollbar-track-piece { \
					background-color: #C5C2A1; \
					-webkit-border-radius: 6px; \
					margin-top: 2px; \
					margin-bottom: 2px; \
				} \
				.notsu-list-items::-webkit-scrollbar-thumb:vertical, textarea.notsu-note::-webkit-scrollbar-thumb:vertical { \
					height: 50px; \
					background-color: #2C2B24; \
					-webkit-border-radius: 6px; \
				}'
			}).inject(document.head);
		}


		this.fromInput.store('handlers', {
			focus: function() {
				this.fromPlaceholder.hide();
			}.bind(this),
			
			blur: function() {
				if (this.fromInput.value.trim() == '') {
					this.fromPlaceholder.show();
				}
			}.bind(this)
		});
		this.fromInput.addEvents(this.fromInput.retrieve('handlers'));

		this.toInput.store('handlers', {
			focus: function() {
				this.toPlaceholder.hide();
			}.bind(this),
			
			blur: function() {
				if (this.toInput.value.trim() == '') {
					this.toPlaceholder.show();
				}
			}.bind(this)
		});
		this.toInput.addEvents(this.toInput.retrieve('handlers'));

		this.listTitle.store('handlers', {
			focus: function() {
				this.listTitlePlaceholder.hide();
			}.bind(this),
			
			blur: function() {
				if (this.listTitle.value.trim() == '') {
					this.listTitlePlaceholder.show();
				}
			}.bind(this)
		});
		this.listTitle.addEvents(this.listTitle.retrieve('handlers'));

		this.note.inject(document.body);
	},

	updateNoteUI: function() {
		var fromName = Cookie.read('notsu-from');
		if (!fromName) fromName = '';
		this.fromInput.value = fromName;
		this.toInput.value = '';
		this.fromPlaceholder.hide();
		this.toPlaceholder.hide();
		
		this.sentNote = false;
		
		var handlers;
		handlers = this.fromInput.retrieve('handlers');
		if (handlers) handlers.blur();
		handlers = this.toInput.retrieve('handlers');
		if (handlers) handlers.blur();

		switch(this.noteType) {
			case 'text':
			
				this.watermark.setStyle('background-image', 'url(' + this.images + 'text-watermark.png)');
				
				this.textEdit.value = '';
				
				this.listEdit.hide();
				this.textEdit.show();
			
				break;
			case 'list':
			
				this.watermark.setStyle('background-image', 'url(' + this.images + 'list-watermark.png)');

				this.list = [];
				
				// DEBUG
//				this.list = ['Item 1', 'Item 2', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'];
				// DEBUG

				this.updateListUI();

				this.textEdit.hide();
				this.listEdit.show();
			
				break;
		}
	},

	showNote: function() {
		this.note.show();
		
		// Show send button hint
		this.sendHint.setStyles({
			display: 'block'
		}).set('tween', {
			transition: Fx.Transitions.Bounce.easeOut,
			duration: 600
		}).tween('left', [150, 228]);
	},

	show: function() {
		this.mask = new Mask($(document.body), {
			style: {
				background: '#000000',
				opacity: 0,
				zIndex: 1000
			},
			onShow: function() {
				this.element.set('tween', { duration: 200 }).tween('opacity', 0.8);
			}
		}).show();
		this.mask.element.setStyle('position', 'fixed');

		this.chooser.setStyles({
			display: 'block',
			opacity: 0
		}).tween('opacity', 1);
	},
	
	hide: function() {
		// DEBUG
		this.chooser.hide();
		//$(document.body).unmask();
		this.mask.hide();
	},
	
	updateListUI: function() {
		this.listTitle.value = '';
		var handlers = this.listTitle.retrieve('handlers');
		if (handlers) handlers.blur();
		
		this.listItems.empty();
		this.list.each(function(item) {
			this.addListItem(item);
		}.bind(this));
		this.addNewItemRow();
	},
	
	addListItem: function(item, sibling, where) {
		if (!where && sibling) {
			where = 'before';
		}
	
		var row = new Element('div', {
			styles: {
				position: 'relative',
				width: 316,
				overflow: 'hidden',
				padding: '3px 0',
				borderBottom: '1px solid #D7D6BF'
			},
			'class': 'notsu-list-item'
		});
		
		var origHeight;
		
		var input = new Element('textarea', {
			'class': 'notsu-list-item-editor maxLength:120',
			name: 'list[]',
			styles: {
				position: 'relative',
				marginLeft: 60,
				width: 240,
				'min-height': 16,
				height: 16,
				fontFamily: 'Arial',
				fontSize: '14px',
				color: '#000000',
				padding: '3px 0',
				border: 'none',
				background: 'none',
				outline: 'none',
				resize: 'none',
				overflow: 'hidden'
			}
		});
		
		var meter = input.clone();
		meter.setStyles({
			position: 'absolute',
			opacity: 0,
			left: 0,
			top: 3,
			'min-height': 0,
			overflow: 'auto'
		}).set('name', '').set('class', '');
		
		var updateSize = function() {
			var delta = Browser.Engine.webkit ? 6 : 0;
			meter.setStyle('height', 0).set('value', input.value).scrollTo(0, 10000);
			input.setStyle('height', Math.max(origHeight, meter.getScrollSize().y - delta));
		};
		
		input.addEvents({
			keydown: function(event) {
				// Escape
				if (event.code == 27) {
					event.stop();
					if (input.value.trim() == '') {
						row.destroy();
					}
					return;
				}
				// Enter
				if (event.code == 13) {
					event.stop();
					if (!row.hasClass('notsu-list-last-item')) {
					  var newRow = this.addListItem('', row, 'after');
					  this.focusRow(newRow, true);
					}
					return;
				}
				// Backspace
				if (event.code == 8) {
					if (input.value.trim() == '') {
						event.stop();
						var prev = row.getPrevious();
						row.destroy();
						this.focusRow(prev);
						return;
					}
				}
				// Tab
				if (event.code == 9) {
					event.stop();
					var next;
					if (event.shift) {
						next = row.getPrevious();
					} else {
						next = row.getNext();
					}
					if (next) {
						if (next.hasClass('notsu-list-new-row')) {
							next = this.addListItem('', next);
						}
						this.focusRow(next, true);
					}
					return;
				}
				
				updateSize();
			}.bind(this),
			keypress: function(event) {
				// Opera fix
				if (event.code == 13) {
					event.stop();
				}			
			}.bind(this),
			keyup: function() {
				if (input.value.trim() != '') {
					row.removeClass('notsu-list-last-item');
					var handlers = input.retrieve('handlers');
					if (handlers) {
						input.removeEvents(handlers);
						input.eliminate('handlers');
					}
					this.addNewItemRow();
				}

				updateSize();
			}.bind(this),
			change: updateSize,
			blur: function() {
				if (input.value.trim() == '' && !row.hasClass('notsu-list-last-item')) {
					row.destroy();
				}
			}
		});

		row.adopt(
			meter,
			input
		);
		if (sibling) {
			row.inject(sibling, where);
		} else {
			row.inject(this.listItems);
		}
		
		origHeight = 16;
		
		input.value = item;
		updateSize.delay(10);
		
		return row;
	},
	
	focusRow: function(row, begin) {
		if (!row) return;
		var tx = row.getElement('textarea.notsu-list-item-editor');
		if (tx) {
			tx.focus();
			if (begin) {
				tx.setCaretPosition(0);
			} else {
				tx.setCaretPosition('end');
			}
		}
	},
	
	addNewItemRow: function() {
		var last = this.listItems.getElement('.notsu-list-last-item');
		if (last) return;
		
		var row = this.addListItem('add new item');
		row.addClass('notsu-list-last-item');
		var input = row.getElement('.notsu-list-item-editor');
		if (input) {
			input.store('handlers', {
				focus: function() {
					input.value = '';
					input.setStyle('color', '#000000');
				},
				blur: function() {
					input.value = 'add new item';
					input.setStyle('color', '#B4B3AC');
				}
			});
			input.setStyle('color', '#B4B3AC').addEvents(input.retrieve('handlers'));
		}
	},
	
	sendNote: function() {
		var newItem;
		if (this.noteType == 'list') {
			newItem = this.listItems.getElement('.notsu-list-last-item');
			if (newItem) {
				// remove required from new item plceholder
				newItem.getElement('.notsu-list-item-editor').removeClass('required').set('value', '');
			}
			var items = this.listItems.getElements('.notsu-list-item').erase(newItem);
			// if list items count == 0 - add required to new item placeholder
			if (items.length == 0) {
				newItem.getElement('.notsu-list-item-editor').addClass('required');
			}
		}

		var validator = new Form.Validator.Callout(this.note, {
			errorPrefix: '',
			serial: false,
			onFormValidate: function() {
				if (newItem) {
					newItem.getElement('.notsu-list-item-editor').set('value', 'add new item');
				}
			}
		});
		if (!validator.validate()) {
			return;
		};

		var noteDate = new Date();
		var data = {
			'datetime': noteDate.getDate() + '.' + (noteDate.getMonth() + 1) + '.' + noteDate.getFullYear() + ' ' +
									noteDate.getHours() + ':' + noteDate.getMinutes() + ':' + noteDate.getSeconds(),
			'from': this.fromInput.value,
			'to': this.toInput.value
		};

		if (this.noteType == 'text') {
			data.type = 'text';
			data.note = this.textEdit.value;
		} else if (this.noteType == 'list') {
			var items = this.listItems.getElements('.notsu-list-item-editor');
			var newItem = this.listItems.getElement('.notsu-list-last-item .notsu-list-item-editor');
			items.erase(newItem);
			items = items.map(function(item) { return item.value; }).filter(function(item) { return item.trim() != ''; });
		
			data.type = 'list';
			data.title = this.listTitle.value;
			data.note = items;
		}
	
		/*var scripts = document.getElementsByTagName('script');
		scripts.each(function(script) {
			if (script.src.indexOf('notsu-mail.js') != -1) {
				data.sign = 
			}
		});*/
		
//		data.sign = 
		
		// ... sending
		//console.log(data, JSON.encode(data));

		this.sendingState(true);
		
		new Request({
			url: 'send-note.php',
			method: 'post',
			data: data,
			onSuccess: function() {
				this.sentNote = true;
				this.sendingState.delay(300, this, [false]);
				this.sentState.delay(900, this, [true]);
				
				Cookie.write('notsu-from', this.fromInput.value, {path: '/', duration: 366});
			}.bind(this),
			onFailure: function(transport) {
				this.sendingState(false);
				this.alert('Error: ' + transport.responseText);
			}.bind(this)
		}).send();
		
		// if success - Cookie.write('notsu-from', this.fromInput.value, {path: '/', duration: 366});
	},
	
	sendingState: function(value) {
		if (value) {
			this.sending.setStyles({
				display: 'block',
				opacity: 0
			}).tween('opacity', 1);
			this.closeNoteButton.tween('opacity', 0);
			this.sendHint.tween('opacity', 0);
			this.sendButton.tween('opacity', 0.4);
		} else {
			this.closeNoteButton.tween('opacity', 1);
			this.sendHint.tween('opacity', 1);
			this.sendButton.tween('opacity', 1);
			new Fx.Tween(this.sending, {
				onComplete: function() {
					this.sending.setStyle('display', 'none');
				}.bind(this)
			}).start('opacity', 0);
		}
	},

	sentState: function(value) {
		if (value) {
			this.sent.show();
			this.sendHint.tween('opacity', 0);
			this.sendButton.tween('opacity', 0);
			
			this.sentStamp.setStyles({
				display: 'block',
				opacity: 0
			});
			var bounds = this.sentStamp.getCoordinates(this.sentStamp.getParent());
			this.sentStamp.setStyles({
				left: bounds.left - 60,
				top: bounds.top - 60,
				width: bounds.width + 120,
				height: bounds.height + 120
			});
			
			this.fromInput.setStyle('opacity', 0.5);
			this.toInput.setStyle('opacity', 0.5);
			this.textEdit.setStyle('opacity', 0.5);
			this.listEdit.setStyle('opacity', 0.5);
			
			new Fx.Morph(this.sentStamp, {
				transition: Fx.Transitions.Quint.easeOut,
				duration: 120
			}).start({
				left: bounds.left,
				top: bounds.top,
				width: bounds.width,
				height: bounds.height,
				opacity: 1				
			});
			
			this.chooserHint.setStyles({
				display: 'block'
			}).set('tween', {
				transition: Fx.Transitions.Bounce.easeOut,
				duration: 600
			}).tween('left', [140, 90]);

		} else {
			this.closeNoteButton.tween('opacity', 1);
			this.sendHint.tween('opacity', 1);
			this.sendButton.tween('opacity', 1);
			this.sent.hide();
			this.sentStamp.hide();
			
			this.fromInput.setStyle('opacity', 1);
			this.toInput.setStyle('opacity', 1);
			this.textEdit.setStyle('opacity', 1);
			this.listEdit.setStyle('opacity', 1);
		}
	},
	
	msgBox: function(message, buttons) {
		var alert;
		var mask = new Mask(document.body, {
			style: {
				background: '#000000',
				opacity: 0.01,
				zIndex: 5490
			}
		}).show();
	
		var closeFunc = function() {
			mask.destroy();
			new Fx.Tween(alert, {
				transition: Fx.Transitions.Expo.easeOut,
				onComplete: function() {
					alert.destroy();
				}
			}).start('opacity', 0);
		};

		var btns = [];
		$H(buttons).each(function(fn, title) {
			btns.push(
				new Element('span', {
					styles: {
						padding: '4px 15px 2px',
						fontFamily: 'Helvetica, Arial, sans-serif',
						fontSize: '13px',
						color: '#000000',
						background: '#ffffff',
						cursor: 'pointer',

						'border-radius': '16px',
						'-moz-border-radius': '16px',
						'-webkit-border-radius': '16px',
						
						marginRight: 10
					},
					html: title
				}).addEvent('click', function() {
					closeFunc();
					fn();
				})
			);
		});
	
		var winSize = window.getSize();
		var box = {
			width: 250,
			height: 60
		};
		alert = new Element('div', {
			styles: {
				opacity: 0,
				position: 'absolute',
				left: Math.round((winSize.x - box.width - 46) / 2),
				top: Math.round((winSize.y - box.height - 46) / 2),
				width: box.width,
				zIndex: 5500,

				fontFamily: 'Helvetica, Arial, sans-serif',
				fontSize: '14px',
				color: '#FFFFFF',
				background: '#000000',
				border: '3px solid #FFFFFF',
				padding: 20,
				'border-radius': '8px',
				'-moz-border-radius': '8px',
				'-webkit-border-radius': '8px',
				'box-shadow': Browser.Engine.presto ? '0 0 8px #000000' : '0 0 25px #000000',
				'-moz-box-shadow': '0 0 25px #000000',
				'-webkit-box-shadow': '0 0 25px #000000'
			}
		}).adopt(
			new Element('div', { align: 'center', html: message }),
			new Element('div', {
				align: 'center',
				styles: {
					marginTop: 20,
					marginBottom: 5
				}
			}).adopt(btns)
		).inject(document.body);
		
		new Fx.Tween(alert, {
			transition: Fx.Transitions.Sine.easeOut
		}).start('opacity', 1);
	},
	
	alert: function(message) {
		this.msgBox(message, {
			'OK': function() {}
		});
	},
	
	confirm: function(message, cb) {
		this.msgBox(message, {
			'Yes': cb,
			'No': function() {}
		});
	}

});

NotsuMail.images = 'i/send/';

NotsuMail.popup = function() {
	if (Browser.Engine.trident4) {
		alert('Requires a modern browser such as Internet Explorer 8, Mozilla Firefox 3, Safari 4, Opera 10 or Chrome 4.');
		return;
	}

	var n = new NotsuMail();
	n.show();
	return n;
}

NotsuMail.preload = function() {
	Asset.images([
		//NotsuMail.images + 'type-bk.png',
		NotsuMail.images + 'text-note-thumb.png',
		NotsuMail.images + 'list-note-thumb.png',
		NotsuMail.images + 'text-watermark.png',
		NotsuMail.images + 'list-watermark.png',
		NotsuMail.images + 'send-btn.png',
		NotsuMail.images + 'sent-stamp.png',
		NotsuMail.images + 'note-bk.png',
		NotsuMail.images + 'sending.gif',
		NotsuMail.images + 'callout-pointer.png'
	]);
}

window.addEvent('domready', NotsuMail.preload);

