var PicturesPage = {
	currSelection: -1,
	currDrawerSelection: -1,
		
	init: function(){
		this.picApp = contentAPI.GrabPicturesService;
		this.picApp.initService();
		
		try {
			var [, , params] = window.location.href.match(/^(.*)\?(.*)$/);
			params = jQuery.trim(decodeURIComponent(params));
			var paramArray = params.split("&");
			for (var i = 0; i < paramArray.length; i += 1) {
				var [key, value] = paramArray[i].split("=");
				if (key === 's') {
					this.currSelection = parseInt(value);
				}
			}
		} catch (e) { }
		
		var self = this;
		window.setTimeout(function() {
			try {
			self.loadPictures();
			} catch (e) {
				alert(e);
			}
		}, 0);
	},
	
	loadPictures: function(){
		var self = this;
		var picGroups = this.picApp.getGroups();
		
		var groupInDrawers = {};
		try {
			var groupDrawers = contentAPI.getCharPref('drawers');
			groupDrawers = groupDrawers.split(',');
			for (var i = 0; i < groupDrawers.length; i += 1) {
				if (groupDrawers[i]) {
					groupInDrawers[String(groupDrawers[i])] = "true";
				}
			}				
		} catch (e) { }
		
		for (var i = 0; i < picGroups.length; i += 1) {
			var group = picGroups[i];
			var groupContainer = null;

			if (String(group.id) in groupInDrawers) {
				this.miniGroup(group);
			} else {
				if (i == 0) {
					groupContainer = $('div#picgroup_1');
					$('.header-button > .save-icon-button', groupContainer).click(function(group) {
						return function() {
							self.saveGroup(group);
						}
					}(group));
				} else {
					groupContainer = this.showGroup(group);
				}
				
				this.updateGroup(group, groupContainer);
			}
		}
		
		if (this.currSelection != -1) {
			this.highlightPicture(this.currSelection, -1, true);
		}
		
		// add global actions
		this.addListeners();
		
	},
	
	updateGroup: function(group, groupContainer) {
		if (group.pictures.length == 0) {
			$('div.group-message', groupContainer).show();
			$('.header-button > .drawer-icon-button', groupContainer).hide();
		} else {
			$('div.group-message', groupContainer).hide();
			$('.header-button > .drawer-icon-button', groupContainer).show();
			for (var j = 0; j < group.pictures.length; j += 1) {
				var picture = group.pictures[j];
				this.addPicture(picture);
			}
		}
		
		// init the drag drop event;
		this.addDndListeners(group.id);
	},
		
	addListeners: function(){
		var self = this;
		
		// init the add group function
		$('#btn-addgroup').click(function(event) {
			self.addGroup();
		});
		$('#btn-movegroup').click(function(event) {
			var group = self.addGroup();
			var defaultGroup = self.picApp.getGroups()[0];
			
			var pictures = defaultGroup.pictures.slice(0);
			for (var i = 0; i < pictures.length; i += 1) {
				self.movePicture(pictures[i].id, defaultGroup.id, group.id);
			}
		});
		
		// init the detail mask
		$('#picture-detail-container').click(function(event) {
			event.stopPropagation();
		});
		$('#picture-detail-mask').click(function(event) {
			$("#picture-detail-mask").hide();
		});
		
		// init the buttons on detail mask
		$('#detail-btn-open').click(function() {
			var picObject = self.picApp.getPicObject(self.currSelection);
			if (!picObject) return;
			self.picApp.openLink(picObject.uri);
		});
		$('#detail-btn-link').click(function() {
			var picObject = self.picApp.getPicObject(self.currSelection);
			if (!picObject) return;
			self.picApp.openLink(picObject.weburi);
		});
		$('#detail-btn-delete').click(function() {
			var picObject = self.picApp.getPicObject(self.currSelection);
			if (!picObject) return;
			$("#picture-detail-mask").hide();
			self.removePicture(picObject, true);
		});
		$('#detail-btn-close').click(function() {
			$("#picture-detail-mask").hide();
		});	
		
		// init save-all button
		$('#btn-saveall').click(function() {
			try {
			self.savePictures();
			} catch (e) {
				alert(e);
			}
		});
		
		// init global key
		$(window).keydown(function(e) {
			var key = e.keyCode;
					
			if (key == 8 || key == 46) {
				if (self.currSelection === -1) return;
		
				// remove current picture
				var picObject = self.picApp.getPicObject(self.currSelection);
				if (!picObject) return;
				self.removePicture(picObject, true);
				
				e.preventDefault();
				e.stopPropagation();				
			}
		});
	},
	
	addDndListeners: function(groupId) {
		var self = this;
		
		function _canDrop(groupId, event) {
 			var params = event.dataTransfer.getData('text/plain').split("&");
 			for (var i = 0; i < params.length; i += 1) {
 				var [key, value] = params[i].split("=");
 				if (key === 'gid' && value !== groupId)
 					return true;								
 			}
			return false;
		}
		
		var groupSection = document.getElementById('picgroup_' + groupId);

		groupSection.addEventListener('dragenter', function(event) {
			if (_canDrop(groupId, event)) {
				$('#picgroup_' + groupId).addClass("picgroup-dragover");
			}
		}, false);

		groupSection.addEventListener('dragleave', function(event) {
			if (_canDrop(groupId, event)) {
				$('#picgroup_' + groupId).removeClass("picgroup-dragover");
			}
		}, false);

		groupSection.addEventListener('dragover', function(event) {
			if (_canDrop(groupId, event))
				event.preventDefault();
		}, false);

		groupSection.addEventListener('drop', function(event) {
			var params = event.dataTransfer.getData('text/plain').split("&");
			var keymap = {};
			for (var i = 0; i < params.length; i += 1) {
				var [key, value] = params[i].split("=");
				keymap[key] = value;
			}
			if ('gid' in keymap && keymap['gid'] !== groupId) {
				self.movePicture(parseInt(keymap['pid']), parseInt(keymap['gid']), parseInt(groupId));
				event.preventDefault();
			}
		}, false);
	},
	
	hideGroupTitleInput: function(group) {
		var groupSection = $('#picgroup_' + group.id);
		var headerTitle = $('.header-title', groupSection);
		headerTitle.text(group.title);
	},
	
	showGroupTitleInput: function(group) {
		var self = this;
		var groupSection = $('#picgroup_' + group.id);
		var headerTitle = $('.header-title', groupSection);
		headerTitle.html('<input type="text" class="group-title-input" value="' + group.title + '">');
		
		var input = $('input.group-title-input', headerTitle);
		input.focus(function() {
			this.select();
		});
		input[0].focus();
		
		input.blur(function() {
			var newName = this.value;
			if (newName != group.title && newName) {
				self.picApp.setGroupTitle(group.id, newName);
			}
			self.hideGroupTitleInput(group);
		});
		
		input.keydown(function(e) {
			var key = e.keyCode;
			if (key == 13) {
				var newName = this.value;
				if (newName != group.title && newName) {
					self.picApp.setGroupTitle(group.id, newName);
				}
				self.hideGroupTitleInput(group);
			}
		});
	},
	
	showGroup: function(group){
		var self = this;
		var groupSection = $('<div>').attr("id", "picgroup_" + group.id).addClass("picgroup-section");
		var template = unescape($('#picgroup-template').html());
		groupSection.html(template);
		$('.header-title', groupSection).text(group.title);
		$('.header-title', groupSection).click(function() {
			self.showGroupTitleInput(group);
		});

		$('.header-button > .drawer-icon-button', groupSection).click(function() {
			self.miniGroup(group);
			self.highlightDrawer(group.id, self.currDrawerSelection, true);
		});
		
		$('.header-button > .save-icon-button', groupSection).click(function() {
			self.saveGroup(group);
		});

		$('.group-remove-prompt > .remove-group-yes', groupSection).click(function() {
			$('.group-remove-prompt', groupSection).hide();
			self.removeGroup(group.id, true);
		});
		$('.group-remove-prompt > .remove-group-no', groupSection).click(function() {
			$('.group-remove-prompt', groupSection).hide();
			self.removeGroup(group.id, false);
		});
		$('.header-button > .delete-icon-button', groupSection).click(function() {
			if (group.pictures.length > 0) {
				$('.group-remove-prompt', groupSection).show();				
			} else {
				self.removeGroup(group.id, false);
			}
		});
		
		groupSection.insertAfter($("div#picgroup_1"));
		
		return groupSection;
	},
	
	addGroup: function() {
		var group = this.picApp.addGroup('新建分组');	
			
		var groupSection = this.showGroup(group);
		this.addDndListeners(group.id);
		$('.group-message', groupSection).show();	
		$('.header-button > .drawer-icon-button', groupSection).hide();
		this.showGroupTitleInput(group);
		
		return group;
	},
	
	removeGroup: function(id, delpic) {
		// move all the pictures to default group first
		var group = this.picApp.getGroupObject(id);
		if (!group) return;
		
		var pictures = group.pictures.slice(0);
		for (var i = 0; i < pictures.length; i += 1) {
			var picture = pictures[i];
			if (delpic) {
				this.removePicture(picture, true);
			} else {
				this.movePicture(picture.id, group.id, this.picApp.DEFAULT_GROUP_ID);	
			}
		}
		
		// then remove the group itself
		this.picApp.removeGroup(id);
		var groupSection = $("#picgroup_" + id);
		groupSection.remove();
	},
	
	miniGroup: function(group) {
		var self = this;
		var groupSection = $('#picgroup_' + group.id);
		if (groupSection.length > 0) {
			groupSection.remove();			
		}
		
		// add group drawer element
		var drawerContainer = $('#picgroup-drawer');
		var groupDrawer = $('<div>').attr('id', 'group-drawer-' + group.id).addClass('group-mini-drawer');
		this.updateDrawer(group, groupDrawer);
		drawerContainer.prepend(groupDrawer).show();
		
		groupDrawer.click(function() {
			var drawerId = parseInt($(this).attr('id').substring("group-drawer-".length));
			if (drawerId) {
				self.highlightDrawer(drawerId, self.currDrawerSelection);
			}
		});
		groupDrawer.dblclick(function() {
			var drawerId = parseInt($(this).attr('id').substring("group-drawer-".length));
			if (drawerId) {
				var group = self.picApp.getGroupObject(drawerId);
				if (group) self.maxiGroup(group);
			}
		});
		
		// add DND support, you can drag picture from group to drawer
		function _canDrop(groupId, event) {
		 	var params = event.dataTransfer.getData('text/plain').split("&");
		 	for (var i = 0; i < params.length; i += 1) {
		 		var [key, value] = params[i].split("=");
				if (key === 'gid' && value !== groupId)
 					return true;								
			}
			return false;
		}
		
		var groupId = group.id;
		var drawerDom = document.getElementById('group-drawer-' + groupId);
		drawerDom.addEventListener('dragenter', function(event) {
			if (_canDrop(groupId, event)) {
				$('#group-drawer-' + groupId).addClass("drawer-dragover");
			}
		}, false);
		
		drawerDom.addEventListener('dragleave', function(event) {
			if (_canDrop(groupId, event)) {
				$('#group-drawer-' + groupId).removeClass("drawer-dragover");
			}
		}, false);
		
		drawerDom.addEventListener('dragover', function(event) {
			if (_canDrop(groupId, event))
				event.preventDefault();
		}, false);
		
		drawerDom.addEventListener('drop', function(event) {
			var params = event.dataTransfer.getData('text/plain').split("&");
			var keymap = {};
			for (var i = 0; i < params.length; i += 1) {
				var [key, value] = params[i].split("=");
				keymap[key] = value;
			}
			if ('gid' in keymap && keymap['gid'] !== groupId) {
				self.movePicture(parseInt(keymap['pid']), parseInt(keymap['gid']), parseInt(groupId));
				self.updateDrawer(group, groupDrawer);
				self.highlightDrawer(group.id, self.currDrawerSelection, true);
				event.preventDefault();
			}
		}, false);
		
		this.saveDrawerState();
	},
	
	updateDrawer: function(group, drawer) {
		var thumbnail = "chrome://livemargins/skin/images/apps/picture.png";
		if (group.pictures.length > 0) {
			var picObject = this.picApp.getPicObject(group.pictures[0].id);
			var localThumbnail = this.picApp.getThumbnail(picObject.uri);
			if (localThumbnail) {
				thumbnail = localThumbnail;
			} else {
				this.createThumbnail(picObject.uri);
				var self = this;
				window.setTimeout(function() {
					self.updateDrawer(group, drawer);
				}, 500);
			}
		}
		
		var displayObj = {};
		displayObj.title = group.title;
		displayObj.thumbnail = thumbnail;
		displayObj.count = group.pictures.length;
		var template = unescape($('#group-drawer-template').html());
		drawer.html(TrimPath.parseTemplate(template).process({ group: displayObj }));
	},
	
	maxiGroup: function(group) {
		var self = this;
		
		// remove the drawer
		var groupDrawer = $('#group-drawer-' + group.id);
		if (groupDrawer.length > 0) {
			groupDrawer.remove();
		}
		
		// add group
		var groupContainer = this.showGroup(group);
		this.updateGroup(group, groupContainer);
		$(window).scrollTo(groupContainer);
		
		// save the state
		this.saveDrawerState();
	},
	
	saveDrawerState: function() {
		var drawerContainer = $('#picgroup-drawer');
		var groupInDrawer = [];
		drawerContainer.find('.group-mini-drawer').each(function(index) {
			var groupId = $(this).attr('id').substring('group-drawer-'.length);
			groupInDrawer.push(groupId);
		});
		contentAPI.setCharPref('drawers', groupInDrawer.join(','));		
	},
	
	openFolderPicker: function() {
		return contentAPI.openFolderPicker(window, "请选择目录");
	},
	
	saveGroup: function(group) {
		var folder = this.openFolderPicker();
		if (folder != null) {
			this.picApp.doSaveGroup(group, folder);
		}
	},
	
	savePictures: function(){
		var folder = this.openFolderPicker();
		if (folder != null) {
			this.picApp.doSavePictures(folder);
		}
	},
	
	movePicture: function(pid, oGid, nGid) {		
		if (oGid === nGid) return;
		
		
		// remove the picture from old group
		var picObject = this.picApp.getPicObject(pid);
		this.removePicture(picObject, false);
		
		// add the picture to the new group
		var newObjId = this.picApp.addPicture(picObject.uri, picObject.weburi, nGid);
		
		var groupContainer = $('div#picgroup_' + nGid);
		if (groupContainer.length > 0) {
			picObject = this.picApp.getPicObject(newObjId);
			this.addPicture(picObject);
			$('div.group-message', groupContainer).hide();
			$('.header-button > .drawer-icon-button', groupContainer).show();			
			this.highlightPicture(newObjId, this.currSelection, true);
		}
	},
	
	createThumbnail: function(uri) {
		var self = this;

		// seems we can just use a invisible canvas for drawing the pictures
		function createDone() {}
		var image = new Image();
		$(image).load(function() {
			self.picApp.createThumbnail(uri, contentAPI.getImageDataURL(image));
			createDone();
		});
		$(image).error(function() {
			createDone();
		});
		$(image).bind("abort", function() {
			createDone();
		});
		var localCache = this.picApp.getLocalCache(uri);
		if (localCache) {
			image.src = localCache;
		} else {
			image.src = uri;			
		}
	},
	
	addPicture: function(picture) {
		var self = this;
		var groupContainer = $('div#picgroup_' + picture.groupId);
		var template = unescape($("#pictures-container-template").html());
		var newPicture = {
			id: picture.id,
			uri: picture.uri,
			weburi: picture.weburi,
			groupId: picture.groupId
		};
		
		var needScale = false;
		var thumbnail = this.picApp.getThumbnail(picture.uri);
		if (thumbnail) {
			newPicture.uri = thumbnail;
		} else {
			this.createThumbnail(picture.uri);
			var localCache = this.picApp.getLocalCache(picture.uri);
			if (localCache) {
				newPicture.uri = localCache;
			} 
			needScale = true;
		}
		
		$('div.pictures-container', groupContainer).append(
			$(TrimPath.parseTemplate(template).process({"picture": newPicture}))
		);
		
		var jObject = $('#picture-' + picture.id);
		jObject.click(function(event) {
			var picId = parseInt($(this).attr('id').substring("picture-".length));
			if (picId) {
				self.highlightPicture(picId, self.currSelection);
			}
		});
		jObject.dblclick(function(event) {
			var picId = parseInt($(this).attr('id').substring("picture-".length));
			if (picId) {
				self.highlightPicture(picId, self.currSelection);
				self.showPicture(picId);
			}
		});

		var domObject = document.getElementById('picture-' + picture.id)
		domObject.addEventListener("dragstart", function(pid, gid) {
			return function(event) {
				self.highlightPicture(parseInt(pid), self.currSelection);
				event.dataTransfer.setData("text/plain", "pid=" + pid + "&gid=" + gid);
			}
		}(picture.id, picture.groupId), false);
		
		var imageObject = domObject.getElementsByTagName("img")[0];
		if (needScale) {
			$(imageObject).load(function() {
				self.scaleImage(this);
			});
		} else {
			$("#picture-" + picture.id + " > img").css('width', '100%').css('height', '100%');
		}
		$(imageObject).error(function() {
			contentAPI.log("image error");
			this.src = "chrome://marginbox/skin/images/apps/picture.png";
		});
	},
	
	removePicture: function(picObject, clearCache) {
		this.picApp.removePicture(picObject.id, clearCache);
		
		var picElement = $("#picture-" + picObject.id);
		var picContainer = picElement.parent();
		var picGroup = picContainer.parent();
		
		picElement.remove();
		if (picContainer.find('div').length == 0) {
			$('div.group-message', picGroup).show();
			$('.header-button > .drawer-icon-button', picGroup).hide();
		}
	},
	
	showPicture: function(id) {
		var picObject = this.picApp.getPicObject(id);
		var imgSrc = picObject.uri;
		
		var localCache = this.picApp.getLocalCache(picObject.uri);
		if (localCache) {
			imgSrc = localCache;
		} 
		$("#picture-detail-container img").attr("src", imgSrc);
		$("#picture-detail-mask").show();
	},
	
	highlightPicture: function(id, oldId, scroll) {
		if (oldId != -1) {
			$('#picture-' + oldId).removeClass('highlight');
		}
		if (id != -1) {
			$('#picture-' + id).addClass('highlight');
			if ((typeof scroll !== "undefined") && scroll) {
				try {
					$(window).scrollTo($('#picture-' + id));
				} catch(e) {}
			}
		}
		
		this.currSelection = id;
		if (this.currSelection !== -1) {
			this.highlightDrawer(-1, this.currDrawerSelection);			
		}
	},
	
	highlightDrawer: function(id, oldId, scroll) {
		if (oldId != -1) {
			$('#group-drawer-' + oldId).removeClass('highlight');
		}
		if (id != -1) {
			$('#group-drawer-' + id).addClass('highlight');
			if ((typeof scroll !== "undefined") && scroll) {
				$(window).scrollTo($('#group-drawer-' + id));
			}
		}
		
		this.currDrawerSelection = id;
		if (this.currDrawerSelection !== -1) {
			this.highlightPicture(-1, this.currSelection);
		}
	},
	
	scaleImage: function(img) {
		var container = img.parentNode;
		$(container).height($(container).width());
		if (img.offsetWidth > img.offsetHeight) {
			img.style.height = "100%";
		} else {
			img.style.width = "100%";
		}
	},	
};

function logObject(obj) {
	var x = [];
	for (var key in obj) {
		if (typeof obj[key] === 'function') {
			x.push(key + ": function");
		} else {
			x.push([key, obj[key]].join(' = '));			
		}
	}
	contentAPI.log(x.join('\r\n'));
}

function init() {
	PicturesPage.init();
}
