$(document).ready(function(){
	dialogCreated = false;
	$("a.thickbox").live("click", function() {
		return registerDownload($(this).attr("href"));
	});
});

function registerDownload(documentUrl) {
	// If registration has been done (this request) don't display form
    if (hasRegistered)
        return true;

	// Prepare form
	$("#formtarget").val(documentUrl);
	showDownloadThickbox();
	$("#form").wrapInner("<form></form>");

	// Set up form
	$("#form form").validate({
		rules: {
			name: {
				required: true,
				minlength: 2
			},
			company: {
				required: true,
				minlength: 2
			},
			industry: {
				required: true
            },
			phone: {
				required: true
			},
			country: {
				required: true,
				minlength: 2
			},
			email: {
				required: true,
				email: true
			}
		},
		messages: {
			name: {
				required: "",
				minlength: ""
			},
			company: {
				required: "",
				minlength: ""
			},
			industry: "",
			phone: "",
			country: {
				required: "",
				minlength: ""
			},
			email: {
				required: "",
				email: ""
			}
		},
		errorElement: "em",
		submitHandler: function(form) {
			$.ajax({
				url: $("#formtarget").val(),
				type: "POST",
				data: {
					registerfordownload: "true",
					name: encodeURIComponent($("#name").val()),
					title: encodeURIComponent($("#title").val()),
					company: encodeURIComponent($("#company").val()),
					industry: encodeURIComponent($("#industry").val()),
					country: encodeURIComponent($("#country").val()),
					email: encodeURIComponent($("#email").val()),
					phone: encodeURIComponent($("#phone").val()),
					customer: $("#customer").attr("checked") ? "yes" : "no"
				},
				success: function(html) {
					displayTipMessage(html, false);
					hasRegistered = true;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					displayTipMessage(XMLHttpRequest.status + ";" + textStatus + ";" + errorThrown, true);
				}
			});
		}
	});

	// Send form
	$("#download-commands a").click(function() {
		$("#form form").submit();
		return false;
	});

	return false;
}

// Display form response
function displayTipMessage(message, includeParagraph) {
	var text = message;
	if (includeParagraph)
		text = "<p>" + text + "</p>"
	$("#download-dialog .rte").html(text);
	$("#form").hide();
}

function showDownloadThickbox() {

	// Create a new dialog-object each time, workaroung a bug where it prevents clicks in the entire window
	if(dialogCreated) {
		$("#download-dialog").dialog("open");
	} else {
		$("#download-dialog").dialog({
			modal: true,
			resizable: false,
			dragable: true,
			width: 550,
			height: 345,
			overlay: {
				opacity: 0.5,
				background: "black"
			}
		});
		dialogCreated = true;
	}

	// Unhide the hidden div
	$("#download-dialog").show();
}

