$(function() {

	var animating = null;

	$('div#register-with-us').each(function() {

		var $this = $(this);
		var width = $this.outerWidth(true);
		var $link = $(this).find('h3 a');

		var openForm = function() {
			if (!animating) {
				animating = true;
				$this.removeClass('closed');
				$this.animate({
					right : 0
				}, {
					duration : 1000,
					easing : 'easeOutQuad',
					complete : function() {
						animating = false;
						$link.unbind('mouseenter');
						$link.bind('click', function() {
							closeForm();
						});
					}
				});
			}
		};

		var closeForm = function(duration) {
			
			duration = typeof(duration) != 'undefined' ? duration : 500;
			
			if (!animating) {
				$this.addClass('closed');
				animating = true;
				// close it
				$this.animate({
					right : (width * -1) + 26
				}, {
					duration : duration,
					easing : 'easeOutQuad',
					complete : function() {
						animating = false;
						$link.unbind('click');
						$link.bind('mouseenter', function() {
							openForm();
						});
					}
				});
				
			}
		};

		var createCookie = function(name, value, days) {
			var expires = "";
			if (days) {
				var date = new Date();
				date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
				expires = "; expires=" + date.toGMTString();
			}
			document.cookie = name + "=" + value + expires + "; path=/";
		};

		var readCookie = function(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for ( var i = 0; i < ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0) == ' ')
					c = c.substring(1, c.length);
				if (c.indexOf(nameEQ) == 0)
					return c.substring(nameEQ.length, c.length);
			}
			return null;
		};

		// init
		if ($this.hasClass('closed')) {
			if (readCookie('form-seen') != 'true') {
				setTimeout(function() {
					createCookie('form-seen', 'true', 7);
					closeForm();
				}, 2000);
			} else {
				createCookie('form-seen', 'true', 7);
				closeForm(0);
			}
		} else {
			openForm();
		}

	});

});
