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

function readCookie(name)
{
	var results = document.cookie.match (name + '=(.*?)(;|$)');
	if (results) {
		return (unescape(results[1]));
	}
	else {
		return null;
	}
}		

function deleteCookie(name) {
	setCookie(name, "", -1);
}

function getParameter(name)
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if(results == null)
		return "";
	else
		return results[1];
}

function registerUser() {
	setCookie("registered", "yes", 365);
}

/*
 * resourcePath: Full path to the resource
 * htmlStaticPath: Full path to the static html that will redirect the user to the registration form
 * locale: The locale
 * width: Form width
 * height: Form height
 */
function openResource(resourcePath, htmlStaticPath, locale, width, height, newWindow) {
	// If exists the cookie indicating that the user has already been registered it will allow the user to download
	// the resouce directly
	if (readCookie("registered")) {
		if(newWindow) {
			var newWindow = window.open(resourcePath, '_blank');
			newWindow.focus();
		}
		else {
			window.location.href = resourcePath;
		}
	} else {
		// Otherwise a cookie with the resource path will be stored and the user will be redirected to the 
		// registration form
		setCookie("doc", resourcePath);
		var staticHtmlUrl = htmlStaticPath + "?locale=" + locale;
		
		if (!width) {
			width = "500";
		}
		if (!height) {
			height = "600";
		}
		
		window.open(staticHtmlUrl, "registrationForm", "width=" + width + ",height=" + height + 
			",resizable=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollable=yes");
	}
}

/*
 * Downloads the secure resource
 */
function downloadSecureResource() {
	resourcePath = readCookie("doc");
	window.open(resourcePath);
}
