var imageLoadedCallback = function() {};

function bindIfExists(elem, eventName, func) {
	if (elem == null) return;
	Event.observe(elem, eventName, func);	
}

function focusIfExists(elem) {
	if (!elem) { return; }
	elem.focus();
}

function getInputValue(id) {
	input = $(id);
	if (input) return input.value;
}

var ClientsList = {
	
	initialize: function() {
		scriptAfterLoad = this.update.bind(this);
		scriptAfterFinished = function() { window.location.reload(true); };
		return this;
	},
	
	beforeUpdate: function() {
		ClientDetail.reset();
	},
	
	afterUpdate: function() {
		bindIfExists($("clientsListNew"), 'click', this.onNew.bindAsEventListener(this));
		bindIfExists($("clientsListList"), 'change', this.onEdit.bindAsEventListener(this));
		bindIfExists($("clientsListDelete"), 'click', this.onDelete.bindAsEventListener(this));
		ClientDetail.reset();
	},
	
	update: function() {
		this.beforeUpdate();
		new Ajax.Updater($("clientsList"), "admin/moduleClientsList.php", { onComplete: this.afterUpdate.bind(this) });
	},
	
	updateClientLink: function(id, name) {
		if (!id) return;
		var clients = this.getClients();
		var found = false; 
		for (key in clients) {
			if (clients[key].value == id) {
				clients[key] = new Option(name, id, false, true);
				found = true;
			}
		}
		if (!found) {
			clients[clients.length] = new Option(name, id, false, true);
		}
	},
	
	getSelectedId: function() {
		var i = this.getSelectedIndex();
		if (i >= 0) {
			return this.getClients()[i].value;
		} else {
			return;
		}
	},
	
	getClients: function() {
		return $("clientsListList").options;
	},
	
	getSelectedIndex: function() {
		return $("clientsListList").selectedIndex;
	},
	
	onNew: function() {
		ClientDetail.update();
	},
	
	onEdit: function() {
		var id = this.getSelectedId();
		ClientDetail.update(id);		
	},
	
	onDelete: function() {
		ClientDetail.deleteClient(this.getSelectedId());
		this.getClients()[this.getSelectedIndex()] = null;
	}
	
}.initialize();


var ClientDetail = {
	
	initialize: function() {
		return this;
	},
	
	beforeUpdate: function() {
	},
	
	getId: function() {
		return getInputValue("clientDetailId");
	},
	
	afterUpdate: function() {
		bindIfExists($("clientDetailApply"), 'click', this.onApply.bindAsEventListener(this));
		ClientProjects.update(this.getId());
		ClientsList.updateClientLink(this.getId(), $("clientDetailName").value);
		focusIfExists($("clientDetailName"));
	},
	
	update: function(id, params) {
		this.beforeUpdate();
		if (!params) params = {};
		new Ajax.Updater($("clientDetail"), "admin/moduleClientDetail.php?id=" + id, { onComplete: this.afterUpdate.bind(this), parameters: params });		
	},
	
	reset: function() {
		$("clientDetail").innerHTML = "";
		ClientProjects.reset();
	},
	
	deleteClient: function(clientId) {
		var p = { action: "delete", id: clientId, name: "" };
		this.update(clientId, p);		
	},
	
	onApply: function() {
		var p = { action: "save", id: -1, name: "" };
		p.id = this.getId();
		p.name = $("clientDetailName").value;
		this.update(this.getId(), p);
	},
	
}.initialize();


