/**
 * Aptus Interactive 2011
 * @author Paul Bain
 * @author Mark Robinson
 */
var defaultWidth = 2048;
var defaultHeight = 1536;
var defaultRatio = defaultWidth / defaultHeight;
var currentRatio = defaultRatio;
var magazine;
var timeouts = [];

(function($){
 $.fn.aptusReader = function(pages) {
    var settings = {};
    var currentPage = 0;
    var navTimeout = null;
    var navShown = false;
    var apiUrl = 'http://magazine-api.aptusinteractive.com/';
    var defaultFooterHeight = 30;
    var defaultHeaderHeight = 33;
    var animationDuration = 450;
   
    return this.each(function() {
        var $eBook = $(this);
        magazine = pages;
        /* Setup the reader*/
        $eBook.init = function(){
            // Setup variables
            $eBook.isDoubleSize=false; // i.e. zoomed
            $eBook.lense = $(this).find('#lense');
            defaultHeaderHeight = $eBook.lense.offset().top;
            $eBook.canvas = $(this).find('.canvas');
            $eBook.controls = $(this).find('#aControls');
            $eBook.navigator = $(this).find('.navigator');
            $eBook.overview = $(this).find('.overview');
            $eBook.xOfy = $(this).find('#xOfy');
            $eBook.animating = false;
            // Add hover/off listeners for the thumbnail navigator
            $eBook.navigator.hover(function(){
                $eBook.showNavigator();
                },
                function(){
                    $eBook.hideNavigator();
                }
            );
            $eBook.pageCount = magazine.pages.length;
            defaultWidth = magazine.pages[0].width;
            defaultHeight = magazine.pages[0].height;
            defaultRatio = defaultWidth / defaultHeight;
            //Add a page number to each page
            $.each(magazine.pages,function(i,page){
                page.number=(i+1);
            });

            //Setup intial page size
            $eBook.updatePageSize();

            //Add listner for window resize
            $(window).resize(function(){
                $eBook.updatePageSize();
            });

            //Setup the 1st page
            $eBook.goToPage(1);
            $eBook.find('#leftControl').click(function(e){
                e.preventDefault();
               $eBook.previousPage();
            });
            $eBook.find('#rightControl').click(function(e){
                e.preventDefault();
                $eBook.nextPage();
             });

            // Load thumbnails into the navigator
            $eBook.loadThumbs();

            // Add key listners for right and left arrow buttons
            $(window).keydown(function(event){
                if(event.keyCode == 37 && !$eBook.animating){
                    $eBook.previousPage();
                }else if(event.keyCode==39 && !$eBook.animating){
                    $eBook.nextPage();
                }
            });

            //Add listner for the search form
            $('.search form').submit(function(e){
                e.preventDefault();
                $eBook.findText($('#search').val());
            });

            //Add keydown listners to search input to remove failed class
            $('#search').keydown(function(){
                $(this).removeClass('failed');
            });
        };

        /**
         * Search Function
         */
        $eBook.findText = function(term){
            var found = false;
            var reg = new RegExp(term,'i');
            if($eBook.currentPage<magazine.pages.length){
                for(x=$eBook.currentPage;x<magazine.pages.length;x++){
                    if(magazine.pages[x].text.search(reg)>0){
                        $eBook.goToPage(x+1);
                        return;
                    }
                }
            }
            // wrap search
            if(!found && $eBook.currentPage!=1){
                for(x=0;x<=$eBook.currentPage - 1;x++){
                    if(magazine.pages[x].text.search(reg)>0){
                        $eBook.goToPage(x+1);
                        return;
                    }
                }
            }
            $('#search').addClass('failed');
        };

        /**
         * Resize canvas and pages after window resize
         */
        $eBook.updatePageSize = function() {
            var height = $(window).height() - defaultFooterHeight - defaultHeaderHeight;
            var width = height * 2 * defaultRatio; // 2page window
            
            if($eBook.isDoubleSize){
                height=height*2;
                width=width*2;
            }
            else {
                $eBook.lense.offset({top : defaultHeaderHeight}); // Reset top after dragStop
            }
            $eBook.height = height;
            $eBook.width = width / 2;
            
            $eBook.lense.height(height);
            $eBook.lense.width(width);
            
            $eBook.lense.css('left',($(window).width() - width) / 2);
            $eBook.canvas.height('100%');
            $eBook.canvas.width(3*width); // 6pages in width
            $eBook.canvas.css('left',-width); // 2page offset left
            
            $eBook.navigator.css('top',$(window).height()-30);
            navShown = false;

            $eBook.sizeRatio = $eBook.height / defaultHeight; //y scaleFactor
            currentRatio = $eBook.sizeRatio;

            $eBook.singlePage = 2.5 * $eBook.width;
            $eBook.leftPage = 2 * $eBook.width;
            $eBook.rightPage = 3 * $eBook.width;
            
            // Use seperate resize when resetting without page resize (after draggable)
            $eBook.resizePages();

            //Recreate image maps, could optimise this
            $.each(magazine.pages,function(e,p){
                $eBook.createMap(p,$eBook.find('#page_'+p.number));
            });
        };

        /**
         * Reset page sizes for all existing pages, could just do this for visible pages
         */
        $eBook.resizePages = function(){
            $eBook.find('.page').css('height',$eBook.height);
            $eBook.find('.page').css('width',$eBook.width);
            $eBook.find('.leftPage').css('left',$eBook.leftPage);
            $eBook.find('.rightPage').css('left',$eBook.rightPage);
            $eBook.find('.singlePage').css('left',$eBook.singlePage);
        };

        /**
         *Go to the next page in the magazine 
         */
        $eBook.nextPage = function(){
            if($eBook.currentPage == magazine.pages.length || $eBook.currentPage > magazine.pages.length){
                return;
            }
            $eBook.goToPage($eBook.currentPage+1);
        };

        /**
         * Go to the previous page in the magazine
         */
        $eBook.previousPage = function(){
            if($eBook.currentPage==1){
                return;
            }
            if($eBook.currentPage%2==0 || (($eBook.currentPage%2)==1 && $eBook.currentPage == magazine.pages.length)){
                $eBook.goToPage($eBook.currentPage-2);
            } else {
                $eBook.goToPage($eBook.currentPage-3);
            }
        };
        
        $eBook.updatePageNumber = function(pageNumber) {
            $eBook.xOfy.text(pageNumber + "/" + $eBook.pageCount);
        };

        $eBook.doOnLoad = function(page){
            var pageData = magazine.pages[page-1];
            for(var x=0;x<pageData.on_load.length;x++){
                var e = new jQuery.Event('runactions');
                e.action_data_id=pageData.on_load[x].action_data_id;
                $('#'+pageData.on_load[x].element_id).triggerHandler(e);
            }
        };

        /**
         * Go to a specific page
         */
        $eBook.goToPage = function(pageNumber){
            clearTimeouts();

            if ($eBook.isDoubleSize) {
                $eBook.toggleDoubleSize();//reset zoom on transition
            }

            // do not transition if page already available
            if ($eBook.currentPage == pageNumber || ((pageNumber % 2)==0 && pageNumber+1 == $eBook.currentPage)) {
                return;
            }

            $eBook.updatePageNumber(pageNumber);

            var slideOffset = $eBook.leftPage + 2 * $eBook.width;
            if(pageNumber<1){
                pageNumber=1;
            } else if(pageNumber>magazine.pages.length){
                pageNumber=magazine.pages.length;
            } else if(pageNumber %2 && pageNumber>1){
                pageNumber--; // Requesting odd page > 1
            }
            
            // Get existing slides
            $left = $eBook.find('.leftPage:visible');
            $right = $eBook.find('.rightPage:visible');
            $single = $eBook.find('.singlePage:visible');

            var isSingle = true;
            page = $eBook.getPage(pageNumber);

            $eBook.lastPage = $eBook.currentPage;
            $eBook.currentPage = pageNumber;
            
            if(pageNumber!= 1 && (pageNumber % 2)==0 && (pageNumber < magazine.pages.length)){
                var isSingle = false;
                page2 = $eBook.getPage(pageNumber+1);
                $eBook.currentPage =pageNumber+1;
            }

            if(pageNumber == 1 && !$left.length &&  !$right.length && !$single.length){
                page.show();
            } else {
                // Animate
                $eBook.animating = true;
                if($eBook.currentPage>$eBook.lastPage){
                    // Animage Right
                    if($single.length>0){
                        $single.addClass('remove');
                        if(isSingle){
                            // Animage from single to single
                            page.css('left', (slideOffset + $eBook.width/2)).show().addClass('added');
                            page.animate({
                                left:($eBook.leftPage + $eBook.width/2)
                            },animationDuration,function(){
                                $eBook.resetAfterAnimation();
                            });
                            $single.animate({
                                left:($eBook.width/2)
                            },animationDuration);
                        } else {
                            //Animage from single to double
                            page.css('left', slideOffset).show().addClass('added');
                            page.animate({
                                left:$eBook.leftPage
                            },animationDuration,function(){
                                $eBook.resetAfterAnimation();
                            });
                            $single.animate({
                                left:($eBook.width/2)
                            },animationDuration);
                            page2.css('left', slideOffset+$eBook.width).show().addClass('added');
                            page2.animate({
                                left:$eBook.rightPage
                            },animationDuration);
                        }
                    } else {
                        $left.addClass('remove');
                        $right.addClass('remove');
                        if(isSingle){
                            //Animage from double to single
                            page.css('left', (slideOffset + $eBook.width/2)).show().addClass('added');
                            $left.animate({
                                left: 0
                            },animationDuration);
                            $right.animate({
                                left: $eBook.width
                            },animationDuration);
                            page.animate({
                                left: ($eBook.leftPage + $eBook.width/2)
                            },animationDuration,function(){
                                $eBook.resetAfterAnimation();
                            });
                        } else {
                            //Animage from Double to Double
                            page.css('left', slideOffset).show().addClass('added');
                            $left.animate({
                                left: 0
                            },animationDuration);
                            $right.animate({
                                left: $eBook.width
                            },animationDuration);
                            page.animate({
                                left:$eBook.leftPage
                            },animationDuration,function(){
                                $eBook.resetAfterAnimation();
                            });
                            page2.css('left', slideOffset+$eBook.width).show().addClass('added');
                            page2.animate({
                                left:$eBook.rightPage
                            },animationDuration);
                        }
                    }
                } else {
                    // Animage Left
                    if($single.length>0){
                        $single.addClass('remove');
                        if(isSingle){
                            // Animage from single to single
                            page.css('left', ($eBook.width/2)).show().addClass('added');
                            page.animate({
                                left:($eBook.leftPage + $eBook.width/2)
                            },animationDuration,function(){
                                $eBook.resetAfterAnimation();
                            });
                            $single.animate({
                                left:(slideOffset + $eBook.width/2)
                            },animationDuration);
                        } else {
                            //Animage from single to double
                            page.css('left', 0).css('z-index',11).show().addClass('added');
                            page2.css('left', $eBook.width).css('z-index',11).show().addClass('added');
                            $single.animate({
                                left: ($eBook.width * 3/2 + $eBook.rightPage)
                            },animationDuration,function(){
                                $eBook.resetAfterAnimation();
                            });
                            page.animate({
                                left:$eBook.leftPage
                            },animationDuration);
                            page2.animate({
                                left:$eBook.rightPage
                            },animationDuration);
                        }
                    } else {
                        $left.addClass('remove');
                        $right.addClass('remove');
                        if(isSingle){
                            //Animage from double to single
                            page.css('left', $eBook.width/2).css('z-index',11).show().addClass('added');
                            $left.animate({
                                left: ($eBook.width + $eBook.rightPage)
                            },animationDuration);
                            $right.animate({
                                left: (2*$eBook.width + $eBook.rightPage)
                            },animationDuration);
                            page.animate({
                                left:($eBook.leftPage + $eBook.width/2)
                            },animationDuration,function(){
                                $eBook.resetAfterAnimation();
                            });
                        } else {
                            //Animage from Double to Double
                            page.css('left', 0).css('z-index',11).show().addClass('added');
                            $left.animate({
                                left: ($eBook.width + $eBook.rightPage)
                            },animationDuration);
                            $right.animate({
                                left: (2*$eBook.width + $eBook.rightPage)
                            },animationDuration);
                            page.animate({
                                left:$eBook.leftPage
                            },animationDuration,function(){
                                $eBook.resetAfterAnimation();
                            });
                            page2.css('left', $eBook.width).css('z-index',12).show().addClass('added');
                            page2.animate({
                                left:$eBook.rightPage
                            },animationDuration);
                        }
                    }
                }
            }
            $eBook.doOnLoad(pageNumber);
            $eBook.getPage($eBook.currentPage+1);
            $eBook.getPage($eBook.currentPage+2);
        };

        $eBook.resetAfterAnimation = function(){
            $eBook.find('.remove').hide().removeClass('remove');
            $eBook.find('.added').css('z-index',10).removeClass('added');
            $eBook.animating = false;
        };

        /**
         * Get a page, checks to see if it's been created already
         */
        $eBook.getPage = function(pageNumber){
            if(pageNumber<1 || pageNumber>magazine.pages.length){
                return;
            }
            pageIndex = pageNumber-1;
            if(pages.pages[pageIndex].html==null){
                pages.pages[pageIndex].html = this.createPage(pages.pages[pageIndex]);
                $eBook.canvas.append(pages.pages[pageIndex].html);
            } else {
                $eBook.createMap(pages.pages[pageIndex],pages.pages[pageIndex].html);
            }
            return pages.pages[pageIndex].html;
        };

        /**
         * Create a new page from page data
         */
        $eBook.createPage = function(pageData){
            var page = $('<div>').attr('id','page_'+pageData.number)
                        .addClass('page')
                        .css('width',$eBook.width)
                        .css('height',$eBook.height).hide();
            page.renderWidth=$eBook.width;
            page.renderHeight=$eBook.height;

            if(pageData.number == 1 || ((pageData.number%2)==0 && pageData.number==magazine.pages.length)){
                page.addClass('singlePage');
                page.css('left',$eBook.singlePage);
            } else if(pageData.number%2){
                page.addClass('rightPage');
                page.css('left',$eBook.rightPage);
            } else {
                page.addClass('leftPage');
                page.css('left',$eBook.leftPage);
            }
            var image = new Image();
            image.src = $eBook.getImage('page_image', pageData.page_id,pageData.image_filename);
            if(image.complete){
                page.append($(image).addClass('pageImage'));
            } else {
                page.append(
                    $('<img>').attr('src','images/loading.gif').addClass('loader')
                        .css('top', ($eBook.height-42)/2)
                        .css('left', ($eBook.width-42)/2)
                );
                image.onload = function(){
                    page.find('img.loader').remove();
                    page.append($(image).addClass('pageImage'));
                    image.onload = function(){};
                };
            }
            //Add handler for doubleclick zoom
            page.dblclick(function(e){
                $eBook.toggleDoubleSize();
                // Zoom in on the point of dblClick
                if ($eBook.isDoubleSize) {
                    var parent = e.currentTarget; // element listener attached to
                    var totalTopOffset = 0;
                    while (parent != null) {
                       var diff = parent.offsetTop;
                       if (diff > 0) {
                           totalTopOffset += parent.offsetTop;
                       }
                       parent = parent.parentNode;
                    }
                    // browser viewport (not the document)
                    var centrePoint = {x:$(window).width()/2,y:$(window).height()/2};
                    var clickPoint = {x:e.pageX,y:e.pageY};
                    var dx = (centrePoint.x - clickPoint.x);
                    // the click point has been scaled (minus the original topOffset)
                    var dy = (centrePoint.y - 2*(clickPoint.y-totalTopOffset)+totalTopOffset);
                    $eBook.lense.offset({top : dy-totalTopOffset, left: $eBook.lense.offset().left + dx});
                }
            });
            //Create element map for this page
            $eBook.createMap(pageData,page);
            return page;
        };

        /**
         * Zoom onto image canvas, doubling the size
         */
        $eBook.toggleDoubleSize = function(){
            $eBook.isDoubleSize=!$eBook.isDoubleSize;
            if($eBook.isDoubleSize){
                $eBook.lense.draggable();
                $eBook.navigator.hide();
                $eBook.find('.page').addClass('drag');
            } else {
                $eBook.lense.draggable('destroy');
                $eBook.navigator.show();
                $eBook.find('.page').removeClass('drag');
            }
            $eBook.updatePageSize();
        };

        /**
         * Create element map base on page data and append to page
         */
        $eBook.createMap = function(pageData, page){
            page.find('.element').remove();
            for(var x=0;x<pageData.elements.length;x++){
                if(pageData.elements[x].type!='link' && pageData.elements[x].type!='video' && pageData.elements[x].type!='image'){
                    continue;
                }
                page.append($eBook.createElement(pageData.elements[x]));
            }
            $eBook.doOnLoad(pageData.page_no);
            return page;
        };

        /**
         * Create a specific element, currently just for links :-s
         */
        $eBook.createElement = function(element){
            switch(element.type){
                case 'region':
                    return $eBook.createRegion(element);
                    break;
                case 'video':
                    return $eBook.createVideo(element);
                    break;
                case 'image':
                    return $eBook.createImage(element);
                    break;
            }
        };

        $eBook.createRegion = function(element){
            var $area = $('<div>').addClass('element')
                .addClass('region')
                .attr('id',element.element_id)
                .attr('title',element.tooltip);

            $area.css('top',Math.ceil(element.y*$eBook.sizeRatio));
            $area.css('left',Math.ceil(element.x*$eBook.sizeRatio));
            $area.width(element.w * $eBook.sizeRatio);
            $area.height(element.h * $eBook.sizeRatio);
            if(element.display !=1){
                $area.hide();
            }
            $area.activeElement(element);
            return $area;
        };

        $eBook.createImage = function(element){
            var $area = $('<img>').addClass('element')
                .addClass('image')
                .attr('id',element.element_id)
                .attr('src',apiUrl+ element.image_url+'.'+magazine.web_image_filetype);

            $area.css('top',Math.ceil(element.y*$eBook.sizeRatio));
            $area.css('left',Math.ceil(element.x*$eBook.sizeRatio));
            $area.width(element.w * $eBook.sizeRatio);
            $area.height(element.h * $eBook.sizeRatio);
            if(element.display !=1){
                $area.hide();
            }
            if(element.action_data.length>0){
                for(var x=0;x<element.action_data.length;x++){
                    // insert listners
                }
            }
            $area.activeElement(element);
            return $area;
        };

        $eBook.createVideo = function(element,pageData){
            var $element = $('<div>').addClass('element video')
                .attr('id',element.element_id);
            var $area = $('<div>').addClass('video-js-box');
            var $video = $('<video>').addClass('video-js')
                .attr('controls','controls')
                .attr('preload','auto')
                .attr('poster',apiUrl+element.image_url);

            for(var x=0;x<magazine.web_video_filetypes.length;x++){
                var $type = $('<source>').attr('src',apiUrl+element.media_url+'.'+magazine.web_video_filetypes[x].filetype)
                    .attr('type',magazine.web_video_filetypes[x].mime +'; codecs="'+magazine.web_video_filetypes[x].codecs+'"');
                $video.append($type);
            }

            var $fallBack = $('<p>').addClass('vjs-no-video').
                append(
                        $('<strong>').html('Download')
                );

            $video.attr('width',element.w * $eBook.sizeRatio);
            $video.attr('height',element.h * $eBook.sizeRatio);

            $area.append($video);
            $area.width(element.w * $eBook.sizeRatio);
            $area.height(element.h * $eBook.sizeRatio);
            
            $element.css('top',Math.ceil(element.y*$eBook.sizeRatio));
            $element.css('left',Math.ceil(element.x*$eBook.sizeRatio));

            $element.append($area);

            $element.width(element.w * $eBook.sizeRatio);
            $element.height(element.h * $eBook.sizeRatio);

            $area.find('video').VideoJS();
            if(element.display != 1){
                $element.hide();
            }
            if(element.action_data.length>0){
                for(var x=0;x<element.action_data.length;x++){
                    // insert listners
                }
            }
            $element.activeElement(element);
            return $element;
        };


        /**
         *Expand the thumbnail navigator
         */
        $eBook.showNavigator = function(){
            if(navTimeout!=null){
                clearTimeout(navTimeout);
            } 
            if(!navShown){
                navTimeout = setTimeout(function(){
                    $eBook.navigator.animate({top: '-=80',opacity:'0.9'});
                    navShown=true;
                },300);
            }
        };

        /**
         * Return the thumbnail navigator to initial position
         */
        $eBook.hideNavigator = function(){
            if(navTimeout!=null){http://magazine-api.aptusinteractive.com/api/resource/e048366c-bd97-47e3-8ee1-437034ee8c62/page_thumbnail/undefined.jpg
                clearTimeout(navTimeout);
            } 
            if(navShown){
                navTimeout = setTimeout(function(){
                        $eBook.navigator.animate({top: '+=80',opacity: '0.5'});
                        navShown=false;
                },300);
            }
        };

        /**
         * Load thumbs from magazine into thumbnail navigator
         */
        $eBook.loadThumbs = function(){
            $.each(magazine.pages,function(i,page){
                var thumb = $('<img>').attr('src',$eBook.getImage('page_thumbnail',page.page_id,page.thumbnail))
                    .addClass('thumb').click(
                            function(){
                                $eBook.goToPage(page.number);
                            });

                if(page.number==1 || ((page.number%2)==0 && page.number==magazine.pages.length)){
                    thumb.addClass('singleThumb');
                } else if(page.number%2){
                    thumb.addClass('rightThumb');
                } else {
                    thumb.addClass('leftThumb');
                }
                var thumbWrapper = $('<div>');
                 thumbWrapper.addClass('thumbWrapper');
                 thumbWrapper.append(thumb);
                $eBook.overview.append(thumbWrapper);
            });
            //This isn't working:
            //$('#scrollbar1').tinyscrollbar({ axis: 'x'});
        };

        /**
         * Bulid an image url
         */
        $eBook.getImage = function(type,uid,name){
        // live magazine api can't serve jpgs yet
            var url = apiUrl+'api/resource/'+uid+'/'+type+'/'+name + '.'+magazine.web_image_filetype;
            
            return url;
        };

        $eBook.init();
    });
 };
 
})(jQuery);

