jquery and javascript functions timing
<p>I am trying to write a cookie based menu which contains three options (three links). Now I want that when a user gets on the site, they must have to choose one of the three options. The user's selection may be store in a cookie so that next time when he arrives at the same site, he does not have to make the selection again and he must be directed automatically to his previous selection.</p>

<p>This is my code for that</p>

<pre><code>&lt;/style&gt;
&lt;!-- style Develpor page ends here--&gt;
&lt;script src="jqery1.8.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;

var val;

$(document).ready(function (e) {
  $('.nav a').click(function (event) {
    event.preventDefault();
    val = $(this).index();

    if (val == 0) {

      $('#hide_main').hide();
      $('.main_BSNS').animate({
        opacity: "show",
        height: "400px"
      }, 'slow')

    } //if val==0 ends here

    else if (val == 1) {

      $('#hide_main').hide();
      $('.main_ACTNT').animate({
        opacity: "show",
        height: "400px"
      }, 'slow')

    } else if (val == 2) {

      $('#hide_main').hide();
      $('.main_devp').animate({
        opacity: "show",
        height: "400px"
      }, 'slow')

    }
  });
});



&lt;!--cookies starts here--&gt;
function getCookie(c_name) {
  var i, x, y, ARRcookies = document.cookie.split(";");
  for (i = 0; i &lt; ARRcookies.length; i++) {
    x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
    y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
    x = x.replace(/^\s+|\s+$/g, "");
    if (x == c_name) {
      return unescape(y);
    }
  }
}

function setCookie(c_name, value, exdays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
  document.cookie = c_name + "=" + c_value;
}

function checkCookie() {
  var username = getCookie("BSNS");
  if (username != null &amp;&amp; username != "") {
    $('#hide_main').hide();
    $('.main_BSNS').animate({
      opacity: "show",
      height: "400px"
    }, 'slow')

  } else {

    username=val;
    alert(val);
    if (username != null &amp;&amp; username != "") {
      setCookie("BSNS", username, 365);
      $('#hide_main').hide();
      $('.main_BSNS').animate({
        opacity: "show",
        height: "400px"
      }, 'slow')

    }
  }
}
&lt;!--cookies ends here--&gt;
&lt;/script&gt;
</code></pre>

<p>Now function <code>checkCookie()</code> is called by body <code>onload="checkCookie()"</code> and the alert returns the value of <code>val</code> as <code>undefined</code> I know this is because the <code>checkCookie()</code> is being loaded before <code>document.write</code> but I don't know how to overcome this difficulty.</p>
