/**
	notesView
*/
var notesView = (function(){

	/** helper functions */
	var 
	 showAllNotes = function(){
		$list.empty();
		notes.each(function(){
			//	append note to list
			addNoteToList(this);
		});
	}
	,showFilteredNotes = function(filter) {
		notes.save();
		log('showFilteredNotes : '+filter);
		if ( !filter ) {
			showAllNotes();
			return false;
		}
		
		if ( filter.slice(0,6) === 'title:' ) {
			filter = { title: filter.slice(6) };
		} else if ( filter.slice(0,8) === 'content:' ) {
			filter = { content: filter.slice(8) };
		} else if ( filter.slice(0,4) === 'tag:' ) {
			filter = { tag: filter.slice(4) };
		}
		
		var  a = notes.find(filter)
			,i=0, ile=a.length
		;
		//	clear list of notes
		$list.empty();
		
		if ( ile === 0 ) {
			$list.append('<p class="searchResult">Really? Try to find something else!</p>');
		} else {
			//	show notes
			for(;i<ile;i++) {
				addNoteToList(a[i]);
			}
		}
		
	}
	,openNote = function(note){
		if ( typeof note.css === 'undefined' ) {
			note.css = {};
		}
		
		var 
			//	generating html
			noteView = $('<div class="note"><h5 class="note_title">'+note.getTitle()+'</h5><div class="note_contentContainer"><div class="note_content">'+note.getContent()+'</div></div><div class="note_tags"><span class="note_tags_a">'+note.getTags().join('</span><span class="note_tags_a">')+'</span></div></div>')
				.data('note', note)
				//	click note to bring it in front
				.mousedown(function(e){
					//	get current z-index
					var zIndex = parseInt( $(this).css('zIndex'), 10 );
					log('z-index: '+zIndex+', currentMaxZIndex: '+currentMaxZIndex);
					if ( zIndex < currentMaxZIndex ) {
						currentMaxZIndex++;
						$(this).css('zIndex', currentMaxZIndex);
						note.css.zIndex = currentMaxZIndex;
					}
				})
				//	double click on note to start editing
				.dblclick(function(e){
					var  content = $(this).find('.note_content')
						,textA = $('<textarea class="note_content_text">'+content.html()+'</textarea>')
						,height = noteView.height() - 60
					;
					content.replaceWith(textA);
					textA.height(height);
					
					//	save note on blur or 'esc' key
					textA
						.focus()
						.blur(function(){
							noteManager({
								 action: 'inlineEdit'
								,textA: $(this)
								,note: note
							});
						})
						.keydown(function(e){
							if ( e.keyCode === 27 ) {
								noteManager({
									 action: 'inlineEdit'
									,textA: $(this)
									,note: note
								});
							}
						});
				})
				//	set position
				.css({ position: 'absolute', left: currentPosLeft+'px', top: currentPosTop+'px', zIndex: currentMaxZIndex })
			
			,$link_close = $('<span class="note_icon note_close ui-icon ui-icon-power "></span>')
				.appendTo( noteView )
				.click(function(e){
					note.opened = false;
					note.li
						.removeClass('active')
						.find('span').remove();
					noteView.hide();
					e.stopPropagation(); e.preventDefault();
				})
			$link_edit = $('<span class="note_icon note_edit ui-icon ui-icon-pencil"></span>')
				.appendTo( noteView )
				.click(function(e){
					noteManager({ action: 'edit', note: note, noteView: noteView });
					e.stopPropagation(); e.preventDefault();
				})
		;
		
		//	check css options for note.
		//.css('position', 'absolute').css(note.css)
		//	check z-index
		if ( note.css.zIndex > currentMaxZIndex ) {
			currentMaxZIndex = note.css.zIndex;
			noteView.css('zIndex', currentMaxZIndex);
		}
		
		
		noteView
			.draggable({ 
				handle: 'h5'
				,start: function(event, ui) {
					$(ui.helper).css({ position:'absolute' }).addClass('dragging');;
				}
				,stop: function(event, ui) {
					$(ui.helper).removeClass('dragging');
					note.css.left = ui.position.left;
					note.css.top = ui.position.top;
				}
			})
			.resizable({
				stop: function(event, ui) {
					note.css.width = ui.size.width;
					note.css.height = ui.size.height;
				}
			});
		
		note.noteView = noteView;
		$noteViews.append( noteView );
	}
	,addNoteToList = function(note){
		//	generate html
		var $li = $('<li class="notesList_li" rel="0">'+note.getTitle()+'</li>')
			//	add events
			.click(function(){
				if ( note.opened === true ) {
					note.noteView.trigger('mousedown');
					return false;
				}
				//	mark as opened
				note.opened = true;
				note.li = $(this);
				//	mark list item as opened
				$(this).addClass('active');
				$(this).prepend('<span class="sidebar_icon ui-icon ui-icon-carat-1-e"></span>');
				//	open note
				openNote(note);
			})
			.data('note', note)
			//.button()
		;
		//	open or not to open ? 
		if ( note.opened === true ) {
			//	open note only when it is not already opened
			$li.addClass('active').prepend('<span class="sidebar_icon ui-icon ui-icon-carat-1-e"></span>');
			if ( typeof note.noteView === 'undefined' ) {
				note.li = $(this);
				openNote(note);
			}
		}
		if ( $list.find('li').length === 0 ) {
			$li.addClass('notesList_li_first');
		}
		$list.append( $li );
		return true;
	}
	,noteManager = function(options) {
		/**	*/
		var title, buttons;
		if ( !options || !options.action ) {
			return false;
		}
		
		//	create new note
		if ( options.action === 'new' ) {
			$('#nm_title').val('');
			$('#nm_content').val('');
			$noteManagerTags.find('.note_tags_a').remove();
			title = 'Add note';
			buttons = {
				"Ok" : function() {
					var note = {};
					var title = $.trim( $('#nm_title').val() );
					if ( title !== '' ) {
						note.title = title;
					}
					note.content = $('#nm_content').val();
					// get tags
					var tags = [];
					$(this).find('.note_tags_a').each(function(){
						tags.push( $(this).text() );
					});
					note.tags = tags;

					notes.addNote(note);
					addNoteToList(notes.getLast());
					
					$(this).dialog("close"); 
				}
			};
		}
		//	modify exitsing note by 'edit' form
		if ( options.action === 'edit' ) {
			var n = options.note, $tag;
			$('#nm_title').val(n.getTitle());
			$('#nm_content').val(n.getContent());
			$noteManagerTags.empty();
			//	tags
			n.eachTag(function(){
				$tag = $('<a href="#" class="note_tags_a">'+this+'</a>');
				$noteManagerTags.append($tag);
			});				
			title = 'Edit note';
			buttons = {
				"Ok" : function() {
					var  title = $.trim( $('#nm_title').val() )
						,content = $('#nm_content').val()
					;
					if ( title === '' ) {
						title = '*untitled*';
					}
					// get tags and set tags
					options.note.setTags([]);
					
					var tagTxt, tagsView = '';
					$noteManagerTags.find('.note_tags_a').each(function(){
						tagTxt = $(this).text();
						if ( options.note.addTag( tagTxt ) !== false ) {
							tagsView+='<span class="note_tags_a">'+tagTxt+'</span>';
						}
					});
					
					//	update note
					options.note.setTitle(title).setContent( content );
					//	update list and visible note
					options.note.li.html(title);
					options.noteView
						.find('h5').html( title ).end()
						.find('.note_content').html(content).end()
						.find('.note_tags').empty().append(tagsView)
					;
					$(this).dialog("close"); 
				}
			};
		}
		//	inline edit
		if ( options.action === 'inlineEdit' ){
			options.note.setContent( options.textA.val() );
			options.textA.replaceWith('<div class="note_content">'+options.note.getContent()+'</div>');
			return true;
		}
		
		//	open modal :)
		$('#noteManager').dialog({
			buttons: buttons
			,modal: true
			,title: title
			//,zIndex: 99999999
			,width: 'auto'
		});
	}
	;
	
	/** initialize */
	var 
		 $container = $('#notes')
		,$sidebar = $('#sidebarNav')
		,$noteManagerTags = $('#noteManager_content_tags')
		,$divClear = $('<div class="clearer"></div>')
		
		,currentMaxZIndex = 1			//	z-index value for new 'front' note
		,currentPosLeft = 210			//	left position for new note
		,currentPosTop = 0				//	top position for new note
		
		,searchTimeout = false
	
		//	generate list container
		$list = $('<ul id="notesList"></ul>')
		//	generate notes container
		$noteViews = $('<div id="notesContainer"></div>')
	;
	
	
	//	input filter
	$search = $('<input type="text" id="noteFilter" />');
	// 	init view - inserting to DOM 
	$container.append( $noteViews, $divClear.clone() );
	//	sidebar initialization
	$sidebar.append( $search, $list );
	
	/** events */
	//	attach events to buttons etc (if not attached)
	$(document).on('click', '#notes_newNote', function(){
		noteManager({ action:'new'});			
	});
	//	@menu -> help
	$(document).on('click', '#notes_help', function(){
		$('#noteHelp').dialog({ 
			 modal: true 
			,title: 'Help'
			,zIndex: 99999999
		});
	});
	//	tab key on textarea 
	$(document).on('keydown', '#nm_content, .note_content_text', function(e) {
		if(e.keyCode === 9) { // tab was pressed
			// get caret position/selection
			var  start = this.selectionStart
				,end = this.selectionEnd
				,$this = $(this)
			;

			// set textarea value to: text before caret + tab + text after caret
			$this.val($this.val().substring(0, start)
						+ "\t"
						+ $this.val().substring(end));

			// put caret at right position again
			this.selectionStart = this.selectionEnd = start + 1;

			// prevent the focus lose
			e.preventDefault(); e.stopPropagation();
		}
	});
	//	@menu -> save
	$(document).on('click', '#notes_save', function(){
		if ( confirm('* SAVE *\n Are you sure you want to save?\n All your notes will be overwritten.') ) {
			var s = notes.save();
			
			$.ajax({
				 url: app.notes.save
				,data: { n: s }
				,dataType: 'json'
				,type: 'POST'
				,complete: function(jqXHR, textStatus){
				}
				,success: function(data, textStatus, jqXHR){
					if ( data.succes) {	
						alert(data.msg);
					} else {
						alert(data.msg);
					}
				}
			});
		}
	});
	//	@menu -> load
	$(document).on('click', '#notes_load', function(){
		if ( confirm('* LOAD *\n Are you sure you want to load\n All your notes will be overwritten.') ) {
			//	delete all opened notes and all from menu
			$('.note, .notesList_li').remove();
			$.ajax({
				 url: app.notes.load
				,dataType: 'json'
				,type: 'GET'
				,complete: function(jqXHR, textStatus){
				}
				,success: function(data, textStatus, jqXHR){
					if ( data.status ) {	
						notes.load( JSON.parse( data.data )); 
						showAllNotes(); 
					} else {
						alert(data.msg);
					}
				}
			});
		}
	});		
	//	search
	$(document).on('keyup', '#noteFilter', function(e){
		var
			val = $(this).val()
		;
		//	clear timeout
		clearTimeout(searchTimeout);
		
		//	escape
		if ( e.keyCode === 27 ) {
			$(this).val('');
			showAllNotes();
		}
		//	enter - search
		else if ( e.keyCode === 13 ) {
			showFilteredNotes(val);
			e.preventDefault();
		}
		//	other key
		else {
			//	start searching in 50 miliseconds
			searchTimeout = setTimeout(function(){
				showFilteredNotes(val);
			}, 300);
		}
	});
	//	noteManager
	$(document).on('keydown', '#nm_tag', function(e){
		//	coma, enter, semicolon 
		if ( e.keyCode === 188 || e.keyCode === 13 || e.keyCode === 59 ) {
			//	add new tag and reset input value
			var tagTxt = $.trim($(this).val());
			if ( tagTxt !== '' ) {
				var found = false, foundObj;
				//	chek if tag is already added
				$noteManagerTags.find('.note_tags_a').each(function(){
					if ( $(this).text() == tagTxt ) {
						found = true;
						foundObj = $(this);
					}
				});
				if ( !found ) {
					//	add new tag
					var $tag = $('<a href="#" class="note_tags_a">'+tagTxt+'</a>');
					$noteManagerTags.append($tag);
				} else {
					//	blink existing one :)
					foundObj.fadeOut(100, function(){
						$(this).fadeIn(300);
					});
				}
				//	set input value as empty
				$(this).val('');
			}
			e.preventDefault();
		}
	});
	$(document).on('click', 'a.note_tags_a', function(e){
		$(this).remove();
		e.preventDefault();
	});
	
	
	/** public API */
	return {
		init: function(){
			/** 
			 * 	init function 
			 */
			$container.show();
			$sidebar.show();
			//notes.load(); 
			//showAllNotes(); 
		}
	}
	
})();