(function($){
    $.fn.activeElement = function(data) {
       
       return this.each(function() {
           var $element = $(this);

           /* Setup the reader*/
           $element.init = function(){
               this.data = data;
               this.bind('runactions',function(e){
                   $element.runAction(e);
               });
               if(this.data.on_click.length>0){
                   this.click(function(){
                       $element.runClickActions();
                   });
                   this.addClass('active');
               }
               this.css('z-index',this.data.z_index);
               if(this.data.opacity<100){
                   this.css('opacity',this.data.opacity/100);
               }
           };

           $element.runAction = function(e){
               e.preventDefault();
               var action=false;

               for(var x=0; x<this.data.action_data.length;x++){
                   if(data.action_data[x].id == e.action_data_id){
                       action = data.action_data[x]; 
                       break;
                   }
               }
               if(action!=false){
                   switch(action.type){
                       case 'HIDE':
                           this.hide();
                           break;
                       case 'SHOW':
                           this.show();
                           break;
                       case 'OPEN_URL':
                       case 'OPEN_MAIL':
                           window.open(action.url,'_blank');
                           break;
                       case 'ANIMATE':
                           this.animateElement(action,this.data);
                           break;
                       case 'LOAD':
                           this.loadElement(action,this.data);
                           break;
                       case 'PLAY':
                           var video = this.find('.video-js').get(0).play();
                   }
               }
           };

           $element.doAnimation = function(action){

           };

           $element.runClickActions = function(){
               for(var x=0;x<data.on_click.length;x++){
                   var e = new jQuery.Event('runactions');
                   e.action_data_id=data.on_click[x].action_data_id;
                   $('#'+data.on_click[x].element_id).triggerHandler(e);
               }
           };

           $element.init();
       });
    };
    
   })(jQuery);

