$(document).ready(function(){
	
	// This is the Whitepaper download dialog window controls.
	var first_name = $("#first_name"),
		last_name = $("#last_name"),
		email = $("#email"),
		company = $("#company"),
		allFields = $([]).add(first_name).add(last_name).add(email).add(company),
		tips = $("#validateTips"),
		count = 10,
		timer = null,
		paper = 0;

	function updateTips(t) 
	{
		tips.text(t).effect("highlight",{},1500);
	}

	function checkLength(o,n,min,max) 
	{
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass('ui-state-error');
			updateTips("Length of " + n + " must be between "+min+" and "+max+".");
			return false;
		} else {
			return true;
		}
	}

	function checkRegexp(o,regexp,n) 
	{
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass('ui-state-error');
			updateTips(n);
			return false;
		} else {
			return true;
		}
	}

	function countdown() 
	{
		if (count >= 1) {
			count--;
			$(".time").text(count);  // update count
		} else {
			window.clearInterval(timer);  // stop the timer
			location.href = "/ajax/wp_download.php?download=1&paper="+paper;
			$("#order").dialog('close');
		}
	}

	$("#order").dialog({
		bgiframe: true,
		autoOpen: false,
		width: 415,
		modal: true,
		title: "Would you like to stay in touch?",
		buttons: {
			'Download': function() 
			{
				var bValid = true;
				allFields.removeClass('ui-state-error');

				bValid = bValid && checkLength(first_name,"First Name",2,30);
				bValid = bValid && checkLength(last_name,"Last Name",2,30);
				bValid = bValid && checkLength(email,"Email",6,80);
				bValid = bValid && checkLength(company,"Company",5,50);
			
				// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
				bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"Your email address isn't correct.");
			
				if (bValid) 
				{
					// Save data and force download of whitepaper
					paper = $('#paper',this).val();
					var formData = $('form',this).serialize();
					$('form,#no-thanks',this).fadeOut();
					$('.ui-dialog-buttonpane').fadeOut();
					$('#downloadLink1a a').attr("href","/uploads/whitepapers/"+paper+"_whitepaper.pdf");
					$('#downloadLink1a a').attr("rel",paper);
					$('#downloadLink1a').fadeIn().effect("highlight",{},1500);
				
					$.get('/ajax/wp_download.php',formData,function(data){
						if(data=='success')
						{
							$('#order').dialog('option', 'title', 'Download your document...');
							//timer = window.setInterval(countdown, 1000);
						}
					});
				
				}
			}
		},
		close: function() {
			//location.reload(true);
			window.clearInterval(timer);
			count = 10;
			$('form,#no-thanks',this).show();
			$('.ui-dialog-buttonpane').show();
			$('#downloadLink1a,#downloadLink2a').hide();
		}
	});
	
	$('#no-thanks').click(function(){
		paper = $('#paper').val();
		$('form,.ui-dialog-buttonpane,#no-thanks').fadeOut();
		$('#downloadLink2a a').attr("href","/uploads/whitepapers/"+paper+"_whitepaper.pdf");
		$('#downloadLink2a a').attr("rel",paper);
		$('#downloadLink2a').fadeIn().effect("highlight",{},1500);
		$('#order').dialog('option', 'title', 'Download your document...');
		//timer = window.setInterval(countdown, 1000);
		return false;
	});
	
	$('#downloadLink1a a, #downloadLink2a a').click(function(){
		// Count download
		var paper_id = $(this).attr("rel");
		$.get("/ajax/wp_download.php", { paper: paper_id, add_count: true } );
		
		// Close dialog then return to send file
		$("#order").dialog('close');
		return true;
	});

	$('table td.download a').click(function(){
		$('#order').dialog('open');
		var paper = this.id;
		paper = paper.split('_');
		$('#order #paper').val(paper[1]);
		$('#first_name').focus();
		return false;
	});

	$('table td.details a').click(function(){
		var block = $(this).parent().parent().next();
		$('td div',block).slideToggle();
		$(this).toggleClass("close");
		return false;
	});

	$('#downloadLink a').click(function(){
		$('#order').dialog('close');
		return true;
	});

});