// Auto Slug
// version 0.1 BETA
// 2005-06-30
// Copyright (c) 2005, Choan C. Gálvez
// Released under the GPL license
// http://www.gnu.org/copyleft/gpl.html
//
// --------------------------------------------------------------------
//
// This is a Greasemonkey user script.
//
// To install, you need Greasemonkey: http://greasemonkey.mozdev.org/
// Then restart Firefox and revisit this script.
// Under Tools, there will be a new menu item to "Install User Script".
// Accept the default configuration and install.
//
// To uninstall, go to Tools/Manage User Scripts,
// select "Auto Slug", and click Uninstall.
//
// --------------------------------------------------------------------
//
// ==UserScript==
// @name          Auto Slug
// @namespace     http://dizque.lacalabaza.net/greasemonkey/
// @description   Fills the slug field in WordPress advanced interface following changes in the title field
// @include       */wp-admin/*
// ==/UserScript==

(function() {
	var autoSlug = {

		title: null,

		slug: null,

		init: function() {
			if (null != (this.title = document.getElementsByName('post_title')[0])
				&& null != (this.slug = document.getElementsByName('post_name')[0]))
			{
				this.setHandler();
			}
		},

		setSlug: function() {
			var t = autoSlug.title.value;
			t = t.toLowerCase();
			//t = autoSlug.strtr('áàéèíìóòöõúùüñ \'";,:.&', 'aaeeiioooouuun--------', t); // remove accents
			// Oops, Opera doesn't like accented chars
			t = autoSlug.strtr('\u00E1\u00E0\u00E9\u00E8\u00ED\u00EC\u00F3\u00F2\u00F6\u00F5\u00FA\u00F9\u00FC\u00F1 \'";,:.&', 'aaeeiioooouuun--------', t); // remove accents, 
			t = t.replace(/[^a-z0-9\-]/g, '');
			t = t.replace(/-+/g, '-'); // remove consecutive dashes
			t = t.replace(/^-/, ''); // trim dash from start
			t = t.replace(/-$/, ''); // trim dash from the end
			autoSlug.slug.value = t;
		},

		setHandler: function() {
			if ('' == autoSlug.slug.value) {
				autoSlug.setSlug();
				autoSlug.title.addEventListener('keyup', autoSlug.setSlug, false);
				autoSlug.slug.addEventListener('keyup', autoSlug.setHandler, false);
			} else {
				autoSlug.title.removeEventListener('keyup', autoSlug.setSlug, false);
			}
		},

		strtr: function(search, replace, source) { // similar to PHP's strtr
			var r = source;

			if (0 == r.length) {
				return r;
			}

			if (search.length != replace.length) {
				// this should never happen
				alert('Search (' + search.length + ') and replace (' + replace.length + ')lengths doesn\t match, returning original string');
				return r;
			}

			for (var i = 0; i < search.length; i++) {
				// **escape the dot char**, it's a regexp
				var c = search.substr(i, 1);
				if ('.' == c) {
					c = '\\\.';
				}
				var re = new RegExp(c, 'g');
				r = r.replace(re, replace.substr(i, 1));
			}
			return r;
		}
	}

	autoSlug.init();
})();