It's best not to include the script in the header, because the header is hard to talk to. Instead you should use Page.ClientScript.RegisterClientScriptBlock() and Page.ClientScript.RegisterClientScriptBlockInclude() (in 2.0) and Page.RegisterClientScriptBlock() in 1.0. In 1.0 you can embed the Client Script Include link as a as a string which is not as clean as in 2.0, but it works.
As Keith points out, it's best to isolate that code either into a control or class so that it's reusable but you can also do it in code directly.
As to #2 of detecting https you can check for Request.ServerVariables("SERVER_PORT") and look for port 443 (or maybe something other than 80). Actually ServerVariables("SERVER_PORT_SECURE") is probably a better choice. If it's not the secure port Redirect to the same URL with a new port. The easiest way to do that is to use the URI class and change the port.
This Blog post has some related content that describes just this scenario:
http://west-wind.com/weblog/posts/1412.aspx+++ Rick ---