moved most code out of $(document).ready