window.jQuery(function ($) {
	$(window).focus();	
	function now() {
		return new Date().getTime();
	}
	var delicious_logged = null, t0 = 0,
		converters = {
		'twitter_interval': {
			get: function (v) {return v / 60 / 1000;},
			set: function (v, cb) {
				cb(v * 60 * 1000);
			}
		},
		'twitter_user': {
			set: function (v, cb) {
				var listitem = $('#twitter_user').parent().addClass('loading'),
					s = function (data, status) {
						cb(v);
						listitem.removeClass('loading').addClass('success');
						setTimeout(function () {
							listitem.removeClass('success');
						}, 2500);
						change_notice();
					},
					f = function () {
						cb('');
						if ($('#enabled').get(0).checked) {
							$('#enabled').click().change();
						}
						listitem.removeClass('loading').addClass('alert');
						setTimeout(function () {
							var input = listitem.removeClass('alert').addClass('focus').find('input'),
								val = input.val();
							input.val('');
							change_notice();
							input.focus().val(val).select();
						}, 2500);
					},
					mid = 'jsonp' + new Date().getTime(),
					scr = document.createElement('script');
				if (v === '') {
					return f();
				}
				scr.type = 'text/javascript';
				scr.src = 'http://twitter.com/users/show/' + v + '.json?callback=' + mid;
				scr.id = mid;
				window[mid] = s;
				scr.onload = function () {
					this.parentNode.removeChild(this);
					delete window[mid];
				};
				scr.onerror = f;
				document.getElementsByTagName('head')[0].appendChild(scr);
			}
		},
		'delicious_user': {
			set: function (v, cb) {
				var t0 = now(), 
					listitem = $('#delicious_user').parent().addClass('loading'),
					s = function () {
						cb(v);
						listitem.removeClass('loading').addClass('success');
						setTimeout(function () {
							listitem.removeClass('success');
						}, 2500);
						delicious_loggedin(true);
						change_notice();
					},
					f = function () {
						cb('');
						if ($('#enabled').get(0).checked) {
							$('#enabled').click().change();
						}
						listitem.removeClass('loading').addClass('alert');
						$('#delicious_status').val('no user');
						setTimeout(function () {
							var input = listitem.removeClass('alert').addClass('focus').find('input'),
								val = input.val();
							input.val('');
							change_notice();
							input.focus().val(val).select();
						}, 2500);
					};
				$('#delicious_status').val('loading');
				if (v !== '') {
					window.bridge.delicious(v);
					(function () {
						var n = window.bridge.info('delicious_exists');
						if (typeof n === 'undefined' && now() - t0 < 5000) {
							setTimeout(arguments.callee, 500);
						} else {
							if (n) {
								s();
							} else {
								f();
							}
						}
					})();					
				} else if ($('#enabled').get(0).checked) {
					$('#enabled').click().change();
				}
			}
		}
	};
	// all inputs with a.change
	$('a.change').each(function () {
		var l = $(this),
			elm = l.parents('li').find('input'),
			oldval = elm.val(),
			endEdit = function (success) {
				var v = '', n = '', save = function (v) {
					window.bridge.set(n, v, true);
					elm.trigger('change');
				};
				if (!success) {
					elm.val(oldval);
				} else {
					v = elm.val();
					n = elm.attr('name');
					if (converters[n] && converters[n].set) {
						converters[n].set(v, save);
					} else {
						save(v);
					}
					//window.bridge.set(n, v, true);
					//elm.trigger('change');
				}
				elm.attr('readonly', 'readonly');
				l.html('change');
				elm.blur();
			},
			startEdit = function (ev) {
				oldval = elm.val();
				elm.removeAttr('readonly');
				l.html('save');
				elm.focus();
			};
		// bind to link
		l
			.bind('click.changed', function (ev) {
				ev.preventDefault();
				if (l.html() === 'change') {
					startEdit();
				}
			})
			.bind('mousedown.changed', function () {
				if (l.html() === 'save') {
					endEdit(true);
				}
			});
		// bind to input
		elm
			.bind('keypress.changed', function (ev) {
				if (ev.keyCode === 13 || ev.keyCode === 10) { // enter
					endEdit(true);
				} else if (ev.keyCode === 9 || ev.keyCode === 27) { // tab or escape
					endEdit();
				}
			})
			.bind('focus.changed', function (ev) {
				if (l.html() === 'change') {
					startEdit();
				}
			})
			.bind('blur.changed', function (ev) {
				$(this).parent().removeClass('focus');
				if (l.html() === 'save') {
					endEdit();
				}
			});
	});
	// checkboxes
	$('input:checkbox').bind('change', function (ev) {
		var v = this.checked? 1 : 0,
			n = this.name,
			save = function (v) {
				window.bridge.set(n, v, true);
			};
		if (converters[n] && converters[n].set) {
			v = converters[n].set(v, save);
		} else {
			save(v);
		}
	});
	// legend links
	$('legend a').click(function (ev) {
		ev.preventDefault();
		window.open(this.href);
	});
	// enable checkbox
	$('#enabled').bind('change', function (ev) {
		var state = change_notice(),
			set = function (id) {
				$('#twitter_lastid').val(window.bridge.tweet(id));
				$('#enabled').get(0).checked = true;
				window.bridge.set('enabled', '1', true);
				$('#tweecious ol li.decide').hide("normal", function () {
					$(this).remove();
				});
				change_notice();
			};
		if (this.checked && state <= 0) {
			ev.preventDefault();
			this.checked = false;
			window.bridge.set('enabled', '0', true);
			if ($('#tweecious ol .decide').size() === 0 && state === 0) {
				$('<li class="decide"><label>How do you want to start?</label><ol><li class="primary"><button>Parse previous 1000 tweets</button></li><li class="secondary"><a href="#nowon">From now on</a></li></ol></li>')
					.hide()
					.find('.primary button')
						.click(function (ev) {
							ev.preventDefault();
							set('1');
						})
						.end()
					.find('.secondary a')
						.click(function (ev) {
							ev.preventDefault();
							$.ajax({
								url: 'http://twitter.com/statuses/user_timeline/' + $('#twitter_user').val() + '.json',
								dataType: 'jsonp',
								success: function (data, status) {
									var id = '1';
									if (data[0]) {
										id = data[0].id;
									}
									set(id);
								}
							});
						})
						.end()
					.insertAfter($('#enabled').parent())
					.show('normal');
			} else if (state === -1) {
				$('#delicious_user').focus().parent().addClass('focus');
			} else if (state === -2) {
				$('#twitter_user').focus().parent().addClass('focus');
			}
		}
	});
	
	function change_notice() { // -2 missing twitter, -1 missing delicious, 0 if only history, 1 if ok
		var text = '',
			have_twitter = ($('#twitter_user').val() !== ''),
			have_delicious = ($('#delicious_user').val() !== ''),
			accessed_twitter = ($('#twitter_lastid').val() !== ''),
			start = 'You need to set your',
			state = 0;
		if (!have_twitter) {
			state = -2;
			text = start + ' twitter username';
		}
		if (!have_delicious) {
			state = -1;
			text += have_twitter? start : ' and';
			text += ' delicious username';
		}
		if (text !== '') {
			text += '. ';
		}
		if (have_twitter && have_delicious && !accessed_twitter) {
			text += 'Before you start we just need to know this - do you want us to parse old tweets or just start from now on? <a href="#enable">Decide now</a> and start using <strong>Tweecious</strong>.';
		}
		if (text !== '') {
			$('#notice').empty().append($('<p>' + text + '</p>').find('a').click(function (ev) {
				ev.preventDefault();
				$('#enabled').click().change();
			}).end());
		} else {
			state = 1;
			$('#notice').html('<p>These are the <strong>Tweecious</strong> preferences. Set them wisely.</p>');
		}
		return state;
	}

	
	function is_logged() {
		var u = $('#delicious_user').val(), l = delicious_logged, s = u === l, a = null;
		if (u !== '' && l !== null) { // both available
			a = $('#delicious_status').val(s? 'logged in' : 'logged out').parent().find('.comment');
			if (s) {
				a.hide();
			} else {
				a.show();
			}
		}
	}
	function delicious_loggedin(fresh) {
		var t0 = 0, u = '', a = null,
			l = window.bridge.info('delicious_loggedin');
		t0 = arguments.callee.t0 = fresh? now() : arguments.callee.t0 || now();
		if (typeof l === 'undefined' && !window.bridge.fail('delicious_info') && now() - t0 < 5000) {
			setTimeout(arguments.callee, 500);
		} else {
			delicious_logged = l;
			is_logged();
		}
	}

	function get_twitter() {
		var t0 = now(),
			next = function (n) {
				if (n) {
					$('#twitter_user').val(n);
				}
				get_delicious();
			};
		if ($('#twitter_user').val() !== '') {
			return next();
		}
		$('h2.action').remove();
		$('#settings').before('<h2 class="action"><span class="msg">We\'re looking for your <span class="service">Twitter</span> username...</span></h2>');
		window.bridge.guess('twitter_user');
		(function () {
			var n = window.bridge.get('twitter_user');
			if (n === '' && !window.bridge.fail('twitter_user') && now() - t0 < 5000) {
				setTimeout(arguments.callee, 500);
			} else {
				if (n) {
					$('h2 span.msg').replaceWith('<span class="done">...and we found it!</span>');
				} else {
					$('h2 span.msg').replaceWith('<span class="done">Couldn\'t find your <span class="service">Twitter</span> username - you\'ll have to specify it.</span>');
				}
				setTimeout(function () {
					next(n);
				}, 1000);
			}
		})();
	}
	function get_delicious() {
		var t0 = now(),
			next = function (n) {
				if (n) {
					$('#delicious_user').val(n);
				}
				show_all();
				is_logged();
			};
		if ($('#delicious_user').val() !== '') {
			return next();
		}
		$('h2.action').remove();
		$('#settings').before('<h2 class="action"><span class="msg">Now we\'re looking for your <span class="service">Delicious</span> username...</span></h2>');
		window.bridge.guess('delicious_user');
		(function () {
			var n = window.bridge.get('delicious_user');
			if (n === '' && !window.bridge.fail('delicious_user') && now() - t0 < 5000) {
				setTimeout(arguments.callee, 500);
			} else {
				if (n) {
					$('h2 span.msg').replaceWith('<span class="done">...and we found it!</span>');
				} else {
					$('h2 span.msg').replaceWith('<span class="done">Couldn\'t find your <span class="service">Delicious</span> username - you\'ll have to specify it.</span>');
				}
				setTimeout(function () {
					next(n);
				}, 1000);
			}
		})();
	}
	function show_all() {
		change_notice();
		$('h2.action').remove();
		$('form').show();
		$('fieldset').each(function (i, n) {
			setTimeout(function () {$(n).show(400);}, i * 400);
		});
	}
	function twitter_quota() {
		var t0 = 0,
			l = window.bridge.info('twitter_left'),
			h = window.bridge.info('twitter_hourly'),
			n = window.bridge.info('twitter_new');
		t0 = arguments.callee.t0 = arguments.callee.t0 || now();
		if (!n && !window.bridge.fail('twitter_info') && now() - t0 < 5000) {
			setTimeout(arguments.callee, 500);
		} else {
			$('#twitter_apiusage').val(l + '/' + h)
				.parent().find('.comment').html('resets at ' + n);
		}
	}
	
	// show interface
	t0 = now();
	(function () {
		try {
			if (!window.bridge.get || !window.bridge.info) {
				throw "Bridge not ready yet";
			}
			var version = window.bridge.version && window.bridge.version() || '1';
			$('body').addClass('version' + version);
			if (version === '1') {
				$('#showerrors').parent().remove();
			}
			
			$('fieldset input').each(function () {
				var v = window.bridge.get(this.name) || '';
				if (this.type === 'text') {
					if (converters[this.name] && converters[this.name].get) {
						v = converters[this.name].get(v);
					}
					this.value = v;
				} else if (this.type === 'checkbox') {
					this.checked = (v === '1');
				}
			});

			// twitter open link
			$('#twitter legend a').attr('href', 'http://twitter.com/' + $('#twitter_user').val());
			// twitter last id
			$('#twitter_lastid').each(function () {
				if (this.value === '' || this.value === '0') {
					this.value = '';
					$(this).parent().find('a').hide();
					$(this).parent().append('<span class="comment">No requests made to twitter yet.</span>');
				}
			});
			// twitter interval
			$('#twitter_interval').bind('change', function (ev) {
				$(this).parent().find('span.comment').html(parseInt(this.value, 10) % 100 === 1? 'minute' : 'minutes');
			}).trigger('change');
			// twitter last link
			$('#twitter_lastid').each(function () {
				var elm = $(this);
				elm.parents('li').find('a.open').attr('href','http://twitter.com/' + $('#twitter_user').val() + '/status/' + elm.val());
			});
			
			// async stuff
			twitter_quota();
			delicious_loggedin(true);
			// sync stuff - start chain (twitter - delicious - show)
			get_twitter();
		} catch (er) {
			if (now() - t0 < 5000) {
				setTimeout(arguments.callee, 250);
			} else {
				$('h2.action').html('Are you sure you have <strong>Tweecious</strong> enabled?');
			}
		}
	})();
});