var TheCarbonAccount = window.TheCarbonAccount || {};

TheCarbonAccount.cookie = function(name, value, options) {
	/* Borrowed from http://jqueryjs.googlecode.com/svn/trunk/plugins/cookie/jquery.cookie.js */
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		var path = options.path ? '; path=' + options.path : '';
		var domain = options.domain ? '; domain=' + options.domain : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = cookies[i].replace(/^\s+|\s+$/g, "");
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};
if (!TheCarbonAccount.cookie('jsDetected')) {
	TheCarbonAccount.cookie('jsDetected', '1');
}

TheCarbonAccount.ajax = (function() {
	var $C = YAHOO.util.Connect;
	var $D = YAHOO.util.Dom;
	function post(url, form, onSuccess, onFailure, numberOfAttempts) {
		numberOfAttempts = numberOfAttempts || 0;
		numberOfAttempts++;
		// Automatically handles CSRF failure case - will resubmit data 
		// if that occurs.
		if (numberOfAttempts > 5) {
			alert('Something went wrong with the CSRF protection');
			// TODO: Fix horrifying error message
			return;
		}
		$C.setForm(form);
		var div = $D.get('modal');
		if (!div) {
			div = $D.getElementsByClassName('registration', 'div')[0];
		}
		if (div) {
			$D.addClass(div, 'ajaxloading');
		}
		$C.asyncRequest('POST', url + '?ajax=1', {
			'success': function(o) {
				if (div) {
					$D.removeClass(div, 'ajaxloading');
				}
				/* o.responseText is eval-able JSON */
				var obj = eval('(' + o.responseText + ')');
				// Resubmit if CSRF failed
				if (!obj.ok && obj.reason == 'csrf') {
					$C.initHeader('X-CSRFToken', obj.csrf_token);
					post(url, form, onSuccess, onFailure, numberOfAttempts);
					return;
				}
				onSuccess(obj);
			},
			'failure': function(o) {
				if (div) {
					$D.removeClass(div, 'ajaxloading');
				}
				onFailure && onFailure(o);
			}
		});
	}
	function failDebug(obj) {
		if (confirm('Ajax failed: ' + obj.statusText)) {
			var win = window.open();
			win.document.write(obj.responseText);
			win.document.close();
		}
	}
	return {
		'post': post,
		'failed': failDebug
	}
})();

/* YUI CustomEvents for various things */
TheCarbonAccount.hooks = {
	'coverArea': new YAHOO.util.CustomEvent(
		'covering part of the page with an element (passed as argument)'
	),
	'uncoverArea': new YAHOO.util.CustomEvent('Reverse of coverPage')
};

/* Easter egg */
YAHOO.util.Event.onDOMReady(function() {
	var tip = YAHOO.util.Dom.getElementsByClassName('tip', 'div');
	if (tip.length > 0) {
		tip = tip[0];
		var img = tip.getElementsByTagName('img')[0];
		var span = tip.getElementsByTagName('span')[0];
		YAHOO.util.Event.on(img, 'click', function() {
			YAHOO.util.Connect.asyncRequest('GET', '/dashboard/tip/', {
				success: function(o) {
					span.innerHTML = o.responseText;
				}
			});
		});
		img.style.cursor = 'hand';
		img.style.cursor = 'pointer';
		img.title = 'Show me another tip!';
	}
});
