/* jslint verified 2009.02.02 */
/*jslint browser: true, onevar: true, undef: true, white: false, eqeqeq: true */
/*global document, $, $$, Ajax, cancelBubble, Twitter,
	doShorten, checkCustomize, doCheckCustomize, doAjax, checkSucceeded, checkFailed, shortenSucceeded, shortenFailed */
var Index = function() {
	var url, customize, customlinks, shorten, shortened, error, _aLink,
		baseUrl = window.location.protocol + '//' + window.location.host + '/', //"http://tra.kz/",
		customizeTimeout, customizeUpdateInterval = 250,
		_regCustom = /^[a-z0-9\-_,\(\)\*:]*$/i,
		ids = {
			url: 'url', customize: 'customize', shorten: 'shorten', shortened: 'shortened',
			customlinks: 'customlinks',
			error: 'error'
		}, msgs = {
			err: 'There was an error shortening your URL. Please try again',
			customInvalidErr: 'You cannot use your custom URL. Please choose another one.',
			customInvalidExtraErr: 'You cannot use your custom URL. Please choose another one.<br />(Note: only letters, numbers, and the symbols _ - , ( ) * : are allowed.'
		};

	function setup() {
		url = $(ids.url);
		customize = $(ids.customize);
		shorten = $(ids.shorten);
		shortened = $(ids.shortened);
		customlinks = $(ids.customlinks);
		error = $(ids.error);
		url.addEvent('keydown', function (e) { if (window.enterKey(e)) { doShorten(); } });
		customize.addEvent('keydown', function (e) { if (window.enterKey(e)) { doShorten(); } });
		customize.addEvent('change', checkCustomize);
		customize.addEvent('keyup', checkCustomize);
		customize.oldVal = customize.value;
		shorten.addClick(doShorten);
		url.focus();
		url.select();
		_aLink = $('initlink_addthis');
		_aLink.addEvent('mouseover', function () { return addthis_open(_aLink, '', 'http://tra.kz/', 'Tra.kz URL Shortener'); });
		_aLink.addEvent('mouseout', addthis_close);
		_aLink.setClick(function () { return addthis_sendto(); });
	}

	function checkCustomize() {
		if (customizeTimeout) {
			window.clearTimeout(customizeTimeout);
		}
		customizeTimeout = window.setTimeout(doCheckCustomize, customizeUpdateInterval);
	}

	function doCheckCustomize() {
		var c = customize.value;
		window.clearTimeout(customizeTimeout);
		if (c.length > 0 && c !== customize.oldVal) {
			if (!_regCustom.test(c)) { checkFailed(false); }
			else { doAjax('/api/test', checkSucceeded, checkFailed, false); }
			customize.oldVal = c;
		} else if (error) { error.empty(); }
	}

	function checkSucceeded(originalC, request) {
		var obj = JSON.parse(request.responseText);
		if (obj.y) {
			if (originalC && error) {
				error.empty();
				if (originalC !== obj.c) { error.update(msgs.customInvalidErr); }
			}
		}
	}

	function checkFailed(request) {
		error.update(request === false ? msgs.customInvalidExtraErr : msgs.customInvalidErr);
	}

	function doShorten() {
		var l = url.value, c = customize.value;
		if (error) { error.empty(); }
		if (l.length > 0 && l !== "http://") {
			doAjax('/api/shorten', shortenSucceeded, shortenFailed, false);
		} else if (l.length === 0 && error) {
			error.update("We can't make 'nothing' any shorter!");
		} else if (l === "http://" && error) {
			error.update('"http://" isn\'t a link!');
		}
	}

	function doAjax(ajaxUrl, onSuccess, onFailure, post) {
		var l = url.value, c = customize.value,
			ajax = new Ajax(ajaxUrl,
				{	method: post ? 'POST' : 'GET',
					parameters: "l=" + encodeURIComponent(l) + "&c=" + encodeURIComponent(c) + '&api=trakz',
					onSuccess: onSuccess.curry(c),
					onFailure: onFailure
				}
			);
		ajax.send();
	}

	function addCustomLink(c) {
		c = baseUrl + c;
		customlinks.create('a').update(c).attrib('href', c);
	}
	function addShortLink(s) {
		s = baseUrl + s;
		shortened.create('a').update(s).attrib('href', s);
	}

	function shortenSucceeded(originalC, request) {
		var c, obj;
		try { obj = JSON.parse(request.responseText); }
		catch (ex) { obj = {}; }
		if (obj.y && obj.s) {
			if (originalC) {
				if (originalC !== obj.c) {
					error.update(msgs.customInvalidErr);
				} else {
					c = obj.c;
				}
			}
			$('content').addClassName('auto');
//			$('adBox').addClassName('big');
			$$(shortened.parentNode).show();
			Twitter.setShortened(baseUrl + (c || obj.s), obj.a === 1);
			shortened.empty();
			addShortLink(obj.s);
			if (c) {
				customlinks.empty();
				addCustomLink(c);
			}
		} else {
			error.update(msgs.err);
		}
	}

	function shortenFailed(request) {
		error.update(msgs.err);
	}

	window.addLoad(setup);
}();