(function($){
    $.fn.animateElement = function(animation,data) {
       
       return this.each(function(){
           var $element = $(this);
           var $animation = animation;
           var $data = data;
           var count = 0;

           /* Setup the reader*/
           $animation.init = function(){
               if(this.delay>0){
                   var t = setTimeout(function(){
                       $animation.animate();
                   },$animation.delay);
                   stackTimeout(t);
               } else {
                   $animation.animate();
               }
           };

           $animation.animate = function(){
               count++;
               var props = {};
               if($animation.x != null && $animation.y != null){
                   if($animation.direction == 'NORMAL' || count%2==1){
                       props.left = $animation.x * currentRatio;
                       props.top = $animation.y * currentRatio;
                   } else {
                       props.left = $data.x * currentRatio;
                       props.top = $data.y * currentRatio;
                   }
               }
               if($animation.w!= null && $animation.h!= null){
                   if($animation.direction == 'NORMAL' || count%2==1){
                       props.width = $animation.w * currentRatio;
                       props.height = $animation.h * currentRatio;
                   } else {
                       props.width = $data.w * currentRatio;
                       props.height = $data.h * currentRatio;
                   }
               }
               if($animation.opacity!= null){
                   props.opacity = $animation.opacity/100;
               }
               
               var easing;
               switch($animation.easing_function){
               case 'EASE_OUT':
                   easing = 'easeOutQuad';
                   break;
               case 'EASE_IN':
                   easing = 'easeInQuad';
                   break;
               case 'EASE_IN_OUT':
                   easing = 'easeInOutQuad';
                   break;
               default:
                   easing = 'linear';
               }
               $element.animate(props,$animation.duration,easing,function(){
                   $animation.complete();
               });
           };

           $animation.complete = function(){
               if($animation.on_finish.length>0){
                   for(var x=0;x<$animation.on_finish.length;x++){
                       var e = new jQuery.Event('runactions');
                       e.action_data_id=$animation.on_finish[x].action_data_id;
                       $('#'+$animation.on_finish[x].element_id).triggerHandler(e);
                   }
               }

               if($animation.play_count > count || $animation.play_count == -1 ){
                   $animation.init();
               }
           };

           $animation.init();
       });
    };
})(jQuery);

