First off, you should never use JavaScript as a security enforcement mechanism, but you can use it within your server's "HTTPS required" error page to automatically (and easily) redirect your viewers to the proper secure page.
So first, configure IIS or Apache to "Require SSL". This will automatically take all users that attempt to target a non HTTPS url to your servers configured 403 (or 403.4) error page. Now go edit that error page (my IIS 7 error page was located at C:\inetpub\custerr\en-US\403.htm; for IIS 6 it was C:\WINDOWS\Help\iisHelp\common\403-4.htm) and add something like this:
<script type="text/javascript">
//<![CDATA[
function RedirNonHttps() {
if (location.href.indexOf("https://") == -1) {
location.href = location.href.replace("http://", "https://");
}
}
//]]>
</script>
Then, simply call the RedirNonHttps function on page load :
<body onload="RedirNonHttps();" >