var BookmarkController = function() {
	
	var _tripid = null; 
	var _bookmark_note_ids = [];
	
	var delete_trip_callback = function(data) {
		
		$("#trip-bookmark").removeClass("favourite-marked");
		$("#trip-bookmark").addClass("favourite");		
	};
	
	var delete_trip_error = function() {
		ErrorHandler.show('Error in removing favorite trip.');
	};
	
	var save_trip_callback = function(data) {
		$("#trip-bookmark").addClass("favourite-marked");
		$("#trip-bookmark").removeClass("favourite");				
	}; 

	var save_trip_error = function(error) {
		ErrorHandler.show(error.msg);
	}; 
	
	var bookmark_trip = function(event) {
		if (_tripid != null){		
			$(event.target).attr("disabled", "true");
			if ($(event.target).hasClass("favourite-marked")) {
				
				var req = MNRequest(); 
				req.init('favourite');
				req.set_complete_fn(function(obj) {
					$(event.target).removeAttr("disabled", "true");
				});
				req.del(delete_trip_callback, delete_trip_error, {"tripid": _tripid});
				
			}else {
				
				var req = MNRequest(); 
				req.init('favourite');
				req.set_complete_fn(function(obj) {
					$(event.target).removeAttr("disabled", "true");
				});				
				req.post(save_trip_callback, save_trip_error, {"tripid":_tripid}); 
			}
		}
	}; 
	
	var save_note_callback = function(data, obj) {
		selected_bookmark = obj;
		if (selected_bookmark != null) {
			selected_bookmark.removeClass("bookmark");			
			selected_bookmark.addClass("bookmarked");
		}
	};

	var save_note_error = function(error) {
		ErrorHandler.show(error.msg);
	}; 
	
	var delete_note_callback = function(data, obj) {
		selected_bookmark = obj;
		if (selected_bookmark != null) {
			selected_bookmark.removeClass("bookmarked");
			selected_bookmark.addClass("bookmark");						
		}
	};
	
	var delete_note_error = function() {
		ErrorHandler.show('Error in removing bookmark');
	};
	
	var bookmark_note = function(event) {
		
		if (_tripid != null) {
			
			selected_bookmark = $(this);
			selected_bookmark.attr("disabled","true");
			
			var note = $(this).parents("div.note"); 
			var noteid = $("input.noteid", note).val();
			
			if ($(event.target).hasClass("bookmarked")) {
				
				var req = MNRequest(); 
				req.init('bookmark', selected_bookmark);
				req.set_complete_fn(function(obj) {
					selected_bookmark.removeAttr("disabled", "true");
				});
				
				req.del(delete_note_callback, delete_note_error, {"noteid": noteid});
				
			}else {
				
				var req = MNRequest(); 
				req.init('bookmark', selected_bookmark);
				req.set_complete_fn(function(obj) {
					selected_bookmark.removeAttr("disabled", "true");
				});				
				req.post(save_note_callback, save_note_error, {"noteid":noteid});
			}
		}
	};
	
	var set_bookmark_class = function() {
		
		$('button.bookmark').each(function(i) {
			var note = $(this).parents("div.note"); 
			var noteid = parseInt($('input.noteid', note).val());
			
			if ($.inArray(noteid, _bookmark_note_ids) != -1){
				$(this).addClass('bookmarked');
				$(this).removeClass('bookmark');
			}
		});

	};
	
	return {
		init : function(tripid, bookmark_note_ids, disabled) {
			_tripid = tripid;

			if (disabled) {
				$('#trip-bookmark').bind('click', function(){MNUser.show_login(MNUtil.trans('Add Favorite'))});
				$('button.bookmark').live('click', function(){MNUser.show_login(MNUtil.trans('to Bookmark'))});
				
			}else{
				
				$('#trip-bookmark').bind('click', bookmark_trip);
				$('button.bookmark').live('click', bookmark_note);
				$('button.bookmarked').live('click', bookmark_note)			

				_bookmark_note_ids = bookmark_note_ids;
				set_bookmark_class();
			}
		}
	}
}();
var CommentController = function() {
	

	var _dialog = null;
	var _cursor = null;
	var _editable = null;

	var add_comment = function(tab, comment) {
				
		var container = $("div.comment-list", tab);
		var entry = $('<div class="comment-entry"></div>')
		.append($(['<input type="hidden" class="commentid" value="', comment.commentid, '"/>'].join('')))
		.append($(['<img src="', comment.created_by_pic , '" class="comment-profile-pic"/>'].join('')));
		
		var info = $('<div class="comment-info">')
		.append($(['<a href="/profile/', comment.created_by, '" class="comment-creator">', comment.created_by_name, ': </a>'].join('')))
		.append($('<span class="comment-content"></span>').text(comment.content))
		.append($('<span class="comment-time"></span></div>').text(comment.created_since));

		if (comment.created_by == MNUser.get_userid() || _editable) {
			info.append($('<a class="delete"><img class="comment-del-img" src="/images/delete.png"/></a>'));
		}
		
		entry.append(info);
		entry.append($('<div style="clear:both"></div>'));
		container.append(entry);
	}; 
	

	var save_comment_callback = function(data, object) {

		var id = data[0]; 
		var tab = object;

		var comment = {}; 
		var content = $("div.comment textarea.comment-text", tab);
		comment["content"] = content.val(); 
		comment["commentid"] = id;
		comment["created_by_name"] = MNUser.get_nickname(); 	
		comment["created_by"] = MNUser.get_userid();
		comment["created_by_pic"] = MNUser.get_userpic();	

		content.val("");
		add_comment(tab, comment);		
	}; 
	
	var save_comment_error = function(error) {
		ErrorHandler.show("Error in saving comment.");
	};
	
	var save_comment = function() {
		
		var note  = $(this).parents("div.note"); 
				
		var content = $("textarea.comment-text", note).val(); 
		var noteid = $("input.noteid", note).val(); 
		
		var request = MNRequest();
		request.init('comment', note); 
		request.post(save_comment_callback, save_comment_error, { "noteid" : noteid, "content": content})
	}; 
	
	var load_comment_callback = function(data, object) {
	
		var comment_div = object;
		var container = $("div.comment-list", comment_div);

		
		var comments = data.results; 
		_cursor = data.next;
		
		if (_cursor) {
			$('a.btn-more', comment_div).show();
		}else {
			$('a.btn-more', comment_div).hide();
		}
		
		var len = comments.length;
		
		for (var i=0; i <len; i++) {
			var comment = comments[i];
			add_comment(comment_div, comment);
		}
	}; 
	
	var load_comment_error = function(error) {
		ErrorHandler.show("Error in loading comment.")
	};
	
	var load_comment = function(note_div) {
		
		if ($("div.comment", note_div).is(':hidden')) return; 	
		
		var comment = $("div.comment", note_div);
		var noteid = $("input.noteid", note_div).val(); 
		var params = {"noteid":  noteid}; 
		
		if (_cursor) {
			params["cursor"] = _cursor;
		}
		
		params["limit"] = MOVNOTE.fetchLimit.comment;
		
		var request = MNRequest();		
		request.init('comment', comment);
		request.get(load_comment_callback, load_comment_error, params)
	};
	
	var hide_tabs = function(note_div) {
		$("div.tab-panel", note_div).hide(); 
		$("div.expand", note_div).removeClass("active")		
		$("div.expand", note_div).children().removeClass("active")				
		$("div.tab", note_div).removeClass("active");
		$("div.tab div.wrapper", note_div).removeClass("active");					
	};
	
	var show_comment = function() {
		var note_div = $(this).parents("div.note");
		
		var is_open = $("div.comment", note_div).is(':hidden');
		//show panel and set active
		hide_tabs(note_div);
		if (is_open) {
			$("div.comment", note_div).show(); 
			$(this).addClass("active");
			$(this).children().addClass("active");
			$("div.tab", note_div).addClass("active");
			$("div.tab div.wrapper", note_div).addClass("active");
		}
		if ($("div.comment div.comment-list", note_div).children().length <= 0)
			load_comment(note_div);
	}
	
	var delete_comment_callback = function(data, object) {
		var comment = object; 
		comment.remove();
		_dialog.dialog('close');
	};
	
	var delete_comment_error = function(error) {
		ErrorHandler.show("Error in deleting comment " + error.msg)
	};
	
	var show_delete_comment = function() {
		
		var comment = $(this).parents('div.comment-entry'); 

		_dialog.dialog('option', 'buttons', {
				Delete: function() {
					
					var commentid = $("input.commentid", comment).val(); 
					var request = MNRequest();
					request.init('comment', comment);
					request.del(delete_comment_callback, delete_comment_error, {"commentid": commentid})
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			}
		);
		_dialog.dialog('open');
	};
	
	return {
		init : function(editable) {
			
			_editable = editable;
			$('div.comment a.save-button').live("click", save_comment);
			$('div.comment a.delete').live("click", show_delete_comment);
			
			
			$('div.expand.comment-nav').click(show_comment);		
			$('div.comment a.btn-more').live("click", load_comment)
			
			_dialog = $("#comment-del").dialog({
				resizable: false,
				height:200,				
				modal: true,
				autoOpen: false
			});
		}	
	
	};
}(); 

var LikeController = function() {
	
	var _tripid = null; 
	var _like_note_ids = [];
	
	var save_note_callback = function(data, obj) {
		selected_like = obj;
		if (selected_like != null) {
			selected_like.removeClass("like");			
			selected_like.addClass("liked");
		}
	};

	var save_note_error = function(error) {
		ErrorHandler.show(error.msg);
	}; 
	
	var delete_note_callback = function(data, obj) {
		selected_like = obj;
		if (selected_like != null) {
			selected_like.removeClass("liked");
			selected_like.addClass("like");						
		}
	};
	
	var delete_note_error = function() {
		ErrorHandler.show('Error in removing like');
	};
	
	var like_note = function(event) {
		
		if (_tripid != null) {
			
			selected_like = $(this);
			var note = $(this).parents("div.note"); 
			var noteid = $("input.noteid", note).val();
			selected_like.attr("disabled","true");
						
			if ($(event.target).hasClass("liked")) {
				
				var req = MNRequest(); 
				req.init('like', selected_like);
				req.set_complete_fn(function(obj) {
					selected_like.removeAttr("disabled", "true");
				});
				req.del(delete_note_callback, delete_note_error, {"tripid" : _tripid, "noteid" : noteid});
				
			}else {
				
				var req = MNRequest(); 
				req.init('like', selected_like);
				req.set_complete_fn(function(obj) {
					selected_like.removeAttr("disabled", "true");
				});
				
				req.post(save_note_callback, save_note_error, {"tripid":_tripid, "noteid":noteid});
			}
		}
	};
	
	var set_like_class = function() {
		
		$('button.like').each(function(i) {
			var note = $(this).parents("div.note"); 
			var noteid = parseInt($('input.noteid', note).val());
			
			if ($.inArray(noteid, _like_note_ids) != -1){
				$(this).addClass('liked');
				$(this).removeClass('like');
			}
		});

	};
	
	return {
		init : function(tripid, like_note_ids, disabled) {
			_tripid = tripid;
			if (disabled) {
				$('button.like').live('click', function(){MNUser.show_login(MNUtil.trans('like it'))});
			}else{
				$('button.like').live('click', like_note);
				$('button.liked').live('click', like_note)			

				_like_note_ids = like_note_ids;
				set_like_class();				
			}
		}
	}
}();
var LocationController = function() {
	var _editable = null; 
	
	var ZOOM = 11;
	var save_map_callback = function(e, object) {
		//var note = object;
		//$('div.location input.save-button', note).attr("disabled", true);		
	}; 
	
	var save_map_error = function(error) {
	
		ErrorHandler.show("Error in saving map " + error.msg)
	}; 
	
	var save_map = function(e) {
		var map = this;
		
		var note = $(this.getDiv()).parents("div.note");		
		var noteid = $("input.noteid", note).val();				
		
		var request = MNRequest(); 
		request.init('note', note); 
		var n = {}; 
		var center = map.getCenter();
		n["center"] = center.lat() + "," + center.lng();
		n["zoom"] = map.getZoom(); 
		
		var notes_json = JSON2.stringify(n); 
		request.post(save_map_callback, save_map_error, {"noteid": noteid, "feed": notes_json});
	}; 
	
	var view_changed = function() {
		//var map = $(this.getDiv());
		//var tab = map.parent();
		
		//var save_btn = $("input.save-button", tab); 
		//save_btn.removeAttr("disabled");
		
		//save_btn.bind("click", this, save_map);
		//save_map();
	}; 
	
	var hide_tabs = function(note_div) {
		$("div.tab-panel", note_div).hide(); 
		$("div.expand", note_div).removeClass("active")		
		$("div.expand", note_div).children().removeClass("active")				
		$("div.tab", note_div).removeClass("active");
		$("div.tab div.wrapper", note_div).removeClass("active");					
	};
		
	var load_map = function(note_div) {
				
		var map_div = $('div.map', note_div);
			
		if (map_div.children().length == 0) {
			var ll = $('input.latlng', note_div).val();			
			var latlng = MNUtil.parse_latlng(ll);
			if (latlng != null) {
		
				var ll_center = $('input.center', note_div).val();
				var center = latlng;
			
				if (ll_center != '') {					
					center = MNUtil.parse_latlng(ll_center);
				}
			
				var s_zoom = $('input.zoom', note_div).val();
				var zoom = ZOOM; 
				if (s_zoom != '') {
					zoom = parseInt(s_zoom);
				}
			
			    var myOptions = {
			      	zoom: zoom,
			      	center: center,
			    	mapTypeId: google.maps.MapTypeId.ROADMAP,
					scrollwheel: false			
			    };
			    var map = new google.maps.Map(map_div.get(0), myOptions);		
				
				if (_editable) {
					google.maps.event.addListener(map, 'zoom_changed', save_map);
					google.maps.event.addListener(map, 'dragend', save_map);
				}
						
				var marker = new google.maps.Marker({
				    position: latlng, 
				    map: map
				});	
				
				GeoUtil.suggest(latlng, MNUser.get_locale(), function(places) {

					var rectags = $("div.recommend", note_div); 
					rectags.empty();
					
					var len = places.length; 
					for (var i=0; i<len; i++) {
						var place = places[i];
						rectags.append($('<a class="suggest-word">' + place + '</a>'));
						if (i != len - 1)
							rectags.append($('<span class="separator">,</span>'));											
					}
				})
			}
		}		
	}; 
	
	
	var show_location = function() {
		var note_div = $(this).parents("div.note");
		//show panel and set active
		var is_open = $("div.location", note_div).is(':hidden');
		hide_tabs(note_div);
		if (is_open) {
			$("div.location", note_div).show(); 
			$(this).addClass("active");
			$(this).children().addClass("active");
			$("div.tab", note_div).addClass("active");
			$("div.tab div.wrapper", note_div).addClass("active");
		}
		load_map(note_div);
	};
	
	var search_nearby = function() {
		var note_div = $(this).parents("div.note"); 
		var latlng = $("input.latlng", note_div).val();
		var zoom = $("input.zoom", note_div).val()
		
		if (!zoom) zomm = ZOOM;
		
		$("#search-latlng").val(latlng);
		$("#search-zoom").val(zoom);
		$("#search-form").submit();
	};
	
	return {
		init : function(editable) {
			_editable = editable; 
			
			//$('div.toggle-location').click(load_map);
			$('div.expand.location-nav').click(show_location);			
			$('div.location a.search-nearby').live('click', search_nearby);
			//var save_buttons = $('div.location input.save-button');
			//save_buttons.attr("disabled", true);
		}
	};
}();
var NoteController = function () {
	
	var _del_dialog = null;
	var _trip_id = null; 

	var show_input = function(note, field) {
		
		var note_display = note.find('.note-' + field).hide(); 
		var note_edit = note.find('div.note-' + field + '-edit').show(); 
		
		if (field == 'description') {
			var note_description_pre = note.find('.note-' + field + '-content');
			note_edit.find('.note-' + field + '-text').val($.trim(note_description_pre.text()));			
		}else {
			note_edit.find('.note-' + field + '-text').val($.trim(note_display.text()));
		}
	};
	
	var save_input = function(save_btn, field, success) {
		
		var note = save_btn.parents("div.note");
		var noteid = note.find("input.noteid").val(); 
		
		save_btn.hide().parent().find('img.loading').show(); 
		
		var dic = {}; 
		dic[field] = $.trim(note.find('.note-' + field + '-text').val()); 
		var notes_json = JSON2.stringify(dic);
						
		var request = MNRequest(); 
		request.init('note');
		
		request.post(function(data) {
			
			var note_id = data[0]; 
			save_btn.show().parent().find('img.loading').hide(); 
			
			if (note) {
				if (field == 'description') {
					note.find('.note-' + field).show();
					note.find('.note-' + field + '-content').text(note.find('.note-' + field + '-text').val()); 
				}else {
					note.find('.note-' + field).text(note.find('.note-' + field + '-text').val()).show(); 
				}
				note.find('div.note-' + field + '-edit').hide(); 
			}			
			
			if (success) {success()};
			
		}, function(error){
			save_btn.show().parent().find('img.loading').hide(); 
			ErrorHandler.show("Error in saving note " + field);
		}, {noteid:noteid, feed: notes_json })		
	}; 
	
	var cancel_input = function(note, field) {

		note.find('.note-' + field).show();
		note.find('div.note-' + field + '-edit').hide();
	};

	
	var show_input_title = function() {

		var note = $(this).parents("div.note"); 
		show_input(note, 'title'); 		
	};
	
	var save_input_title = function() {
		
		var save_btn = $(this);
		save_input(save_btn, 'title');
	}; 
	
	var cancel_input_title = function() {
		var note = $(this).parents("div.note"); 		
		cancel_input(note, 'title'); 
	};
	
	var show_input_description = function() {

		var note = $(this).parents("div.note"); 
		show_input(note, 'description'); 		
	};

	var save_input_description = function() {
		
		var save_btn = $(this);
		var note = save_btn.parents('div.note'); 
		
		save_input(save_btn, 'description', 
					function() {
								
						var story = $.trim(note.find('.note-description-text').val())
						if (story != '') {
							note.find('.note-description-content').text(story);			
							note.find('.note-instruction').hide();			
						}else{
							note.find('.note-instruction').show();			
						}								
					});
	}; 

	var cancel_input_description = function() {
		var note = $(this).parents("div.note"); 		
		cancel_input(note, 'description'); 		
	};
	
	var perform_action = function() {
		var note_div = $(this).parents("div.note"); 
		var noteid = $("input.noteid", note_div).val();
		
		var selectedValue = $(this).val(); 
		if (selectedValue == "cover") {
			var request = MNRequest();
			request.init('trip', noteid);
			request.post(function() {
				$("#cover-update").dialog({
					modal: true,
					buttons: {
						Ok: function() {
							$("#cover-update").dialog( "close" );
						}
					}
				});
			},
			function() {
				ErrorHandler.show('Error in updating cover.')
			}, 
			{"feed": '{"cover_note_id":' + noteid + '}', "tripid": _trip_id});
		}else if (selectedValue == "delete") {
			$("#note-del").dialog({
				resizable: false,
				height:240,
				modal: true,
				buttons: {
					"Delete": function() {
						var request = MNRequest();
						request.init('note');
						request.del(function() {
										note_div.remove();
										$("#note-del").dialog( "close" );
									},
							 		function() {
										ErrorHandler.show('Error in deleting note.')
									},
									{'noteid' : noteid});
					},
					Cancel: function() {
						$("#note-del").dialog( "close" );
					}
				}
			});	
		}else if (selectedValue != ""){
			var feed = '{"tripid":' + selectedValue + '}';
			var request = MNRequest();
			request.init('note', note_div);
			request.post(function() {
				note_div.remove();
				ErrorHandler.show('Note has been moved successfully.')
			}
			, 
			function() {
				ErrorHandler.show('Error in moving note.')
			}, 
			{"feed": feed, "noteid": noteid});
		}
	};
			
	return {
		
		init : function(tripid){
			_trip_id = tripid; 
			
			//note action 
			$('div.note select.action-select').live("change", perform_action);			
			
			//note title edit	
			$('.note-title').live("click", show_input_title);			
			$('.note-title-edit a.save-button').live("click", save_input_title);			
			$('.note-title-edit a.cancel-button').live("click", cancel_input_title);						
			
			//note description edit	
			$('.note-description').bind("click", show_input_description);				
			$('.note-description-edit a.save-button').live("click", save_input_description);			
			$('.note-description-edit a.cancel-button').live("click", cancel_input_description);
							
			
		}		
	};
}();
var ProfileController = function() {

	var _userid = null; 
	
	var follow_user_callback = function(data) {
		$("#follow-panel").show();
		$("#btn-follow").hide();
	}; 
	
	var follow_user_error = function(error) {
		ErrorHandler.show('Error in following user');
	};
	
	var follow_user = function() {
		var req = MNRequest(); 
		req.init('following');
		req.post(follow_user_callback, follow_user_error, {userid:_userid});
	};
	
	var unfollow_user_callback = function(data) {
		$("#follow-panel").hide();
		$("#btn-follow").show();
	}; 
	
	var unfollow_user_error = function(error) {
		ErrorHandler.show('Error in unfollowing user');
	};
	
	var unfollow_user = function() {

		var req = MNRequest(); 
		req.init('following');
		req.del(unfollow_user_callback, unfollow_user_error, {userid:_userid});
		
	}; 
	
	
	var check_follow_callback = function(data) {
		
		if (data[0]) {
			$("#follow-panel").show();
			$("#btn-follow").hide();			
		}else {
			if (MNUser.get_userid() != _userid) {
				$("#follow-panel").hide();
				$("#btn-follow").show();	
				$("#setting").hide();		
			}else {
				$("#follow-panel").hide();
				$("#btn-follow").hide();							
				$("#setting").show();				
			}
		}
	}; 
	
	var check_follow_error = function(error) {
		ErrorHandler.show('Error in checking following');
	};
	
	return {
		get_userid : function() {
			return _userid;
		}, 
		
		init: function(userid) {
			_userid = userid
			//Follow ppl 
			$("#btn-follow").click(follow_user); 	
			$("#btn-unfollow").click(unfollow_user); 		
			
			if (MNUser.is_logged_in()) {
				var req = MNRequest(); 
				req.init('following');
				req.get(check_follow_callback, check_follow_error, {check_follow:'true',userid:_userid});
			}
		}
	}
}(); 


var ResponseController = function() {
	

	var _dialog = null;
	var _editable = null;
	var _tripid = null;
	var _cursor = null;
	var _prompt_mail = null;
	var _set_mail_act = null;

	var add_response = function(res, prepend) {
				
		var container = $("div#response-list");
		var entry = $('<div class="response-entry"></div>');
		
		entry.append($(['<input type="hidden" class="responseid" value="', res.responseid, '"/>'].join(''))) 
		
		var info = $('<div class="response-info"></div>'); 
		
		if (entry.created_by) {
			entry.append($(['<img src="', res.created_by_pic , '" class="response-profile-pic"/>'].join(''))); 
			
			entry.append(info); 
			info.append($(['<a href="/profile/', res.created_by, '" class="response-creator">', res.created_by_name, '</a>'].join('')));

		}else{
			if (res.created_by_pic) {
				entry.append($(['<img src="', res.created_by_pic , '" class="response-profile-pic"/>'].join(''))); 
			}
			entry.append(info); 			
			info.append('<a class="response-creator">' + res.created_by_name + '</a>');
		}
		
		info.append($('<span class="response-content"></span>').text(res.content));			
		info.append($('<br/>'));
		
		if ((res.created_by == MNUser.get_userid() || _editable) && MNUser.is_logged_in()) {
			info.append($('<a class="delete"><img src="/images/delete.png"/></a>'));
		}
		info.append($('<span class="response-time"></span>').text(res.created_since));	
		entry.append($('<div style="clear:both"></div>'));
		if (prepend) {
			container.prepend(entry);
		}else{
			container.append(entry);
		}
	}; 
	

	var save_response_callback = function(data, feed) {

		var id = data[0]; 

		var response = {}; 
		response["content"] = feed.content;
		response["responseid"] = id;
		if (MNUser.is_logged_in()) {		
			response["created_by_name"] = MNUser.get_nickname(); 	
			response["created_by"] = MNUser.get_userid();
			response["created_by_pic"] = MNUser.get_userpic();	
		}else{
			response["created_by_name"] = feed.name; 	
			response["created_by_pic"] = null;
		}

		$("#response-content").val("");
		add_response(response, true);		
		$('#btn-save-response').removeAttr("disabled");				
	}; 
	
	var save_response_error = function(error) {
		ErrorHandler.show("Error in saving response.");
		$('#btn-save-response').removeAttr("disabled");		
	};
	
	var save_response = function() {
		
		$('#btn-save-response').attr("disabled","true");
		var content = $.trim($("#response-content").val()); 
		if (content) {
			var feed = {"content": content}; 
			
			if (!MNUser.is_logged_in()) {
				feed["name"] = $.trim($("#response-name").val()); 
				feed["email"] = $.trim($("#response-email").val()); 				
			}
			
			if ($("#response-followup").attr("checked")) {
				feed["followup"] = true;
				
				if (MNUser.is_logged_in()) {
					if (_prompt_mail) {
						MailPrompt.grant_mail();
					}

					if (_set_mail_act) {
						var req = MNRequest(); 
						req.init('user'); 
						req.post(function(data) {
						}, function(error) {
							ErrorHandler.show("Error in updating user info.");						
						}, 
						{feed:'{"mail_act":true}'});				
					}			
				}
			}else{
				feed["followup"] = false;
			}
			
			var request = MNRequest();
			request.init('response', feed); 
			request.post(save_response_callback, save_response_error, { "tripid" : _tripid, "feed": JSON2.stringify(feed)})
		}
		return false;
	}; 
	
	var load_response_callback = function(data, object) {
	
		var response_div = object;
		var container = $("div#response-list", response_div);

		
		var responses = data.results; 
		_cursor = data.next;
		
		if (_cursor) {
			$('a.btn-more', response_div.parent()).show();
		}else {
			$('a.btn-more', response_div.parent()).hide();
		}
		
		var len = responses.length;
		
		for (var i=0; i <len; i++) {
			var res = responses[i];
			add_response(res);
		}
	}; 
	
	var load_response_error = function(error) {
		ErrorHandler.show("Error in loading responses." + error.msg)
	};
	
	var load_response = function() {
		
		var response = $("div#response-list");

		var params = {"tripid":  _tripid}; 
		
		if (_cursor) {
			params["cursor"] = _cursor;
		}
		
		params["limit"] = MOVNOTE.fetchLimit.response;
		
		var request = MNRequest();		
		request.init('response', response);
		request.get(load_response_callback, load_response_error, params)
	};
			
	var show_delete_response = function() {
		
		var response = $(this).parent().parent(); 

		_dialog.dialog('option', 'buttons', {
				Delete: function() {
					
					var responseid = $("input.responseid", response).val(); 
					var request = MNRequest();
					request.init('response', response);
					request.del(function() {
						response.remove();
						_dialog.dialog('close');						
					}, function() {
						ErrorHandler.show("Error in deleting response")						
					}, {"responseid": responseid})
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			}
		);
		_dialog.dialog('open');
	};
	
	return {
		init : function(editable, tripid, prompt_mail, set_mail_act, disabled) {
			
			_set_mail_act = set_mail_act;
			_prompt_mail = prompt_mail;
			_tripid = tripid;
			_editable = editable;
			
			if (disabled) {
				$('#btn-save-response').live('click', function(){
														MNUser.show_login(MNUtil.trans('Leave a reply'));
														return false;
												});
												
			}else {
				$('#btn-save-response').live ("click", function(){
				
					$("#response-form").validate({
						submitHandler: function() {
							save_response();
						}
					})
								
				});
				$('div.response-entry a.delete').live("click", show_delete_response);
				$('div#panel-response a.btn-more').click(load_response);
									
				_dialog = $("#response-del").dialog({
					resizable: false,
					height:200,				
					modal: true,
					autoOpen: false
				});
			}
			load_response();
		}	
	
	};
}(); 


	
var RouteController = function() {
	var _editable = null; 
		
	var get_routes = function(route_list) {
		
		var routes = []; 
		$("div.route-transport", route_list).each(function () {
			var route_transport = $(this);

			var dest = $.trim($("p.destination", route_transport).text()); 	
			var tran = $.trim($("span.transport", route_transport).text()); 	
			var hour = $.trim($("span.hour", route_transport).text());
			var min = $.trim($("span.minute", route_transport).text());
			var exp = $.trim($("span.expense", route_transport).text()); 	

			var route = {}; 
			if (dest) {
				route["dest"] = dest; 
			}

			if (tran) {
				route["tran"] = tran; 
			}
			
			var time = 0; 
			if (hour) {
				 time = parseInt(hour) * 60; 
			}

			if (min) {
				time += parseInt(min);
			}
			
			if(time > 0) {
				route["time"] = time;
			}

			if (exp) {
				route["exp"] = parseInt(exp)
			}
			routes.push(route);
		});
		return routes;
	}; 
	
	var add_route = function() {
		
		var transport_div = $(this).parents("div.transport-edit"); 
		var note = $(this).parents("div.note"); 
		
		var input_dest = $("input.destination", transport_div);
		var dest = $.trim(input_dest.val()); 	
		
		var input_tran = $("input.transport-text", transport_div);
		var tran = $.trim(input_tran.val()); 	
		
		var input_hour = $("input.hour", transport_div);
		var hour = $.trim(input_hour.val());
		
		var input_min = $("input.minute", transport_div);
		var min = $.trim(input_min.val());
		
		var input_exp = $("input.expense", transport_div);
		var exp = $.trim(input_exp.val()); 	
		
		if (!(dest || tran || hour || min || exp))
			return;
		
		var route = {}; 
		if (dest) {
			route["dest"] = dest; 
		}
		
		if (tran) {
			route["tran"] = tran; 
		}
		
		var time = 0; 
		if (hour) {
			time = parseInt(hour) * 60; 
		}

		if (min) {
			time += parseInt(min); 
		}

		if (time > 0) {
			route["time"] = time;
		}
		
		if (exp) {
			route["exp"] = parseInt(exp)
		}
		
		var list = $("div.route-list", transport_div.parents("div.route"));
		var routes = get_routes(list); 
		routes.push(route); 
		
		
		var btn = $(this);
		$("img.loading", btn.parent()).show(); 
		$("a.add-route", btn.parent()).hide();
		
		//store the routes as json string in backend
		var update_note = {"route_json" : JSON2.stringify(routes)};
		
		var noteid = $("input.noteid", note).val(); 
		var feed = JSON2.stringify(update_note); 
		
		var request = MNRequest()
		request.init('note', {"route":route, "hour":hour, "min":min, "note":note, "div":transport_div}); 
		request.post(function(data){
			/*
				var route = object.route;
				var note = object.note;
				var hour = object.hour;
				var min = object.min;
				var transport_div = object.div;
			*/
			
			input_dest.val(''); 	
			input_tran.val(''); 	
			input_hour.val('');
			input_min.val('');
			input_exp.val(''); 	

			//update the heading
			var item = $('<div class="route-transport"></div'); 

			if (route.dest) {
				$('<p class="destination"></p>').text(route.dest).appendTo(item);
			}

			var detail = $('<div class="detail">').appendTo(item);
			if (route.tran) {
				$('<span class="caption">' + MNUtil.trans("Transport") + '</span>').appendTo(detail);
				$('<span class="transport"></span>').text(route.tran + ' ').appendTo(detail);
			}

			if (hour) {
				$('<span class="hour"></span>').text(hour).appendTo(detail);
				$('<span class="caption">' + MNUtil.trans("hours") + '</span>').appendTo(detail);			
			}

			if (min) {
				$('<span class="minute"></span>').text(min).appendTo(detail);
				$('<span class="caption">' + MNUtil.trans("mins") + '</span>').appendTo(detail);
			}

			if (route.exp) {
				$('<span class="caption">$ </span>').appendTo(detail);
				$('<span class="expense"></span>').text(route.exp).appendTo(detail);
			}

			$('<a class="delete"></a><div style="clear:both;"></div>').appendTo(item);

			item.appendTo(list);
			$("img.loading", btn.parent()).hide(); 
			$("a.add-route", btn.parent()).show();			
		}, function(error) {
			ErrorHandler.show("Error in saving the route " + error.msg);
			$("img.loading", btn.parent()).hide(); 
			$("a.add-route", btn.parent()).show();						
		}, {'noteid':noteid, 'feed': feed})		
	}; 
	
	var save_route_dest_callback = function(data, obj) {
		var editable = obj;
		editable.finish_edit();
	};
	
	var save_route_dest_error = function(error) {
		ErrorHandler.show("Error in saving the route");		
	};
	
	var save_route_dest = function() {
		var editable = $(this);
		var list = $("div.route-list", editable.parents("div.route"));
		var routes = get_routes(list); 
		
		routes.push({"dest":$.trim(editable.prev().val())});
		var note = $(this).parents("div.note"); 
		var noteid = $("input.noteid", note).val(); 
		
		var update_note = {"route_json" : JSON2.stringify(routes)};
		var feed = JSON2.stringify(update_note); 
			
		var request = MNRequest()
		request.init('note', editable); 
		request.post(save_route_dest_callback, save_route_dest_error, {'noteid':noteid, 'feed': feed})
	};
	
	var delete_route_callback = function(data, obj) {
		var list = obj.list;
		var del_index = obj.del_index; 
		
		var item = $("div.route-transport", list).eq(del_index); 
		if (item)
			item.remove();
	};
	
	var delete_route_error = function(error) {
		ErrorHandler.show("Error in saving the route");		
	};
	
	var delete_route  = function() {
		
		var del = $(this);
		var list = $("div.route-list", del.parents("div.route"));
				
		var transport = del.parent(); 
		var del_index = $("div.route-transport", list).index(transport);
		
		var routes = get_routes(list); 
		routes.splice(del_index, 1);
		
		var note = $(this).parents("div.note"); 
		var noteid = $("input.noteid", note).val(); 

		var update_note = {"route_json" : JSON2.stringify(routes)};
		var feed = JSON2.stringify(update_note); 

		var request = MNRequest()
		request.init('note', {"del_index":del_index, 'list':list}); 
		request.post(delete_route_callback, delete_route_error, {'noteid':noteid, 'feed': feed})
	}
	
	return {
		init : function(editable) {
			
			_editable = editable;
			$('div.route a.add-route').live("click", add_route);
			
			$('div.route div.route-list a.delete').live("click", delete_route);
			
			if (_editable) {
				$("div.route div.route-destination").each(function () {
					$(this).editable({save:save_route_dest});
				});
				
				$("div.route div.transport-edit").each(function () {
					var transport = $(this);
					$("input.expense", transport).mask("999999", {placeholder:' '});
					$("input.hour", transport).mask("99", {placeholder:' '});					
					$("input.minute", transport).mask("99", {placeholder:' '});										
				});
			}
		}
	};
}();
var CATEGORY_NAMES = ['Food','Shop','Rest','Scene'];

var WordController = function() {
	
	var _container_class = null; 
	var _entity = null;
		
	var update_words = function(note) {
		
		var list = $(_container_class + " div.tag-list", note);		
		var text = $("div.toggle-word span.word-text", note); 
		var title = $("div.toggle-word span.word-title", note); 
		
		if ($("div.word a.text", list).size() > 0) {
			title.hide();
			
			var str = "";
			var count = 0;
			$("div.word a.text", list).each(function () {
				if (count == 0) str += $.trim($(this).text()); 
				else str += ", " + $.trim($(this).text()); 
				count += 1;
			});
			text.text(str);
			text.show();
		}else{
			text.text('');
			text.hide(); 
			title.show()
		}
	}
	
	var save_word_callback = function(data, object) {

		var note = object.note;
		var words = object.words;	
		
		var list = $(_container_class + " div.tag-list", note);
		var words_text = $(_container_class + " div.tag-edit input.tag-words", note);

		var len = words.length;
		
		for (var i=0; i<len; i++) {
			var val = $.trim(words[i]); 
			var word_div = $('<div class="tag-word"></div>'); 
			word_div.append($('<a class="text"></a>').text(val));
			word_div.append($('<a class="delete"></a>'))
			list.append(word_div);
		}
		
		//update the count 		
		var words_count = $("div.word", list).size()
		update_words(note);
		
		words_text.val('');
	}; 
	
	var save_word_error = function(error) {
		ErrorHandler.show("Error in saving the words information");
	};
	
	//New Word is unqiue
	//Word is not empty
	//New Word and existing should be unique
	var save_word = function(e) {
		
		var edit = $(this).parent();
		var note  = $(this).parents("div.note"); 
		
		var words = $("input.tag-words", edit).val(); 
		var noteid = $("input.noteid", note).val(); 
		
		var existing_words = [];
		var list = $(_container_class + " div.list", note);		
		$("div.word a.text", list).each(function () {
			existing_words.push($.trim($(this).text().toLowerCase())); 
		});
		
		var words_text = $(_container_class + " div.tag-edit input.tag-words", note);

		var words = words_text.val().split(','); 
		var len = words.length;
		var new_words = [];
		for (var i=0; i<len; i++) {
			var val = $.trim(words[i].toLowerCase()); 
			if (val != '') {
				//Check existing words make sure no duplicated
				//Check new words make sure no duplicated 
				if ($.inArray(val, existing_words) == -1 && 
					$.inArray(val, new_words) == -1) {
					new_words.push(val);
				}
			}
		}
		
		if (new_words.length > 0) {
			
			var n = {}
			n["words"] = new_words; 	
			var feed = JSON2.stringify(n); 
		
			var request = MNRequest()
			request.init(_entity, {note: note, words: new_words}); 
			request.post(save_word_callback, save_word_error, {"noteid":noteid, "feed":feed})
		}
	};
	
	var assign_word = function(e) {
		var div  = $(this).parents(_container_class);
		var input = $("div.tag-edit input.tag-words", div); 

		//check if the word exist
		var href = $(this);
		var val = href.text();
		var words = input.val().split(','); 
		
		for (var i=0; i<words.length; i++) {
			words[i] = $.trim(words[i]);
		}
		
		if ($.inArray(val, words) == -1) {
			
			if ($.trim(input.val()) != "")
				val = "," + val
			input.val(input.val() + val);
		}
	}; 
	
	var delete_word_callback = function(data, object) {

		var word = object.word;
		var note = object.note;	
		var list = word.parent();		
		word.remove()
		update_words(note);
	}; 
	
	var delete_word_error = function(error) {
		ErrorHandler.show("Error in deleting the word");
	};
	
	var delete_word = function(e) {
		
		var note  = $(this).parents("div.note"); 
		var word_div = $(this).parent();
		
		var word = $("a.text", word_div).text(); 
		var noteid = $("input.noteid", note).val(); 
		
		var n = {}
		n["words"] = [word]; 	
		var feed = JSON2.stringify(n);
	
		var request = MNRequest()
		request.init(_entity, {note: note, word: word_div}); 
		request.del(delete_word_callback, delete_word_error, {"noteid" : noteid, "feed":feed})
	}; 
	
	
	return {
		init : function(container_class, entity) {
			
			_container_class = container_class; 
			_entity = entity; 
			
			$(_container_class + ' div.tag-edit input.save-button').live("click", save_word);
			$(_container_class + ' div.recommend a.suggest-word').live("click", assign_word);
			$(_container_class + ' div.tag-list div.tag-word a.delete').live("click", delete_word);
		}
	}
};


var CategoryController = function() {
	
	var update_category_callback = function(data, object) {
		var note = object;
		var category = $("input.category-rb:checked", note).val();
		
		$("div.note-remark div", note).hide();				
		if (category == '1') {
			$("div.food-panel", note).show();
		}else if (category == '2') {
			$("div.rest-panel", note).show();			
		}else if (category == '3') {
			$("div.shop-panel", note).show();
		}else if (category == '4') {
			$("div.scene-panel", note).show();							
		}
	};
	
	var update_category_error = function(error) {
		ErrorHandler.show("Error in updating the category");
	};
	
	var update_category = function(e) {
		
		var note  = $(this).parents("div.note"); 
		var noteid = $("input.noteid", note).val(); 
		var category = $("input.category-rb:checked", note).val();

		var notes_json = '{"category":' + category + '}'

		var request = MNRequest()
		request.init('note', note); 
		request.post(update_category_callback, update_category_error, {'noteid': noteid,'feed': notes_json})
	};
	
	return {
		init : function() {			
			$("div.tag input.category-rb").live('click', update_category);
		}
	}
}(); 