var ClientProjects = {
	
	clientId: -1,
	
	initialize: function() {
		return this;
	},
	
	beforeUpdate: function() {
	},
	
	getClientId: function() {
		elem = $("clientProjectsClientId");
		if (elem) {
			return elem.value;
		} else {
			return;
		}
	},
	
	afterUpdate: function() {
		bindIfExists($("clientProjectsNew"), 'click', this.onNew.bindAsEventListener(this));
		bindIfExists($("clientProjectsList"), 'change', this.onEdit.bindAsEventListener(this));
		bindIfExists($("clientProjectsDelete"), 'click', this.onDelete.bindAsEventListener(this));
		bindIfExists($("clientProjectsUp"), 'click', this.onUp.bindAsEventListener(this));
		bindIfExists($("clientProjectsDown"), 'click', this.onDown.bindAsEventListener(this));
		bindIfExists($("clientProjectsApplyOrdering"), 'click', this.onApplyOrdering.bindAsEventListener(this));
		ProjectDetail.reset();
	},
	
	update: function(id) {
		this.clientId = id;
		this.beforeUpdate();
		if (this.clientId) {
			new Ajax.Updater($("clientProjects"), "admin/moduleClientProjects.php?clientId=" + id, { onComplete: this.afterUpdate.bind(this) });
		} else {
			this.reset();
		}
	},
	
	reset: function() {
		this.clientId = -1;
		$("clientProjects").innerHTML = "";
		ProjectDetail.reset();
	},
	
	getProjects: function() {
		return $("clientProjectsList").options;
	},
	
	getSelectedIndex: function() {
		return $("clientProjectsList").selectedIndex;
	},
	
	updateProjectLink: function(id, name) {
		if (!id) return;
		var projects = this.getProjects();
		var found = false; 
		for (key in projects) {
			if (projects[key].value == id) {
				projects[key] = new Option(name, id, false, true);
				found = true;
			}
		}
		if (!found) {
			projects[projects.length] = new Option(name, id, false, true);
		}		
	},
	
	onNew: function() {
		ProjectDetail.update();
	},
	
	onEdit: function() {
		var projects = $("clientProjectsList");
		var id = projects.options[projects.selectedIndex].value;
		ProjectDetail.update(id);
	},
	
	onDelete: function() {
		ProjectDetail.deleteProject(this.getProjects()[this.getSelectedIndex()].value);
		this.getProjects()[this.getSelectedIndex()] = null;
	},
	
	onUp: function() {
		var i = this.getSelectedIndex();
		var projects = this.getProjects();
		if (i < 1) return;
		//Swap projects
		var dummy =  projects[i].cloneNode(true);
		projects[i] = projects[i - 1].cloneNode(true);
		dummy.selected = true;
		projects[i - 1] = dummy;		
	},
	
	onDown: function() {
		var i = this.getSelectedIndex();
		var projects = this.getProjects();
		if (i >= projects.lenght - 1) return;
		//Swap projects
		var dummy =  projects[i].cloneNode(true);
		projects[i] = projects[i + 1].cloneNode(true);
		dummy.selected = true;
		projects[i + 1] = dummy;		
	},
	
	onApplyOrdering: function() {
		var projects = this.getProjects();
		var p = { clientId: -1, ordering: '' };
		p.clientId = ClientDetail.getId();
		var ordering = new Array();
		for (var i = 0; i < projects.length; i++) {
			ordering[i] = projects[i].value;
		}
		p.ordering = ordering.join(",");
		new Ajax.Request('actions/updateProjectsOrdering.php', { parameters: p });		
	}
	
}.initialize();

var ProjectDetail = {
	
	wymeditor: null,
	
	initialize: function() {
		return this;
	},
	
	beforeUpdate: function() {
	},

	setWymInstance: function(instance) {
		this.wymeditor = instance;
	},
	
	afterUpdate: function() {
		bindIfExists($("projectDetailApply"), 'click', this.onApply.bindAsEventListener(this));
		var l = new WymCreationListener();
		var setWymFunc = this.setWymInstance.bind(this);
		l.onCreation = function(inst) { setWymFunc(inst); };
		applyWYMEditorToTextArea($("projectDetailDescription"), l);
		ClientProjects.updateProjectLink(this.getId(), $("projectDetailTitle").value);
		ProjectImages.update(this.getId());
	},
	
	update: function(id, params) {
		this.beforeUpdate();
		if (!params) params = {};
		new Ajax.Updater($("projectDetail"), "admin/moduleProjectDetail.php?id=" + id, { onComplete: this.afterUpdate.bind(this), parameters: params });
	},
	
	reset: function() {
		$("projectDetail").innerHTML = "";
		ProjectImages.reset();
	},
	
	deleteProject: function(projectId) {
		var p = { action: "delete", id: projectId, name: "" };
		this.update(projectId, p);		
	},
	
	getId: function() {
		return getInputValue("projectDetailId");
	},
	
	getClientId: function() {
		return ClientProjects.getClientId();
	},
	
	onApply: function() {
		if (this.wymeditor) this.wymeditor.update(); 
		var p = { action: "save", id: -1, title: "", description: "", clientid: -1, url: "", ordering: 0 };
		p.id = this.getId();
		p.title = getInputValue("projectDetailTitle");
		p.description = getInputValue("projectDetailDescription");
		p.clientid = this.getClientId();
		p.url = getInputValue("projectDetailUrl");
		p.ordering = getInputValue("projectDetailOrdering");
		this.update(this.getId(), p);
	}
	
}.initialize();