(function($){
    $.fn.loadElement = function(load,data) {
       
       return this.each(function(){
           var $element = $(this);
           var $load = load;
           var $data = data;
           /* Setup the reader*/
           $load.init = function(){
               $element.show();
               this.data = data;
               if(this.data.type=='video'){
                   this.loadVideo();
               }
               this.complete();
           };

           $load.loadVideo = function(){
               $element.find('source').each(function(i,e){
                   $(e).attr('src',$(e).attr('src').replace($data.media_url,$load.media_url));
               });
               $element.find('.vjs-poster').each(function(i,e){
                   $(e).attr('src',$(e).attr('src').replace($data.image_url,$load.image_url));
               });
           };

           $load.complete = function(){
               if($load.on_finish.length>0){
                   for(var x=0;x<$load.on_finish.length;x++){
                       var e = new jQuery.Event('runactions');
                       e.action_data_id=$load.on_finish[x].action_data_id;
                       $('#'+$load.on_finish[x].element_id).triggerHandler(e);
                   }
               }
           };

           $load.init();
       });
    };
})(jQuery);

function stackTimeout(timeout){
    timeouts.push(timeout);
}
function clearTimeouts(){
    while(timeouts.length>0){
        clearTimeouts(timeouts.pop());
    }
}
$(document).ready(function() {
    //setup the reader! Assuming the ebook is defined within the body of the html page
    if(ebook.data.length>0){
        // Only designed to have one book per page at the moment, this could change I guess!
        $('#aptusReader').aptusReader(ebook.data[0]);
    }
});
