(function($) {
	
	$.fn.eBookLink = function() {
		
		return this.each(function() {
			
			var $this = $(this), href = $this.attr('href'), ebook = $this.attr('id').substr(11);

			$this.click(function() {

				var position = $(this).position(), css = {'top':(position.top - 93) + 'px', 'left':(position.left - 53) + 'px'};

				//console.log(css);
				//console.log(position);
				
				if(position.left == 0) {
					css.left = '-58px';
				}
				
				var $html = $("<div class=\"ebook-form\">" + 
						"<input type=\"text\" name=\"name\" value=\"Your Name\" onfocus=\"if(this.value == 'Your Name') this.value = '';\" onblur=\"if(this.value == '') this.value = 'Your Name'\"/>" + 
						"<input type=\"text\" name=\"email\" value=\"Email Address\" onfocus=\"if(this.value == 'Email Address') this.value = '';\" onblur=\"if(this.value == '') this.value = 'Email Address'\"/>" +
						"* Name and email are required fields." +
						"<a class=\"ebook-link-2\" style=\"margin-left: 30px\">Download &raquo;</a>" +
					"</div>");


				$html.find('a.ebook-link-2').click(function() {

					var name = $html.find('input[name="name"]').val(), email = $html.find('input[name="email"]').val(), feedback = '';

					
					if(name.length == 0 || name == 'Your Name') {
						feedback += "Please enter your name.\n";
					}

					if(email.length == 0 || email.length == 'Email Address' || !email.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)) {
						feedback += "Please enter a valid email address.\n";
					}

					if(feedback.length > 0) {
						alert(feedback);
					}
					else {

						$html.css('cursor', 'wait');

						$.post('/ebook-request.php', { ebook: ebook, name: name, email: email }, function(resp, stat) {
							window.open(href);
							$html.css('cursor', 'default').fadeOut(function() { $html.remove(); });
						});
					}

					return false;

				});


				$html.insertAfter(this).css(css).fadeIn('slow');

				return false;
			});

		});
	}

})(jQuery);