var ProjectImages = {
	
	projectId: -1,
	
	initialize: function() {
		return this;
	},
	
	beforeUpdate: function() {
	},
	
	afterUpdate: function() {
		bindIfExists($("projectImagesNew"), 'click', this.onNew.bindAsEventListener(this));
		bindIfExists($("projectImagesList"), 'change', this.onEdit.bindAsEventListener(this));
		bindIfExists($("projectImagesDelete"), 'click', this.onDelete.bindAsEventListener(this)); 
		bindIfExists($("projectImagesUp"), 'click', this.onUp.bindAsEventListener(this)); 
		bindIfExists($("projectImagesDown"), 'click', this.onDown.bindAsEventListener(this)); 
		bindIfExists($("projectImagesApplyOrdering"), 'click', this.onApplyOrdering.bindAsEventListener(this)); 
		ProjectImageDetail.reset();
	},
	
	update: function(id) {
		this.projectId = id;
		this.beforeUpdate();
		if (this.projectId) {
			new Ajax.Updater($("projectImages"), "admin/moduleProjectImages.php?projectId=" + id, { onComplete: this.afterUpdate.bind(this) });
		} else {
			this.reset();
		}
	},
	
	reset: function() {
		this.projectId = -1;
		$("projectImages").innerHTML = "";
		ProjectImageDetail.reset();
	},
	
	getImages: function() {
		return $("projectImagesList").options;
	},
	
	getSelectedIndex: function() {
		return $("projectImagesList").selectedIndex;
	},
	
	updateImageLink: function(id, img) {
		if (!id) return;
		var images = this.getImages();
		var found = false; 
		for (key in images) {
			if (images[key].value == id) {
				images[key].style.backgroundImage = "url(" + img + ")";
				found = true;
			}
		}
		if (!found) {
			var newOption = new Option("", id, false, true);
			newOption.style.backgroundImage = "url(" + img + ")";
			images[images.length] = newOption;
		}		
	},
	
	onNew: function() {
		ProjectImageDetail.update();
	},
	
	onEdit: function() {
		var projectImages = $("projectImagesList");
		var id = projectImages.options[projectImages.selectedIndex].value;
		ProjectImageDetail.update(id);
	},
	
	onDelete: function() {
		ProjectImageDetail.deleteProjectImage(this.getImages()[this.getSelectedIndex()].value);
		this.getImages()[this.getSelectedIndex()] = null;
	},
	
	onUp: function() {
		var i = this.getSelectedIndex();
		var images = this.getImages();
		if (i < 1) return;
		//Swap images
		var dummy =  images[i].cloneNode(true);
		images[i] = images[i - 1].cloneNode(true);
		dummy.selected = true;
		images[i - 1] = dummy;
	},
	
	onDown: function() {
		var i = this.getSelectedIndex();
		var images = this.getImages();
		if (i >= images.lenght - 1) return;
		//Swap images
		var dummy =  images[i].cloneNode(true);
		images[i] = images[i + 1].cloneNode(true);
		dummy.selected = true;
		images[i + 1] = dummy;
	},
	
	onApplyOrdering: function() {
		var images = this.getImages();
		var p = { projectId: -1, ordering: '' };
		p.projectId = ProjectDetail.getId();
		var ordering = new Array();
		for (var i = 0; i < images.length; i++) {
			ordering[i] = images[i].value;
		}
		p.ordering = ordering.join(",");
		new Ajax.Request('actions/updateImagesOrdering.php', { parameters: p });
	}
	
}.initialize();


var ProjectImageDetail = {
	
	initialize: function() {
		return this;
	},
	
	beforeUpdate: function() {
	},
	
	afterUpdate: function() {
		bindIfExists($("imageDetailApply"), 'click', this.onApply.bindAsEventListener(this));
		ProjectImages.updateImageLink(this.getId(), "data/projectimages/2/" + this.getFilename());
		//focusIfExists("projectDetailDescription");
		focusIfExists($("imageDetailUpload"));
		//focusIfExists($("imageDetailUpload").contentWindow.document.getElementById("imageUploaderFile"));
	},
	
	update: function(id, params) {
		if (!params) params = {};
		this.beforeUpdate();
		url = "admin/moduleProjectImageDetail.php";
		if (id) { 
			url += "?id=" + id; 
		} else if (this.getProjectId()) { 
			url += "?projectid=" + this.getProjectId(); 
		}
		new Ajax.Updater($("projectImageDetail"), url, { onComplete: this.afterUpdate.bind(this), parameters: params });			
	},
	
	reset: function() {
		$("projectImageDetail").innerHTML = "";
	},
	
	getId: function() {
		var id = $("imageDetailId").value;
		if (!id) {
			var iframe = $("imageDetailUpload");
			if (iframe) {
				var idElem = iframe.contentWindow.document.getElementById("imageUploaderId");
				if (idElem) {
					id = idElem.value;
				}
			}
		}
		return id;
	},
	
	getProjectId: function() {
		return ProjectDetail.getId();
	},
	
	getFilename: function() {
		return $("imageDetailFilename").value;
	},
	
	onApply: function() {
		var iframe = $("imageDetailUpload");
		var uploaderForm = iframe.contentWindow.document.getElementById("imageUploader");
		uploaderForm.submit();
		imageLoadedCallback = this.update.bind(this);
	},
	
	deleteProjectImage: function(imgId) {
		var p = { action: "delete", id: imgId, name: "" };
		this.update(imgId, p);		
	}
	
}.initialize();
