I am working on a iPad flip book project. Using html c# Jquery Ajax and Javascript sql server database

I have access all the data in the database to display the books base on client ID. The book works fine the problem is
I have web links or page links that goes on each page. I using ajax and to retrieve the value which works.
The problem I am having is wiring the links to the proper page.

I can pull the links when I add them to the pages. Only the links of the odd pages are wired. but are wire to both pages.

Example on page one. When page loads it does an ajax post if there are any links on page one return those links and
wire them on page one. Then page two ajax post get links for page two and wire them on page two.

Right now it is wiring page one link to page one and two. When I turn the page it is wiring page three links to page three and four and so on.


jquery, ajax and javascript code:
The bold code is my ajax post and retrieval of the links.
the links are prepended to the pages.

Code:
  <script type="text/javascript">
        var ContentCached = 1; // The is 
        var CurrentPage = 1;
        var Contents = new Array();
        var HotLinks = new Array();
        var links = 0;
        var mask = 0;
        var OrgHeight;
        var OrgWidth;
        var Orientation = "portrait";
        var doubleOrSingle = 'double';
        var ResizeTimer;
        var Resizing = false;
        var timer = null;
        var LinkOverlayImg;
        var timeoutID;
        var timeoutIDFromButton;
        var DirectPage = false;
        //Number of times the links have blinked 
        var linkBorderBlinked = 0;
        var timerCount = 0
        var DirectPage = false;

        //Fills the conents array with the address of images from the server 
        //it calls a page method GetUnloadedContent, passes to it the 
        //book id that it gets form the query string 
        function FillContentsArray() {
            $.ajax({
                type: "POST", //Ajax type post 
                url: "tabletBook.aspx/GetUnloadedContent", //URL plus Pagemethod call 
                data: "{'bookid': '" + BookID + "'}", // bookid 
                contentType: "application/json; charset=utf-8", //This is required or you will get all sorts of strange things :-)
                dataType: "json", //We need to specifiy JSON as to have the AJAX serilize the data between Client and server 
                success: function (msg) { // The msg that comes back has in it the d attribute which in this case contains an array from the server
                    Contents = msg.d; //Lets copy the passed back array to a global array 
                    $.ajax({ // Now since we got here , we call another page method which will get is the Original Page width and hieght - *****This is very Important, we need this for the Resize Calculations********
                        type: "POST", //Post
                        url: "tabletBook.aspx/GetWidthHeight", //URL Pluse pagemethod 
                        data: "{'bookid': '" + BookID + "'}", //BookId 
                        contentType: "application/json; charset=utf-8", //Need this as above
                        dataType: "json", //See above
                        success: function (msg) { //The msg here will return an array that has 2 values , the width and height 
                            OrgWidth = msg.d[0]; //Lets save the values in globals 
                            OrgHeight = msg.d[1];
                            // Now we proceed with the rest of the page build
                            GetPageContent();  //This function will Get and load the first page of content 
                            ResizeME(); // We call resize me here to resize the intail page to match the ipad screen
                            PrecacheContent(); // Call to this function will start precaching the image
                        }
                    });
                }
            });
        }
        //Pre caches Images and that were passed in in the contents array 
        //This could probably be done a more AJAX fashion, This function will 
        //Eat up CPU Cycles, so for very large books expect it to be slow 
        function PrecacheContent() {
            //Check if we still need to pull down images 
            if (ContentCached < Contents.length) {
                $("<img>").load(function () { // if so , then create a temp image object and Bind to the load function 
                    //Once the load function executes that means the image is done loading 
                    //Lets get it and set it to the correct page 
                    $("#Page-" + (ContentCached).toString()).css("background-image", "url('" + Contents[ContentCached] + "'),");
                    // images is loading
                    $("#Page-" + (ContentCached).toString()).prepend($("<img src='books/images/ajax-loader.gif' style='position:absolute;left:45%;top:50%;z-index:5000'></img>").addClass("loadPic"));
                    //Lets add the class loaded to it so we can indicate that it is loaded and need not to be pulled again 
                    $("#Page-" + (ContentCached).toString()).addClass("loaded");
                    //Since the book pages are set as the background image lets size them to 100%
                    $("#Page-" + (ContentCached).toString()).css("background-size", "100% 100%");
                    //Since the page is loaded , lets make sure it is visible 
                    $("#Page-" + (ContentCached).toString()).show();
                    //increase the ContentCahced by one 
                    ContentCached = ContentCached + 1;
                    //Call Precache content again until all images are loaded 
                   //  PrecacheContent();
                    $('.loadPic').remove();
                    return;
                }).attr("src", Contents[ContentCached]);       //set the url of the temp image to the content image
            }
            return; //Make sure to return
        }
        //Gets the first page, this can be modified to show a loader image like on the desktop books, once the image loads 
        //then it can be hidden and the page shown (Just a thought) 
        function GetPageContent() {
            if (CurrentPage == 0) { //If Current page is 0 
                //Get it and set the background to the iamge
                $("#Page-" + (CurrentPage).toString()).css("background-image", "url('" + Contents[CurrentPage] + "')");
                $("#Page-" + (ContentCached).toString()).prepend($("<img src='books/images/ajax-loader.gif' style='position:absolute;left:45%;top:50%;z-index:5000'></img>").addClass("loadPic"));
                $("#Page-" + (CurrentPage).toString()).fadeIn("fast"); //Show the page 
                $("#Page-" + (CurrentPage).toString()).addClass("loaded"); // set it to loaded 
                $("#Page-" + (CurrentPage).toString()).css("background-size", "100% 100%"); //Fix the size 
                $("#Page-" + (CurrentPage)).show();
                $('.loadPic').remove();
            } else {
                //The is left empty on purpose
            }
        }

        //Binding to the orientationchange event , this event will 
        //fire an unknown number of times when the device changes orientation 
        //it is unknown because each browser, implements this event 
        //Differently 
        $(window).bind("orientationchange", function (e) {
            $("#BookContainer").fadeOut(); //lets fade out the book 
            if (!Resizing) { //if the resizing flag is false 
                //set the resize timer 
                ResizeTimer = setTimeout(function () {// lets set a time out for one second before we resize anything 
                    if ($(window).width() > $(window).height()) {
                        Orientation = "landscape"; //same as above 
                        $("#book").turn("display", 'double'); //same as above 
                        $("#book").turn("resize"); //same as above

                        $("#book").bind("turned", function (e, page) {
                            var v = $("#book").turn("view");
                            $("#CView").val(v[0] + " - " + v[1]).css({ 'text-align': 'center' });
                            CurrentPage = page;
                        });
                    } else {
                        Orientation = "portrait"//same as above 
                        $("#book").turn("display", 'single'); //same as above 
                        $("#book").turn("resize"); //same as above 
                        $("#book").bind("turned", function (e, page) {
                            var v = $("#book").turn("view");
                            $("#CView").val(v[0]).css({ 'text-align': 'center' });
                            CurrentPage = page;
                        });
                    }
                    ResizeME(); //same as above 
                    $("#BookContainer").fadeIn(); //Fade the book in 
                    clearTimeout(ResizeTimer);
                    Resizing = false;
                }, 1200);
            }
        });


         
        //Bind to the window load event, once all screen assets have 
        //loaded, you may init the book and begin to load the image
        $(window).load(function () {
            //Get images from server and fill content array 
            FillContentsArray();

            //Lets check if we started landscape or portrait 
            //set the display correctly 
            if ($(window).width() > $(window).height()) {
                Orientation = "landscape";
                doubleOrSingle = "double"
            } else {
                Orientation = "portrait";
                doubleOrSingle = "single";
            }

            //Events for buttons 
            $("#btnRight").bind("tap", function (e, page) {
                $("#book").turn("next");
            });

            // click left button turn previouse
            $("#btnLeft").bind("tap", function (e, page) {
                $("#book").turn("previous");
            });

            //swipe page from edge of page left
            $(window).bind("swipeleft", function (e, page) {
                $("#book").turn("next");
            });

            //swipe page from edge of page right
            $(window).bind("swiperight", function (e, page) {
                $("#book").turn("previous");
            });

            //Stops Page current location
            $("#btnAutoStop").bind("tap", function (e, page) {
                clearInterval(timer);
            });

            //Go the First Pages
            $("#btnFirst").bind("tap", function (e, page) {
                $("#book").turn("page", 1)
            })


            $("#book").bind("zoom.doubleTap", function (event) {
                if ($(this).zoom("value") == 0) {
                    $(this).zomm("zoomIn", event);
                } else {
                    $(this).zoom("zoomOut");
                }
            });


            //Goto the Last Pages
            $("#btnLast").bind("tap", function (e, page) {
                // pages = Contents.length;
                $("#book").turn("page", $("#book").turn("pages"));
            });

            //Call the turn js plugin 
            $("#book").turn({ acceleration: true, display: doubleOrSingle, inclination: 0, duration: 650, peel: 'br' } );
            //This function is called when the pages are turned 

            $("#btnAutoPlay").click(function () {
                Play();
            });

            $("#book").bind("turning", function (e, page) {
                //Check if the page is loaded for both left and right 
                //If not loaded load the page and then display 
                if (!$("#Page-" + (page - 1).toString()).hasClass("loaded")) {//If not show a loader image (You may have to tweak this) 
                    $("#Page-" + (page - 1).toString()).prepend($('<img src="books/images/ajax-loader.gif", style="position:absolute;left:40%;top:50%;z-index:5000"/>').addClass("ShowLoading"));
                    $("#Page-" + (page - 1).toString()).css("background-image", "url('" + Contents[page - 1] + "')")
                    $("#Page-" + (page - 1).toString()).addClass("loaded");
                    $("#Page-" + (page - 1).toString()).fadeIn("fast", function () {
                        $(".ShowLoading").remove();
                        $("#Page-" + (page - 1).toString()).remove(".ShowLoading");
                    });
                    $("#Page-" + (page - 1).toString()).css("background-size", "100% 100%");
                } else {
                    $("#Page-" + (page).toString()).show();
                }
                if (!$("#Page-" + (page).toString()).hasClass("loaded")) {
                    $("#Page-" + (page).toString()).prepend($('<img src="books/images/ajax-loader.gif", style="position:absolute;left:40%;top:50%;z-index:5000"/>').addClass("ShowLoading"));
                    $("#Page-" + (page).toString()).css("background-image", "url('" + Contents[page] + "')")
                    $("#Page-" + (page).toString()).addClass("loaded");
                    $("#Page-" + (page).toString()).fadeIn("fast", function () {
                        $(".ShowLoading").remove();
                        $("#Page-" + (page).toString()).remove(".ShowLoading");
                    });
                    $("#Page-" + (page).toString()).css("background-size", "100% 100%");
                } else {

                }
            });

            //This function is called as you start to turn the page, it will load the new page form 
            //the contents array, this is where you would pull links via an ajax call 
            //you dont draw them here though
            $("#book").bind("start", function (e, page) {
                $("#Page-" + page.page).css("background-image", "url('" + Contents[page.page] + "')");
                $("#Page-" + (page.page).toString()).css("background-size", "100% 100%");
                $("#Page-" + page.next).css("background-image", "url('" + Contents[page.next] + "')");
                $("#Page-" + (page.next).toString()).css("background-size", "100% 100%");
                LinkLoading(BookID, page.page);             
                LinkLoading(BookID, page.next);
            });
            // Once the page has been completed turned , display the page numbers in the header or what ever 
            //you want to do after the page has turned, this could be where 
            //you would draw your links posts, or what ever other assets you want to display 
            $("#book").bind("turned", function (e, page) {
                $(".imgLink").remove();
                var v = $("#book").turn("view");
                $("#CView").val(v[0]).css({ 'text-align': 'center' });                             
                $("#pgDiv" + (page - 1).toString()).remove();
                $("#Page-" + (page - 1).toString()).css("background-size", "100% 100%").append(HotLinks);
                $("#pgDiv" + (page).toString()).remove();
                $("#Page-" + (page).toString()).css("background-size", "100% 100%").append(HotLinks);
               // BlinkLinks();
            });
            //When the book first loads it calls this event 
            //it basiclly gets called every time the book 
            //reaches page one 
            $("#book").bind("first", function (e) {
                CurrentPage = 0;
                GetPageContent();
            });
            //we need an inital size for the book 
            $("#book").css("width", "100px");
            $("#book").css("height", "100px");

            ResizeME(); // Call resize to get the correct sizes 
            //remember by this time in the execution, your assets are loaded 
            $("#book").fadeIn("fast"); // Show the book
            LinkLoading(BookID, CurrentPage);
        });
        $(".imgLink").live("mouseover", function () {
            $(this).css("background-image", "url(" + LinkOverlayImg + ")");
            $(this).css("cursor", "pointer");
        });
        $(".imgLink").live("mouseout", function () {
            $(this).css("background-image", "url(books/images/transparent.gif)");
        });

        $(".imgLink").live("tap", function (e, page) {
            var LinkType = $(this).attr("linkType");
            if (LinkType.toUpperCase() == "WEB") {
                var href = $(this).attr("title");
                window.open(href, "_blank");
            } else if (LinkType.toUpperCase() == "DIRECTPAGE") {
                var pgLink = $(this).attr("title");
                $("#book").turn("page", parseInt(pgLink));
            } else if (LinkType.toUpperCase() == "IMAGELINK") {
                href = $(this).attr("title");
            } else if (LinkType.toUpperCase() == "VIDEOLINK") {

                //video link
            }
        });
        //When the doc is ready , show a loader image, for some add reason I cant get it to display, I will 
        //leave it for you to figure out
        $(document).ready(function () {
            $(loaderImage).prepend("#book").prepend($('<img src="books/images/ajax-loader.gif", style="position:absolute;left:40%;top:50%;z-index:5000"/>').addClass("ShowLoading"));
            BookID = getParameterByName("bookid"); //Get the query string param that has the book Id 
            CurrentPage = 0; //set the current page to zero 
              $(".Showloading").remove();
        });

        function Play() {
            timer = setInterval(function (e, page) {
                var way = 1;
                if (way == 1) {
                    $("#book").turn("next");
                }
            }, 1650);
        }

     // Ajax call to get the hot links from the database and return
        function LinkLoading(BookID, page) {
            //Starting code for the search for links
            $.ajax({
                type: "POST", // AJAX type post
                url: "tabletbook.aspx/GetPageLinks",
                data: '{"BookID": "' + BookID + '",  "page": "' + page + '"}',
                contentType: "application/json; charset=utf-8", //This is required or you will get all sorts of strange things :-)
                dataType: "json", //We need to specifiy JSON as to have the AJAX serilize the data between Client and server 
                success: function (link) { // The msg that comes back has in it the d attribute which in this case contains an array from the server
                    HotLinks = link.d; //Lets copy the links to a global array
                    $.ajax({
                        type: "POST",
                        url: "tabletbook.aspx/GetLinkOverImage",
                        data: '{"BookID": "' + BookID + '"}',
                        contentType: "application/json; charset=utf-8", //This is required or you will get all sorts of strange things :-)
                        dataType: "json", //We need to specifiy JSON as to have the AJAX serilize the data between Client and server 
                        success: function (ret) {
                        LinkOverlayImg = ret.d;
                        }
                    });
                  
                }
            }); 
         
        }
</script>