Buy
Bookshop
SEO. Introducción a la disciplina del posicionamiento en buscadores
AnonymousUser

Index

  • SEO. Introducción a la disciplina del posicionamiento en buscadores

  • (1)
  • (2)
  • (3)
  • (4)
  • (5)
  • Presentación
  • Introducción al SEO
  • Introducción al SEO
  •     1. SEO y marketing digital
  •     2. ¿Cómo funciona un buscador?
  •     3. El mercado de los buscadores: ¿solo Google?
  •     4. Metodología SEO: estrategia frente a táctica
  • Keyword & Context Research: análisis de palabras clave y del contexto SEO
  • Keyword & Context Research: análisis de palabras clave y del contexto SEO
  •     1. Cómo buscan los usuarios
  •     2. Consejos para elegir una palabra clave a posicionar
  •     3. Diseño desde cero
  •     4. Rediseño de sitio web ya existente
  • SEO On Site: técnicas dentro del sitio web
  • SEO On Site: técnicas dentro del sitio web
  •     1. Indexabilidad
  •     2. Redirecciones
  •     3. Web Performance Optimization (rapidez de carga)
  •     4. Dominio y URL
  •     5. Internacionalización SEO
  •     6. URL «amigables», carpetas y subdominios
  •     7. Accesibilidad, estándares web y responsive design
  •     8. Usabilidad y experiencia de usuario
  •     9. Arquitectura de información
  •     10. Contenido duplicado
  •     11. Etiqueta </a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    12. Etiquetas H1, H2 y énfasis en palabras clave</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    13. Optimización de imágenes y vídeos</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    14. Estructura y características del texto</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    15. Densidad o repeticiones de palabra clave dentro de un texto</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    16. Knowledge Graph Optimization (web semántica)</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    17. Metadatos y microdatos</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    18. Identificación de autoría</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    19. A evitar (factores negativos)</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#"> SEO Off Site: técnicas fuera del sitio web</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#"> SEO Off Site: técnicas fuera del sitio web</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    1. Marketing de contenidos</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    2. Social Media Marketing</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    3. Factores de calidad en enlaces desde otros sitios web</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    4. Link building: cómo conseguir enlaces</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    5. Link baiting: conseguir enlaces rápidamente</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#"> Analítica web para SEO</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#"> Analítica web para SEO</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    1. Palabras clave por las que se obtiene tráfico frente a no se obtiene tráfico</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    2. Posiciones para palabras clave de interés</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    3. Tráfico debido a SEO frente a resto de tráfico</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    4. Análisis del mercado SEO</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    5. Links desde otras webs frente a competencia</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    6. Páginas de sitio web propio con más links entrantes</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    7. Páginas con más conversiones</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    8. Qué contenido genera más «social signals» y links sociales</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    9. Grado de correlación entre métricas</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#">    10. La medida de todas las cosas: la rentabilidad SEO</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#"> Epílogo</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#"> Bibliografía</a></li> <!-- conditions to make the links not visible when the view percentage should not allow it --> <li class="toc_li"><a class="toc_a toc_disabled" href="#"> Glosario</a></li> </ul> </div> </div> </div> <!-- You can also use articles in submenu, they will automatically align to the right or use class .perex to align left --> <!-- <article> <h2>Header H2</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse et dignissim metus. Maecenas id augue ac metus tempus aliquam.</p> </article> --> </div> <!-- /Sub Nav Block #submenu-2 --> <!-- BUSCAR INSERTAR AQUÍ LA BÚSQUEDA--> <div id="submenu-2" class="submenu"> <ul class="thumbnail-list menu-fit"> <li> <div id="search_box"> <!--<h1>Search</h1>--> <form id="frmsearch" method="post" action="/search/"><div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='a9391c6945f1c3a6872df0c5a823e34f' /></div> <input type="hidden" name="id_book" id="id_book" value="41034" /> <input type="hidden" name="id_chapter" id="id_chapter" value="https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-3.html" /> <input type="text" name="search_text" id="search_text" value="" placeholder="Search"/> <span class="glyphicon icon icon-search"></span> <br /><br /> <span id="search_this_book">In this book:</span> <input type="checkbox" name="search_content" id="search_content" class="marginleft" checked="checked" value="yes" /> Content of the Book<br /> <input type="checkbox" name="search_notes" id="search_notes" class="marginleft" checked="checked" value="yes" /> My notes<br /> <input type="checkbox" name="search_highlights" id="search_highlights" class="marginleft" checked="checked" value="yes" /> My highlights<br /> </form> </div> <br /> <div id="search_results"></div> <div class="clearboth"></div> <script type="text/javascript"> $("#frmsearch .icon-search").click(function () { if ($("#search_text").val().length > 0 ) { $("#frmsearch").submit(); } }); </script></li> </ul> </div> <!-- Sub Nav Block #submenu-3 --> <div id="submenu-3" class="submenu"> <h2 class="reader_submenu_heading" >Settings<h2> <ul class="thumbnail-list menu-fit"> <li class="reader_submenu"> <span class="submenu_conf_title">Font:</span> <select id="font_select" name="font"> <option value="0">- Original Font -</option> <option value="arial">Arial</option> <option value="courier">Courier</option> <option value="georgia">Georgia</option> <option value="palatino">Palatino</option> <option value="SansForgetica">Sans Forgetica</option> <option value="tahoma">Tahoma</option> <option value="times">Times New Roman</option> <option value="verdana">Verdana</option> </select> </li> <li class="reader_submenu"> <div class="submenu_conf_title"> <span>Text size:</span> </div> <div class="sangria margin_top"> <span id="decrease_span"><strong>Aa</strong></span>  <!-- <a href="#" class="decreaseFont"><img class="clean_img" src="/media/img/reader/menu/botonmenos.png" alt="" class="thumb" /></a>  <a href="#" class="increaseFont"><img class="clean_img" src="/media/img/reader/menu/botonmas.png" alt="" class="thumb" /></a>  --> <span id="slider_text_size"></span> <span id="increase_span"><strong>Aa</strong></span><br /> <a href="#" class="resetFont"><span class="glyphicon icon icon-reload"></span>Reset text size</a><br /> </div> </li> <li class="reader_submenu"> <div class="submenu_conf_title br"> <span>Background color:</span> </div> <div class="sangria"> <a href="#" class="colorMode dayMode">Aa</a> <a href="#" class="colorMode greyMode">Aa</a> <a href="#" class="colorMode sepiaMode">Aa</a> <a href="#" class="colorMode nightMode">Aa</a> <br /> </div> </li> <li> <div class="submenu_conf_title br"> <span>Interface language:</span> </div> <div class="sangria"> <form class="language" action="/i18n/setlang/" method="post"> <div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='a9391c6945f1c3a6872df0c5a823e34f' /></div> <select id="language_select" name="language"> <option value="en" selected="selected" >English (US)</option> <option value="en_GB" >English (UK)</option> <option value="es" >Español</option> <option value="ca" >Català</option> </select> <input id="language_button" type="submit" value="Change language" /> </form> </div> </li> </ul> <!-- <ul class="thumbnail-list menu-fit"> <li class="thumbnail-list-header"><h2>Image Content</h2></li> <li> <img src="/img/_sample-data/sample_image_1.png" alt="Sample Image"> <h3>Some image examples</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse et dignissim metus.</p> <a class="thumbnail-list-more">Read more »</a> </li> <li> <img src="/img/_sample-data/sample_image_2.png" alt="Sample Image"> <h3>One more example</h3> <p>Sed pharetra placerat est suscipit sagittis. Phasellus aliquam malesuada blandit.</p> <a class="thumbnail-list-more">Read more »</a> </li> </ul> <article> <h2>Header H2</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse et dignissim metus. Maecenas id augue ac metus tempus aliquam.</p> </article> --> </div> <!-- /Sub Nav Block #submenu-3 --> <!-- Sub Nav Block #submenu-4 --> <div id="submenu-4" class="submenu"> <div class="container"> <div id="scroll-pane-marks"> <div class="submenu_title"> <span class="glyphicon icon icon-bookmark"></span> <span>Bookmarks</span> </div> <ul> </ul> <div class="submenu_title br"> <span class="glyphicon icon icon-pen"></span> <span>Highlights</span> </div> <ul> </ul> <div class="submenu_title br"> <span class="glyphicon icon icon-note"></span> <span>Notes</span> </div> <ul> </ul> </div> </div> <!-- Sub Nav Form --> <!-- /Sub Nav Form --> <!-- <ul class="thumbnail-list menu-fit"> <li><article> <h2>Comparte: Tu opinión importa</h2> <p>Puedes compartir tus textos subrayados, comentarios, calificación de libros, en nuestra red social... </p> <h3>Comunica: Tus aportaciones cuentan</h3> <p>Puedes enviar tus comentarios, notras, textos, calificaciones en las principales redes sociales...</p> </article></li> </ul> --> <!-- Social Sub Nav List Style --> <!-- <ul class="social-list"> <li><a class="social rss" href="#">RSS</a></li> <li><a class="social twitter" href="#">Twitter</a></li> <li><a class="social facebook" href="#">Facebook</a></li> <li><a class="social forrst" href="#">QuieroLeer</a></li> </ul> --> <!-- /Social Sub Nav List Style --> </div> <!-- /Sub Nav Block #submenu-4 --> </nav> <!-- Main Content --> <section role="main" class="main-wrapper"> <section class="fullscreen-wrapper"> <!-- Context menu --> <ul id="ctxMenu" class="contextMenu"> <img src="/media/img/triangle.png" style="position: relative; top: -17px; left: 43px;" ></img> <!-- <li class="ctxHighlight"><a href="#ctxHighlight">Highlight</a></li> <li class="ctxNote"><a href="#ctxNote">Insert note</a></li>--> <li class="ctxFacebook"><a href="#ctxFacebook">Facebook</a></li> <li class="ctxTwitter"><a href="#ctxTwitter">Twitter</a></li> <li class="ctxLinkedin"><a href="#ctxLinkedin">LinkedIn</a></li> <li class="ctxDictionary separator"><a href="#ctxDictionary">Dictionary</a></li> <li class="ctxWikipedia"><a href="#ctxWikipedia">Wikipedia</a></li> </ul> <p id="newNoteP"> <span id="newNote"></span> </p> <!--<a id="fullscreen" href="#" title="Full Screen" class="icon" style="display:none;"><span class="icon icon_modern">v</span></a>--> <section class="page-wrapper"> <!-- Dashboard --> <section id="dashboard"> <h1></h1> <!-- Ponemos el Iframe del lector --> <div> <a class="arrow_b arrow prevpage" href="#"><span class="glyphicon icon icon-left"></span></a> <div id="iframe_container" style="visibility:hidden"> <!--<img class="bookmark_icon" src="/media/img/reader/icons/buttons/bookmark.png" alt="Mark" title="Mark" ></img>--> <iframe id="book_ifr" src="about:blank"></iframe> <!-- Breadcumbs --> <div id="breadcrumbs"> <div class="pagination_progress"></div> <div class="pagination_bottom"> <div class="pagination_left"> <div id="progressBar" class="bar_mortice mortice_tiny rounded"> <div class="progress progress_tiny rounded" ></div> </div> <span class="pagenumber">1</span> </div> <div class="pagination_right"> <b>SEO. Introducción a la disciplina del posicionamiento en buscadores</b> · (5) </div> </div> </div> <!-- /Breadcumbs --> </div> <a class="arrow_f arrow nextpage" href="#"><span class="glyphicon icon icon-right"></span></a> <div class="clearboth"></div> </div> <div class="clearboth"></div> <script src="/media/js/reader/jquery-1.7.1.min.js"></script> <script type="text/javascript" src="/media/js/jquery-ui-1.8.18.custom.min.js"></script> <!-- <script src="/media/js/reader/jquery.contextMenu.js"></script> <script src="/media/js/reader/jquery.highlight-3.js"></script> <script src="/media/js/reader/jquery.scrollTo-1.4.2-min.js"></script> <script type="text/javascript" src="/media/js/reader/jquery.qtip-1.0.0-rc3.min.js"></script> <script type="text/javascript" src="/media/js/reader/dohighlight.js"></script> --> <script type="text/javascript" src="/media/js/reader/textselection.js"></script> <!-- <script type="text/javascript" src="/media/js/reader/internationalization.js"></script> <script type="text/javascript" src="/media/js/reader/positioning.js"></script> <script type="text/javascript" src="/media/js/reader/display_modes.js"></script> <script type="text/javascript" src="/media/js/reader/marks_manipulation.js"></script> <script type="text/javascript" src="/media/js/reader/nodeselector.js"></script> <script src="/media/js/jquery.jscrollpane.min.js"></script> <script src="/media/js/reader/jquery.fullscreen.js"></script> --> <script type="text/javascript" src="/media/js/reader/minified_js_book/all_js_book.js"></script> <script type="text/javascript" src="/media/js/reader/charscount.js"></script> <script type="text/javascript" language="javascript"> (function($) { $.fn.outerHTML = function(s) { return (s) ? this.before(s).remove() : $('<p>').append(this.eq(0).clone()).html(); } })(jQuery); var timeoutStart=false; var timeoutVar; var active_overlay = false; var evento; var t; // Function startsWith definition String.prototype.startsWith = function(str) {return (this.match("^"+str)==str)} var lan = {}; var marcas; switch("es"){ case 'en': lan = languages.en; break; case 'es': lan = languages.es; break; case 'ca': lan = languages.ca; break; default: lan = languages.es; } var buy_div_content = '<div class="buyDiv"><p>If you would like to continue reading this book, you can purchase it at your bookshop.</p><p>Además, dispondrá de nuevas funcionalidades: resaltar textos, añadir notas, buscar entre sus contenidos y muchas más.</p><br><div><a class="buyLink" >Buy</a></div></div>'; function textUntilLength($element, doc) { var T = '#~~~#'; var $marquer = $('<span style="display:none">'+T+'</span>'); $marquer.insertBefore($element); var text = $(doc.body).text().split(T)[0]; $marquer.remove(); return text.length; } if (!document.getElementById('book_ifr').contentWindow.NodeList.prototype.filter){ // NodeList.prototype.filter = function(fun /*, thisp*/) document.getElementById('book_ifr').contentWindow.NodeList.prototype.filter = function(fun /*, thisp*/){ var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; // in case fun mutates this if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; } beginsWith = function(needle, haystack){ if(haystack.substr(0, needle.length) == needle){ return true; } return false; } if (!NodeList.prototype.filter){ NodeList.prototype.filter = function(fun /*, thisp*/){ var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; // in case fun mutates this if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; } /* if (!top.NodeList.prototype.filter){ top.NodeList.prototype.filter = function(fun){ var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; // in case fun mutates this if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; }*/ function filterByClass(element, index, arra){ return (element.className != 'highlight'); } // ==================== Hidding unwanted icons =============================== // to hide the next page icon if there is no next page. Same with previous page /* function pageIcoShow(){ var nextchapter = "x9788490649626EPUB-4"; var prevchapter = "x9788490649626EPUB-2"; if (nextchapter == ""){ $('.nextpage').css('visibility','hidden'); } if (prevchapter == ""){ $('.prevpage').css('visibility','hidden'); } } */ function pageIcoShow(currentPage, numPages){ var nextchapter = "x9788490649626EPUB-4"; var prevchapter = "x9788490649626EPUB-2"; if (nextchapter == "" && currentPage == numPages) { $('.nextpage').css('visibility','hidden'); } else { $('.nextpage').css('visibility','visible'); } if (prevchapter == "" && currentPage == 1) { $('.prevpage').css('visibility','hidden'); } else { $('.prevpage').css('visibility','visible'); } } // ========================================= Count read percent ====================================================== function callCountPage(iframe){ // If there is a timeout started, we need to stop that //console.log("timeout canceled"); clearTimeout(timeoutVar); // Start timeout anew //console.log("timeout started"); timeoutVar=setTimeout(function(){getBoundsPage2(iframe,"41034","x9788490649626EPUB-3","");},6000); timeoutStart=true; } function in_range(offsetLeft, elementLeft, page_width){ current_page = parseInt(1 + offsetLeft / page_width); if ((elementLeft <= offsetLeft + page_width-1) && (elementLeft >= offsetLeft)){ return true; }else{ return false;} } // Returns a node from the coords. Coords used for the suscribooks reader api function getNodeFromCoordsBS(coord){ var levels = coord.split(">"); var l; var doc = document.getElementById('book_ifr').contentDocument; //var doc = document.documentElement; var current_node = doc; // This may not be needed once in the streamer!!! // Its because the first 0000000 is already the document.documentElement // But this may be different when getting 'book_ifr' /* if (levels[0]=='0000000') { levels = levels.slice(1,levels.length); }*/ for(pos in levels){ l = parseInt(levels[pos], 10); /* console.log("POS_search: ",l); console.log("nodo_act: ",current_node);*/ siblings = current_node.childNodes; real_cont=-1; // We start at -1 to "add" every node that is not useless for (var i=0; i< siblings.length;i++){ if ((siblings[i].nodeType == 3 && node_useful(siblings[i])) || siblings[i].nodeType != 3){ real_cont +=1; } // If this is the one we were told is the good one, no need to keep going if (real_cont == l){ current_node = siblings[i] break; } } } /* console.log("coords: ",coord); console.log("NO-DO: ",current_node);*/ return current_node; } // Get coords for a node (specific coords for the suscribooks reader api) function getCoordFromNodeInTotal(node){ // Number of 0's SEL_LEN = 7; var treePos = Array(); // Position first level var position = getCoordFromNodeInSiblings(node); treePos.push(zeroFill(position, SEL_LEN)); // Position for each level above him $(node).parents().each(function() { var position = getCoordFromNodeInSiblings(this); treePos.push(zeroFill(position, SEL_LEN)); }); // Transform to coords style: 0000001>0000000>000.. treePos.reverse(); var stringCoords = treePos.join('>'); /* console.log("Nodo: ",node); console.log("RES FINAL: ", stringCoords);*/ return stringCoords; } // Get coords for a node among his siblings (specific coords for the suscribooks reader api) function getCoordFromNodeInSiblings(node){ var selfParentes = Array(); // Posible brothers of node var childNodesSelf = node.parentNode.childNodes; // Position of node in his siblings list var contPrevSiblings = 0; // Check if there is more brothers than himself var len = childNodesSelf.length; if (len > 1){ // = .haschildNodes() // Iterate through all the brothers for (var i = 0; i < len; i++) { // If the node we want to know the coords about is the first, no need to go further if (node != childNodesSelf[i]){ // This are the ones we need to see if we count them or not: text nodes with \n,\n\n, ' ',... if (childNodesSelf[i].nodeType == 3){ // If its a text node, we need to know if the text is meaningful if (node_useful(childNodesSelf[i])){contPrevSiblings +=1} }else{ // if the nodeType is not Text, we count it for sure contPrevSiblings+=1; } }else{ // If the node we are in is OUR node break; } } } return contPrevSiblings; } // Know if a text node has meaningful text or if its just a newline/space function node_useful(node){ // Replace newlines && spaces textToCheck = node.nodeValue.replace(/\r\n|\n|\r|\s/g,''); if (textToCheck !='' && textToCheck !='\n' && textToCheck != ' '){ return true; }else{ return false; } } // Just fill the coords to match width with 0's function zeroFill(number, width) { width -= number.toString().length; if ( width > 0 ) { return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number; } return number; } RegExp.escape_orig = function(s) { return String(s).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1'). replace(/\x08/g, '\\x08'); }; //Escape special chars RegExp.escape = function(s) { return String(s).replace(/([-()¡«»\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1'). replace(/\x08/g, '\\x08'); }; // Wrap the text of "text" in a span if its found in the node "container" function wrapText(container, text, text2) { // Construct a regular expression that matches text at the start or end of a string or surrounded by non-word characters. // Escape any special regex characters in text. var textRE = new RegExp(RegExp.escape(text)); var textRE2 = new RegExp(RegExp.escape(text2)); var nodeText; var nodeStack = []; // Remove empty text nodes and combine adjacent text nodes. container.normalize(); // Iterate through the container's child elements, looking for text nodes. var curNode = container.firstChild; while (curNode != null) { if (curNode.nodeType == Node.TEXT_NODE) { // Get node text in a cross-browser compatible fashion. if (typeof curNode.textContent == 'string') nodeText = curNode.textContent; else nodeText = curNode.innerText; // Use a regular expression to check if this text node contains the target text. var match = textRE.exec(nodeText);// Determine if an element is "visible" // Used for the top case if left == true, for the bottom node if left==false function isElementInCurrentPage(el, first, page_width) { var rect = el.getBoundingClientRect(); //nn.getClientRects() /* var wid = $(el).width(); console.log("WIDTHELEMENT ", wid);*/ if (first==true){ // Case: first node of the page if (rect.left < 0){ return true; }else{ return false;} }else{ // Case: last node of the page // Log /* console.log(" TIPO ", first); console.log("elemento: ", el); console.log("TEXTEL: ", $(el).text()); console.log("bottom ", rect.bottom); console.log("right ", rect.right); console.log("left ", rect.left); console.log("top ", rect.top);*/ if((rect.right >= page_width-1) || (rect.left>=page_width-1)){ // rec.right < page_width return false; }else{ return true;} } } function go_deeper(current, page_width) { var children = current.childNodes; for (var i = 0, len = children.length; i < len-1; i++) { var xy_pos = children[i].getBoundingClientRect(); if (xy_pos.left > page_width){ console.log("coord last subchildren ",getCoordFromNodeInTotal(children[i])); break; } go_deeper(children[i], page_width); } } var match2 = textRE2.exec(nodeText); if (match != null) { // Create a document fragment to hold the new nodes. var fragment = document.createDocumentFragment(); /* console.log("match: ",match); console.log("MATTCH INDEX ", match.index); console.log("MATTCH INDEX ", match.lastIndex); console.log("match22: ",match2); console.log(" next macth IN",match2.index); console.log("MATTCH INDEX ", match2.lastIndex);*/ // Create a new text node for any preceding text. if (match.index > 0) fragment.appendChild(document.createTextNode(match.input.substr(0, match.index))); // Create the wrapper span and add the matched text to it. var spanNode = document.createElement('span_check'); spanNode.appendChild(document.createTextNode(match[0])); fragment.appendChild(spanNode); // Create a new text node for any following text. if (match.index + match[0].length < match.input.length) fragment.appendChild(document.createTextNode(match.input.substr(match.index + match[0].length))); // Replace the existing text node with the fragment. curNode.parentNode.replaceChild(fragment, curNode); curNode = spanNode; } } else if (curNode.nodeType == Node.ELEMENT_NODE && curNode.firstChild != null) { nodeStack.push(curNode); curNode = curNode.firstChild; // Skip the normal node advancement code. continue; } // If there's no more siblings at this level, pop back up the stack until we find one. while (curNode != null && curNode.nextSibling == null) curNode = nodeStack.pop(); // If curNode is null, that means we've completed our scan of the DOM tree. // If not, we need to advance to the next sibling. if (curNode != null) curNode = curNode.nextSibling; } } // Searches the last word that is visible in the page for a node that is the "last" in the page function lastInoffset(node, page_width){ // Temporal node to restore it later var backup_node = $(node).html() // Words from that node var chars_nc = $(node).text(); chars_nc = chars_nc.split(" "); var arrWords = chars_nc; var num = chars_nc.length; function check_mid_node(init, fin){ var mid = ((fin-init)/2) | 0; while (chars_nc[mid].length<=3){ mid++; } console.log("init ",init) console.log("fin ",fin); console.log("mid: ", mid); console.log("elmid ",chars_nc[mid]); console.log("textelmid ", $(chars_nc[mid]).text()); wrapText(node, chars_nc[mid], chars_nc[mid+1] ); spian= $(node).children().children('span_check'); var keep_going = isElementInCurrentPage(spian[0], false, page_width); console.log("MID: ", keep_going); console.log("MID TEXT", $(spian[0]).text()); if (keep_going){ return [true, mid,fin]; }else{ return [false,init,mid]; } } var continue_= true; var new_init = 0; var new_fin = num; data = check_mid_node(new_init,new_fin); continue_ = data[0]; new_init = data[1]; new_fin= data[2]; while (continue_){ console.log("going ahead"); data = check_mid_node(new_init,new_fin); continue_ = data[0]; new_init = data[1]; new_fin= data[2]; if(!continue_){ while (!continue_){ console.log("going back"); data = check_mid_node(new_init,new_fin); continue_ = data[0]; new_init = data[1]; new_fin= data[2]; } break; } } console.log("last init: ", new_init); console.log("last fin: ", new_fin); console.log("last fintxt: ", $(chars_nc[new_fin]).text()); $(node).html(backup_node); } function binarySearchLastWordNode(node, page_width){ /* dat= node.getClientRects() console.log("NEWDATA ",dat);*/ // Temporal node to restore it later var backup_node = $(node).html(); // Words from that node var chars_nc = $(node).text(); chars_nc = chars_nc.split(" "); var arrWords = chars_nc; var start = 0; var end = chars_nc.length-1; console.log("START ",start); console.log("END ",end); var iter=0; while ((start<end) && iter<6){ iter++; //var mid = parseInt((start + end)/2); var mid = ((end+start)/2) | 0; while(chars_nc[mid].length <4){ mid++; } wrapText(node, chars_nc[mid], chars_nc[mid+1]); var spian= $(node).children().children('span_check'); var keep_going = isElementInCurrentPage(spian[0], false, page_width); if (keep_going) { start=mid; console.log("advanced");} else{ end=mid-1; console.log("going back");} console.log("MID TEXT", $(spian[0]).text()); console.log("start- ",start); console.log("end- ",end); $(node).html(backup_node); } //return chars_nc.length; console.log("-----START---- ",start); console.log("-----END---- ",end); $(node).html(backup_node); } function binarySearch(arr, key){ var left = 0; var right = arr.length - 1; while (left <= right){ var mid = parseInt((left + right)/2); if (arr[mid] == key) return mid; else if (arr[mid] < key) left = mid + 1; else right = mid - 1; } return arr.length; } function lenghtTillPos(arr,pos){ var total=0; for (i=0; i<pos;i++){ total=arr[i].length +1; } return total; } // This function will count only the visible chars of a node wich is not completely visible in the page // first determines if its checking the first node of the page or the last one (for coordsY purposes) function visibleCharsNodePage(node, first, page_width){ try{ // Temporal node to restore it later var backup_node = $(node).html() // Words from that node var chars_nc = $(node).text(); chars_nc = chars_nc.split(" "); var arrWords = chars_nc; var num = chars_nc.length; /* if (first == false){ mid = (num /2) | 0; console.log("num ",num); console.log("mid: ", mid); wrapText(node, chars_nc[mid]); spian= $(node).children().children('span_check'); console.log("MID: ", isElementInCurrentPage(spian[0], first, page_width)); console.log("MID TEXT", $(spian[0]).text()); }*/ if(first == false){ //check_last_node(node, page_width); binarySearchLastWordNode(node, page_width); console.log("after"); return -2; } // Wrap every word of the first node with a span for(var i=0;i<num;i++){ if (chars_nc[i].length >3){ // avoid really small words //console.log("while 1"); wrapText(node, chars_nc[i]); } } var visible_chars = 0; // check every of those spans to see if its visible in the current page var spanners = $(node).children().children('span_check'); // Log /* console.log("spanners: ",spanners); console.log("num spans ",num); console.log("chars_nc: ",chars_nc);*/ var last_word = spanners.length-1; for (i = 0; i<last_word; i++){ //console.log("while 2"); // sometimes spanners[i] is undefined, prolly because of the first== false MID if i have temporarily upwards //if (!spanners[i]){continue;} if (isElementInCurrentPage(spanners[i],first, page_width)== false){ // If its not visible, get out break; }else{ //this_chars = $(spanners[i]).text().length; visible_chars=lenghtTillPos(arrWords,i); // THIS SHOULD BE DONE IN ANOTHER LOOP ADDING ALL UNTILL THE LAST I -> line above /* if (arrWords[i]){ this_chars = arrWords[i].length; visible_chars += this_chars+1; // +1 to make up for the space between words } */ } } // Put the original node back in (we dont want the spanned one to remain) $(node).html(backup_node); return visible_chars; }catch(err){console.log("error visible ",err.message);$(node).html(backup_node);} } function vis(node,name,first){ console.log("NODO_: ",name); console.log("nodo: ",node); dat= node.getClientRects(); console.log("NEWDATA ",dat); console.log("VISIBLE ", dat[0].height); if (dat[1]){ console.log("novisible ",dat[1].height); }else{ console.log("no dat 1");} chars = $(node).text(); numchars = chars.length; if (!first && dat[1]){ tot_node= (dat[0].height+dat[1].height) vis_percent= (dat[1].height*100)/tot_node; console.log("vis percent last",vis_percent); console.log("chars vis: ", parseInt(numchars*(vis_percent/100))) }else if(dat[1]){ tot_node= (dat[0].height+dat[1].height) vis_percent= (dat[0].height*100)/tot_node; console.log("vis percent prim",vis_percent); console.log("chars vis: ", parseInt(numchars*(vis_percent/100))) } } // In this function we get the first node of the currently visible page of the reader and the last node. // If the first node and/or last node are not completely on the visible page, we count how many chars are visible of those nodes function getBoundsPage(iframe){ var Coords_firstN = 0; var Coords_lastN = 0; var chars_firstN = 0; var chars_lastN = 0; var pos_left = iframe.scrollLeft(); // First node that is completely on the page try{ console.log("gbp1"); var first_node = getFirstNodeOfPage(iframe.find('body'), pos_left); var first_children = $(iframe).find('body').children().not('.highlight').not('.notesmark').not('br');//.not('img'); var page_width = $(iframe).find('body').width(); // Some books need this while (first_children.length ==1){ first_children = $(first_children).children().not('.highlight').not('.notesmark').not('br');//.not('img'); } console.log("long children ", first_children.length); // To avoid iterating through all, we look from where we need to iterate index_first_children = first_children.index(first_node); console.log("index first ch ", index_first_children); console.log("nodo first ch ", first_children[index_first_children]); //console.log("first ch ALL ",first_children); console.log("gbp2"); // First node is NOT a direct son of the chapter if (index_first_children == -1){ real_index = 0; }else{ // First node IS a direct son of the chapter real_index = index_first_children; } }catch(error){ console.log("error 0 ",error.message);} console.log("gbp3"); var first = true; var last_index = 0; var first_index = 0; try{ // Iterate through all the elements: // Here we get the real index, regardles of it being 0 at this point for (var i=real_index;i< first_children.length-1;i++){ if (in_range(pos_left, first_children[i].offsetLeft, page_width)){ // its in the column we want if (first==true){ first_index = i; first = false; } // es el last index el que tiene error?? last_index = i; //console.log("III ",i) } else if (first!=true){ // As soon as we are no longer in the page but we already got the nodes of the page break; } } console.log("gbp4"); }catch(error){ console.log("error 1 ",error.message);} // Node that is the last of the previous page and may have some lines in OUR page if (first_index == 0){first_index_not_computed = 0;}else{first_index_not_computed = first_index -1} try{ // Space between the first complete node and the top of the page top_free = first_children[first_index].offsetTop; console.log("gbp5"); console.log("top free ",top_free); if (top_free > 3){ // Height of a line var fontSize = $(first_children[first_index]).css('font-size'); var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.2); console.log(" lineheight ", lineHeight); // If the free space is enough to know there may be lines above if ((top_free/lineHeight)>1){ console.log("gbp5.1"); // Coords of the node Api suscribooks Coords_firstN = getCoordFromNodeInTotal(first_children[first_index_not_computed]); //chars_firstN = visibleCharsNodePage(first_children[first_index_not_computed], first=true, page_width); chars_firstN = 0; }else{ console.log("gbp5.2"); // Coords of the node Api suscribooks Coords_firstN = getCoordFromNodeInTotal(first_children[first_index]); chars_firstN = 0; } }else{ // Coords of the node Api suscribooks Coords_firstN = getCoordFromNodeInTotal(first_children[first_index]); chars_firstN = 0; } console.log("gbp6"); //Coords_lastN = getCoordFromNodeInTotal(first_children[last_index]); Coords_lastN =0 console.log("gbp6.5"); chars_lastN = -7; vis(first_children[first_index],"primero",true); vis(first_children[first_index_not_computed],"primero NOT C", true); vis(first_children[last_index],"ult", false); //go_deeper(first_children[last_index], page_width); //chars_lastN = visibleCharsNodePage(first_children[last_index], first=false, page_width); }catch(error){ console.log("error 2 ",error.message);} // Just log /* console.log("first first_index_not_computed: ", first_index_not_computed); console.log("node first first_index_not_computed: ", first_children[first_index_not_computed]); console.log("first index: ", first_index); console.log("node first index: ", first_children[first_index]); console.log("last index: ", last_index); console.log("node last index: ", first_children[last_index]); console.log("coords_firstN: ",Coords_firstN); console.log("coords_lastN: ",Coords_lastN);*/ console.log("gbp7"); // Return the knowledge var params = { "book_id": 41034, "chapter_id": "x9788490649626EPUB-3", "username": "","coords_from": Coords_firstN, "coords_from_init_char": chars_firstN, "coords_to": Coords_lastN, "coords_to_end_char": chars_lastN}; console.log(params); // Register in suscribooks_gallery api $.ajax({type: 'POST', url: "/mobile/log_user_access/", data: params, cache: false}); } // ======================================= END count read percent ==================================================== function getObjectByAttribute(list, attr, val){ var result; $.each(list, function(index, item){ if(item[attr].toString() == val.toString()){ result = item; return false; } }); return result; } $(document).ready(function () { $('#submenu-4 ul li a').each(function(i, el){ $(el).html(unescape($(el).html())); }) // ======== Function required to send forms by Django ========== $(document).ajaxSend(function(event, xhr, settings) { // Django CSRF Protection: https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#ajax function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function sameOrigin(url) { // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative. !(/^(\/\/|http:|https:).*/.test(url)); } function safeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } if (!safeMethod(settings.type) && sameOrigin(settings.url)) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } }); // ==================== TOC pagination ========================= $("a.nextTocPage").on('click', function(e) { var params = $(this).attr('id').split('-'); url = "/book/toc/" + params[2] + "/" + params[1]; $("#toc").load(url); e.preventDefault(); }); $("a.prevTocPage").on('click', function(e) { var params = $(this).attr('id').split('-'); url = "/book/toc/" + params[2] + "/" + params[1]; $("#toc").load(url); e.preventDefault(); }); $('a.toc_disabled').on('click', function(ev){ ev.preventDefault(); ev.stopPropagation(); var d = document.createElement('div'); $(d).css({ position: 'absolute',height: '100%', width: '100%', 'background': 'rgba(0,0,0,0.7)', top: 0, left: 0}).append(buy_div_content).find('.buyLink') .on('click',function(ev){ ev.preventDefault(); window.location = "https://www.amabook.es/amabook/redirect/isbn?isbn=9788490649626"; }); $(d).on('click', function(ev){ $(this).remove(); }).children().on('click', function(ev){ ev.stopPropagation()}); $('#menu_toc').trigger('click'); $('body').append(d); }); // ===================== Search form =========================== $('#frmsearch').submit(function(e) { var search_content = $('#search_content').is(':checked'); var search_notes = $('#search_notes').is(':checked'); var search_highlights = $('#search_highlights').is(':checked'); $("#search_results").load("/search/", {search: $("#search_text").val(),search_content: search_content, search_notes: search_notes, search_highlights: search_highlights, id_book:$("#id_book").val()}, function(){ }); e.preventDefault(); return false; }); // ==================== Iframe loading ========================= var chapter_url = 'https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-3.html'; //console.log('chapter url '+chapter_url); try{ //chapter_url = chapter_url.replace(/(jacontent\/)/gi, 'content/preview/'); var i = chapter_url.indexOf('content/'); chapter_url = chapter_url.slice(0,i+8)+'preview/'+chapter_url.slice(i+8); }catch(err){ chapter_url = 'https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-3.html'; } $("#book_ifr").attr('src', chapter_url); $("#book_ifr").load(function () { adjustSVGSize(); var arr_selstr = new Array(); var iframe = $(this.contentDocument); var iframewindow = $(this)[0].contentWindow; var book = $(this.contentDocument).find('body'); var iframeBody = iframe.contents().find('body'); var iframeHTML = $(this.contentDocument).find('html'); //$(iframeBody).prepend('<div style="line-height: 0px"> </div>'); var toc_index = [{"title": " (1)", "percentage_initial": 0.0, "id": "CoverImage", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/CoverImage.xhtml", "percentage_final": 0.05735, "order": 1, "percentage_anchor": null}, {"title": " (2)", "percentage_initial": 0.05735, "id": "x9788490649626EPUB", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB.xhtml", "percentage_final": 0.150852, "order": 2, "percentage_anchor": null}, {"title": " (3)", "percentage_initial": 0.150852, "id": "x9788490649626EPUB-1", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-1.xhtml", "percentage_final": 0.258412, "order": 3, "percentage_anchor": null}, {"title": " (4)", "percentage_initial": 0.258412, "id": "x9788490649626EPUB-2", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-2.xhtml", "percentage_final": 1.23136, "order": 4, "percentage_anchor": null}, {"title": " (5)", "percentage_initial": 1.23136, "id": "x9788490649626EPUB-3", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-3.xhtml", "percentage_final": 2.69502, "order": 5, "percentage_anchor": null}, {"title": " Presentaci\u00f3n", "percentage_initial": 2.69502, "id": "x9788490649626EPUB-4", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-4.xhtml", "percentage_final": 3.56131, "order": 6, "percentage_anchor": null}, {"title": " Introducci\u00f3n al SEO", "percentage_initial": 3.56131, "id": "x9788490649626EPUB-5", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-5.xhtml", "percentage_final": 13.3577, "order": 7, "percentage_anchor": null}, {"title": " Introducci\u00f3n al SEO", "percentage_initial": 3.56131, "id": "x9788490649626EPUB-5#toc_marker-2", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-5.xhtml#toc_marker-2", "percentage_final": 13.3577, "order": 8, "percentage_anchor": 3.63542}, {"title": "    1. SEO y marketing digital", "percentage_initial": 3.56131, "id": "x9788490649626EPUB-5#toc_marker-2-1", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-5.xhtml#toc_marker-2-1", "percentage_final": 13.3577, "order": 9, "percentage_anchor": 5.85442}, {"title": "    2. \u00bfC\u00f3mo funciona un buscador?", "percentage_initial": 3.56131, "id": "x9788490649626EPUB-5#toc_marker-2-2", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-5.xhtml#toc_marker-2-2", "percentage_final": 13.3577, "order": 10, "percentage_anchor": 6.38476}, {"title": "    3. El mercado de los buscadores: \u00bfsolo Google?", "percentage_initial": 3.56131, "id": "x9788490649626EPUB-5#toc_marker-2-3", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-5.xhtml#toc_marker-2-3", "percentage_final": 13.3577, "order": 11, "percentage_anchor": 9.7102}, {"title": "    4. Metodolog\u00eda SEO: estrategia frente a t\u00e1ctica", "percentage_initial": 3.56131, "id": "x9788490649626EPUB-5#toc_marker-2-4", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-5.xhtml#toc_marker-2-4", "percentage_final": 13.3577, "order": 12, "percentage_anchor": 10.1483}, {"title": " Keyword & Context Research: an\u00e1lisis de palabras clave y del contexto SEO", "percentage_initial": 13.3577, "id": "x9788490649626EPUB-6", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-6.xhtml", "percentage_final": 24.2865, "order": 13, "percentage_anchor": null}, {"title": " Keyword & Context Research: an\u00e1lisis de palabras clave y del contexto SEO", "percentage_initial": 13.3577, "id": "x9788490649626EPUB-6#toc_marker-3", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-6.xhtml#toc_marker-3", "percentage_final": 24.2865, "order": 14, "percentage_anchor": 13.4315}, {"title": "    1. C\u00f3mo buscan los usuarios", "percentage_initial": 13.3577, "id": "x9788490649626EPUB-6#toc_marker-3-1", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-6.xhtml#toc_marker-3-1", "percentage_final": 24.2865, "order": 15, "percentage_anchor": 14.1911}, {"title": "    2. Consejos para elegir una palabra clave a posicionar", "percentage_initial": 13.3577, "id": "x9788490649626EPUB-6#toc_marker-3-2", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-6.xhtml#toc_marker-3-2", "percentage_final": 24.2865, "order": 16, "percentage_anchor": 15.2141}, {"title": "    3. Dise\u00f1o desde cero", "percentage_initial": 13.3577, "id": "x9788490649626EPUB-6#toc_marker-3-3", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-6.xhtml#toc_marker-3-3", "percentage_final": 24.2865, "order": 17, "percentage_anchor": 17.9382}, {"title": "    4. Redise\u00f1o de sitio web ya existente", "percentage_initial": 13.3577, "id": "x9788490649626EPUB-6#toc_marker-3-4", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-6.xhtml#toc_marker-3-4", "percentage_final": 24.2865, "order": 18, "percentage_anchor": 20.7481}, {"title": " SEO On Site: t\u00e9cnicas dentro del sitio web", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml", "percentage_final": 54.6661, "order": 19, "percentage_anchor": null}, {"title": " SEO On Site: t\u00e9cnicas dentro del sitio web", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4", "percentage_final": 54.6661, "order": 20, "percentage_anchor": 24.3602}, {"title": "    1. Indexabilidad", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-1", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-1", "percentage_final": 54.6661, "order": 21, "percentage_anchor": 24.8575}, {"title": "    2. Redirecciones", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-2", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-2", "percentage_final": 54.6661, "order": 22, "percentage_anchor": 26.753}, {"title": "    3. Web Performance Optimization (rapidez de carga)", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-3", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-3", "percentage_final": 54.6661, "order": 23, "percentage_anchor": 28.0569}, {"title": "    4. Dominio y URL", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-4", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-4", "percentage_final": 54.6661, "order": 24, "percentage_anchor": 29.6098}, {"title": "    5. Internacionalizaci\u00f3n SEO", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-5", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-5", "percentage_final": 54.6661, "order": 25, "percentage_anchor": 30.5223}, {"title": "    6. URL \u00abamigables\u00bb, carpetas y subdominios", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-6", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-6", "percentage_final": 54.6661, "order": 26, "percentage_anchor": 31.0177}, {"title": "    7. Accesibilidad, est\u00e1ndares web y responsive design", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-7", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-7", "percentage_final": 54.6661, "order": 27, "percentage_anchor": 31.9686}, {"title": "    8. Usabilidad y experiencia de usuario", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-8", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-8", "percentage_final": 54.6661, "order": 28, "percentage_anchor": 32.9281}, {"title": "    9. Arquitectura de informaci\u00f3n", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-9", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-9", "percentage_final": 54.6661, "order": 29, "percentage_anchor": 34.1705}, {"title": "    10. Contenido duplicado", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-10", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-10", "percentage_final": 54.6661, "order": 30, "percentage_anchor": 35.7329}, {"title": "    11. Etiqueta <TITLE>", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-11", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-11", "percentage_final": 54.6661, "order": 31, "percentage_anchor": 36.2056}, {"title": "    12. Etiquetas H1, H2 y \u00e9nfasis en palabras clave", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-12", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-12", "percentage_final": 54.6661, "order": 32, "percentage_anchor": 36.9938}, {"title": "    13. Optimizaci\u00f3n de im\u00e1genes y v\u00eddeos", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-13", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-13", "percentage_final": 54.6661, "order": 33, "percentage_anchor": 37.5348}, {"title": "    14. Estructura y caracter\u00edsticas del texto", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-14", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-14", "percentage_final": 54.6661, "order": 34, "percentage_anchor": 38.3022}, {"title": "    15. Densidad o repeticiones de palabra clave dentro de un texto", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-15", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-15", "percentage_final": 54.6661, "order": 35, "percentage_anchor": 39.7593}, {"title": "    16. Knowledge Graph Optimization (web sem\u00e1ntica)", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-16", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-16", "percentage_final": 54.6661, "order": 36, "percentage_anchor": 40.6768}, {"title": "    17. Metadatos y microdatos", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-17", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-17", "percentage_final": 54.6661, "order": 37, "percentage_anchor": 44.4235}, {"title": "    18. Identificaci\u00f3n de autor\u00eda", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-18", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-18", "percentage_final": 54.6661, "order": 38, "percentage_anchor": 46.2022}, {"title": "    19. A evitar (factores negativos)", "percentage_initial": 24.2865, "id": "x9788490649626EPUB-7#toc_marker-4-19", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-7.xhtml#toc_marker-4-19", "percentage_final": 54.6661, "order": 39, "percentage_anchor": 46.89}, {"title": " SEO Off Site: t\u00e9cnicas fuera del sitio web", "percentage_initial": 54.6661, "id": "x9788490649626EPUB-8", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-8.xhtml", "percentage_final": 87.4929, "order": 40, "percentage_anchor": null}, {"title": " SEO Off Site: t\u00e9cnicas fuera del sitio web", "percentage_initial": 54.6661, "id": "x9788490649626EPUB-8#toc_marker-5", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-8.xhtml#toc_marker-5", "percentage_final": 87.4929, "order": 41, "percentage_anchor": 54.7399}, {"title": "    1. Marketing de contenidos", "percentage_initial": 54.6661, "id": "x9788490649626EPUB-8#toc_marker-5-1", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-8.xhtml#toc_marker-5-1", "percentage_final": 87.4929, "order": 42, "percentage_anchor": 55.387}, {"title": "    2. Social Media Marketing", "percentage_initial": 54.6661, "id": "x9788490649626EPUB-8#toc_marker-5-2", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-8.xhtml#toc_marker-5-2", "percentage_final": 87.4929, "order": 43, "percentage_anchor": 62.2736}, {"title": "    3. Factores de calidad en enlaces desde otros sitios web", "percentage_initial": 54.6661, "id": "x9788490649626EPUB-8#toc_marker-5-3", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-8.xhtml#toc_marker-5-3", "percentage_final": 87.4929, "order": 44, "percentage_anchor": 70.9855}, {"title": "    4. Link building: c\u00f3mo conseguir enlaces", "percentage_initial": 54.6661, "id": "x9788490649626EPUB-8#toc_marker-5-4", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-8.xhtml#toc_marker-5-4", "percentage_final": 87.4929, "order": 45, "percentage_anchor": 74.8895}, {"title": "    5. Link baiting: conseguir enlaces r\u00e1pidamente", "percentage_initial": 54.6661, "id": "x9788490649626EPUB-8#toc_marker-5-5", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-8.xhtml#toc_marker-5-5", "percentage_final": 87.4929, "order": 46, "percentage_anchor": 80.2545}, {"title": " Anal\u00edtica web para SEO", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml", "percentage_final": 95.0545, "order": 47, "percentage_anchor": null}, {"title": " Anal\u00edtica web para SEO", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9#toc_marker-6", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml#toc_marker-6", "percentage_final": 95.0545, "order": 48, "percentage_anchor": 87.5669}, {"title": "    1. Palabras clave por las que se obtiene tr\u00e1fico frente a no se obtiene tr\u00e1fico", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9#toc_marker-6-1", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml#toc_marker-6-1", "percentage_final": 95.0545, "order": 49, "percentage_anchor": 88.2809}, {"title": "    2. Posiciones para palabras clave de inter\u00e9s", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9#toc_marker-6-2", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml#toc_marker-6-2", "percentage_final": 95.0545, "order": 50, "percentage_anchor": 89.0305}, {"title": "    3. Tr\u00e1fico debido a SEO frente a resto de tr\u00e1fico", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9#toc_marker-6-3", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml#toc_marker-6-3", "percentage_final": 95.0545, "order": 51, "percentage_anchor": 89.3681}, {"title": "    4. An\u00e1lisis del mercado SEO", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9#toc_marker-6-4", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml#toc_marker-6-4", "percentage_final": 95.0545, "order": 52, "percentage_anchor": 90.0723}, {"title": "    5. Links desde otras webs frente a competencia", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9#toc_marker-6-5", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml#toc_marker-6-5", "percentage_final": 95.0545, "order": 53, "percentage_anchor": 90.404}, {"title": "    6. P\u00e1ginas de sitio web propio con m\u00e1s links entrantes", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9#toc_marker-6-6", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml#toc_marker-6-6", "percentage_final": 95.0545, "order": 54, "percentage_anchor": 90.6424}, {"title": "    7. P\u00e1ginas con m\u00e1s conversiones", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9#toc_marker-6-7", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml#toc_marker-6-7", "percentage_final": 95.0545, "order": 55, "percentage_anchor": 90.7715}, {"title": "    8. Qu\u00e9 contenido genera m\u00e1s \u00absocial signals\u00bb y links sociales", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9#toc_marker-6-8", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml#toc_marker-6-8", "percentage_final": 95.0545, "order": 56, "percentage_anchor": 91.0337}, {"title": "    9. Grado de correlaci\u00f3n entre m\u00e9tricas", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9#toc_marker-6-9", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml#toc_marker-6-9", "percentage_final": 95.0545, "order": 57, "percentage_anchor": 93.8163}, {"title": "    10. La medida de todas las cosas: la rentabilidad SEO", "percentage_initial": 87.4929, "id": "x9788490649626EPUB-9#toc_marker-6-10", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-9.xhtml#toc_marker-6-10", "percentage_final": 95.0545, "order": 58, "percentage_anchor": 94.0218}, {"title": " Ep\u00edlogo", "percentage_initial": 95.0545, "id": "x9788490649626EPUB-10", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-10.xhtml", "percentage_final": 96.151, "order": 59, "percentage_anchor": null}, {"title": " Bibliograf\u00eda", "percentage_initial": 96.151, "id": "x9788490649626EPUB-11", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-11.xhtml", "percentage_final": 97.9137, "order": 60, "percentage_anchor": null}, {"title": " Glosario", "percentage_initial": 97.9137, "id": "x9788490649626EPUB-12", "href": "https://reader.digitalbooks.pro/content/books/41034/book/OEBPS/9788490649626EPUB-12.xhtml", "percentage_final": 100.0, "order": 61, "percentage_anchor": null}]; t = toc_index; var current_index = null; for(ch in toc_index){ if(toc_index[ch].id == 'x9788490649626EPUB-3') current_index = parseInt(ch); } tin = toc_index[current_index]; //var previewPercentage = '10'; //adding some cases to avoid the sec mesg from dj if(tin.percentage_final > '10' || tin.percentage_initial > '10' || tin.percentage_initial == null){ //console.log(tin.percentage_final+' > '+previewPercentage); var chapterPercent = tin.percentage_final - tin.percentage_initial; //console.log('chapter percentage '+chapterPercent); var bodyLength = iframeBody.text().length; var bodyEl =iframeBody.find('*'); // This to show the msg over the django security msg if (tin.percentage_initial == null){ iframe.contents().find('head').append('<style>'+ '.buyDiv { background-color: white; margin-top:20px; width:50%; margin: auto; border: 2px solid #A6A6A6;border-radius: 8px; padding: 15px; overflow: hidden; }'+ '.buyDiv p {font-family: Arial; color: #686868; margin-top: 0}'+ '.buyDiv div {text-align: center; }'+ '.buyLink {background-color: #8851D7;cursor:pointer; cursor: hand;background-image: -webkit-linear-gradient(top, #965DDC 0%, #63C 100%); color: white; text-decoration: none;'+ 'font-family: Arial; font-weight: bold; padding: 10px; border-radius: 5px; margin:20px auto;}'+ +'</style>'); iframeBody.html(buy_div_content); iframeBody.find('.buyLink').off('click').on('click', function(){ //alert('going to https://www.amabook.es/amabook/redirect/isbn?isbn=9788490649626'); window.location = "https://www.amabook.es/amabook/redirect/isbn?isbn=9788490649626"; }); } $.each(bodyEl, function(ind,el){ //here only when the body has any element (loading an iframe from a book) var lengthBefore = textUntilLength(el, iframe[0]); if(((lengthBefore/bodyLength)*chapterPercent) + tin.percentage_initial > '10' || tin.percentage_initial == null){ percentageRemoved = 1 - (lengthBefore/bodyLength); iframe.find('head').append('<style>'+ '.buyDiv { background-color: white; margin-top:20px; width:50%; margin: auto; border: 2px solid #A6A6A6;border-radius: 8px; padding: 15px; overflow: hidden; }'+ '.buyDiv p {font-family: Arial; color: #686868; margin-top: 0}'+ '.buyDiv div {text-align: center; }'+ '.buyLink {background-color: #8851D7;cursor:pointer; cursor: hand;background-image: -webkit-linear-gradient(top, #965DDC 0%, #63C 100%); color: white; text-decoration: none;'+ 'font-family: Arial; font-weight: bold; padding: 10px; border-radius: 5px; margin:20px auto;}'+ +'<style>'); $(el).before(buy_div_content); iframeBody.find('.buyLink').off('click').on('click', function(){ //alert('going to https://www.amabook.es/amabook/redirect/isbn?isbn=9788490649626'); window.location = "https://www.amabook.es/amabook/redirect/isbn?isbn=9788490649626"; }); subArr = bodyEl.splice(ind, bodyEl.length - ind ); $(subArr).remove(); setTimeout(function(){ var p = iframe.find('.buyDiv').position().top; //if(p < 0){ // iframe.find('.buyDiv').css('margin-top', p*(-1)+'px'); //} iframe.find('.buyDiv').css({'position': 'relative'}).animate({'top': iframe.find('.buyDiv').position().top * (-1)+'px'}); //iframe.find('.buyDiv').css({'position': 'absolute', 'left': '200px', 'top':0});//.animate({'top': iframe.find('.buyDiv').position().top * (-1)+'px'}); }, 2000); return false; } }); } // ========== Browser detection and CSS definition ============== $(book).css('padding', '0px').css('margin', '0px').css('height', '100%').css('width', '100%').css('position', 'absolute'); var userAgent = navigator.userAgent.toLowerCase(); jQuery.browser = { version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1], chrome: /chrome/.test( userAgent ), safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ), opera: /opera/.test( userAgent ), msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ), mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ) }; if ($.browser.chrome) { $(iframeHTML).css('overflow', 'hidden'); $(book).css('-webkit-column-width', '622px') .css('-webkit-column-gap', '0px') .css('-webkit-transition-property', 'none') .css('-webkit-transition-duration', 'initial') .css('-webkit-transition-timing-function', 'initial') .css('-webkit-transition-delay', 'initial') .css('-webkit-transform', 'translateX(0px)'); }else if ($.browser.msie){/* if ($.browser.version>=7){ document.write("<link rel='stylesheet' type='text/css' href='css/browsers/ie7.css'>"); }else{ document.write("<link rel='stylesheet' type='text/css' href='css/browsers/ie6.css'>"); }*/ }else if ($.browser.safari) { $(iframeHTML).css('overflow', 'hidden'); $(book).css('-webkit-column-width', '622px') .css('-webkit-column-gap', '0px') .css('-webkit-transition-property', 'none') .css('-webkit-transition-duration', 'initial') .css('-webkit-transition-timing-function', 'initial') .css('-webkit-transition-delay', 'initial') .css('-webkit-transform', 'translateX(0px)'); }else if ($.browser.opera) { $(iframeHTML).css('overflow', 'hidden'); $(book).css('column-width', '622px') .css('column-gap', '0px') .css('-o-transform', 'translateX(0px)'); }else if ($.browser.mozilla) { $(iframeHTML).css('overflow', 'hidden'); $(book).css('-moz-column-width', '622px').css('-moz-column-gap', '0px').css('-moz-transform', 'translateX(0px)'); } if (!document.getElementById('book_ifr').contentWindow.NodeList.prototype.filter){ document.getElementById('book_ifr').contentWindow.NodeList.prototype.filter = function(fun /*, thisp*/){ var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++){ if (i in this){ var val = this[i]; // in case fun mutates this if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; } // =================== Resize images ============================ function resizeImages() { var maxwidth = book.width(); var maxheight = book.height(); // NEW the maxheight was *0.8 but that let some space below the cover. changed to *0.9 book.find("img").css({'max-width': maxwidth -10, 'max-height' : maxheight *0.90, 'width': 'auto'}); } $('#book_ifr').contents().find('*').each(function(index, el){ var bottom = $(el).css('margin-bottom'); var top = $(el).css('margin-top'); var ln = $(el).css('line-height'); if(bottom.charAt(0) == '-' ){ $(el).css('margin-bottom', 0); } if(top.charAt(0) == '-' ){ $(el).css('margin-top', 0); } if(ln.charAt(0) == '-' ){ $(el).css('line-height', 0); } }); var bookmarks = {}; // =================== Resize iframe ============================ function resizeIframe() { // NEW sustract a % of the total instead of a fixed number... //var height_sustract = Math.round($(window).height()/3.5); //console.log("sustract: ", height_sustract); var bookIfr = $("#book_ifr"); var height = $(window).height() - 210; // 210 | height_sustract if (height<300) { height = 300; } $("#iframe_container").css('height', height + 20); bookIfr.css('height', height); $(book).css('height', height); $(".arrow_back").css('top', (height + 80) / 2); $(".arrow_forward").css('top', (height + 80) / 2 - 52); $(".arrow_b").css('top', (height + 80) / 2); $(".arrow_f").css('top', (height + 80) / 2); if ("epub" === "fixed") { var bookBodyWidth = book[0].scrollWidth; var bookBodyHeight = book[0].scrollHeight; var headerHeight = $("#navigation").height(); var pageWrapper = $(".page-wrapper"); var iframeContainer = $("#iframe_container"); var breadcrumbs = $("#breadcrumbs"); bookIfr.css({ width: bookBodyWidth, height: bookBodyHeight }); pageWrapper.css("width", bookBodyWidth + parseFloat(iframeContainer.css("padding")) * 2); var scaleFactor = ($(window).width() - 36) / (bookBodyWidth); if (scaleFactor > 1) scaleFactor = 1; bookIfr.css({ transform: "scale(" + scaleFactor + ")", transformOrigin: "top left" }); breadcrumbs.css({ position: "absolute", top: bookBodyHeight * scaleFactor + 30, width: bookBodyWidth * scaleFactor }); iframeContainer.css({ width: bookBodyWidth * scaleFactor, height: bookBodyHeight * scaleFactor + breadcrumbs.height() }); $(".arrow_b").css({ position: "fixed", top: "calc(50vh + 38px)", right: "unset", zIndex: 1 }); $(".arrow_f").css({ position: "fixed", top: "calc(50vh + 38px)", left: bookBodyWidth * scaleFactor + parseFloat(pageWrapper.css("margin-left")) + 20, zIndex: 1 }); iframeContainer.find(".icon-bookmark").css({ right: 18, left: "unset" }); } try{ isBookmarked(bookmarks); }catch(e){ console.log('bookmarks error'); } } // ==================== Pagination ============================== function scrollToPage(number) { var leftpos = book.width() * (number - 1); iframewindow.scrollTo(leftpos, 0); //alert('isBookmarked en scrollToPage'); isBookmarked(bookmarks); } function adjustPage(){ var pos = $(iframe).scrollLeft(); var book_width = $(book).width(); var offset = (pos % book_width); if(offset != 0) $(iframe).scrollLeft(pos - offset); } $(iframe).bind('scroll', function(){ adjustPage(); }); function calculatePages() { var num_pages = parseInt(iframe.width() / book.width()); //$(".pagetotal").html(num_pages); //$(".pagetotal").html(Math.round(tin.percentage_final)); var current_page = 1; var chapterPercentage = tin.percentage_final - tin.percentage_initial; try{ var percentageErased = percentageRemoved; }catch(err){ var percentageErased = 0; } if (iframe.scrollLeft() != 0) { var current_page = parseInt(1 + iframe.scrollLeft() / book.width()); } //var percent = Math.round(tin.percentage_initial+(((current_page/num_pages)-percentageErased)*chapterPercentage)); var percent = Math.round(tin.percentage_initial+( current_page / ( num_pages / ( 1 - percentageErased ) ) * chapterPercentage)); $(".pagenumber").html(percent+'%'); $('#progressBar').find('.progress').css('width',percent+'%'); //$(".pagenumber").html("<span>" + current_page + "</span>"); pageIcoShow(current_page, num_pages); } calculatePages(); //NEW changed order resize images->iframe to iframe->images resizeIframe(); if ("epub" !== "fixed") resizeImages(); $(window).resize(function() { calculatePages(); resizeIframe(); if ("epub" !== "fixed") resizeImages(); }); function getCurrentPage() { var current_page = 1; if (iframe.scrollLeft() != 0) { var current_page = parseInt(1 + iframe.scrollLeft() / book.width()); } return current_page; } //alert('Previous chapter x9788490649626EPUB-2\n Next chapter x9788490649626EPUB-4'); function gotoPrevPage() { var num_pages = parseInt(iframe.width() / book.width()); var current_page = 1; callCountPage(iframe); if (iframe.scrollLeft() != 0) { var current_page = parseInt(1 + iframe.scrollLeft() / book.width()); } if (current_page > 1) { current_page = current_page - 1; scrollToPage(current_page); calculatePages(); var pos = iframe.scrollLeft(); } else { var d = new Date(); var prevchapter = "x9788490649626EPUB-2"; if (prevchapter != "") { window.location = "/book/preview/41034/x9788490649626EPUB-2/-?"+d.getTime(); return false; } } return false; } function gotoNextPage() { var num_pages = parseInt(iframe.width() / book.width()); var current_page = 1; callCountPage(iframe); if (iframe.scrollLeft() != 0) { var current_page = parseInt(1 + iframe.scrollLeft() / book.width()); } if (current_page < num_pages) { current_page = current_page + 1; scrollToPage(current_page); calculatePages(); var pos = iframe.scrollLeft(); } else { var nextchapter = "x9788490649626EPUB-4"; var d = new Date(); if (nextchapter != "") { if(tin.percentage_final > '10' || tin.percentage_initial == null){ //window.location = "https://www.amabook.es/amabook/redirect/isbn?isbn=9788490649626"; var d = document.createElement('div'); $(d).css({ position: 'absolute',height: '100%', width: '100%', 'background': 'rgba(0,0,0,0.7)', top: 0, left: 0}).append(buy_div_content).find('.buyLink').on('click',function(ev){ window.location = "https://www.amabook.es/amabook/redirect/isbn?isbn=9788490649626"; }); $(d).on('click', function(ev){ $(this).remove(); }).children().on('click', function(ev){ ev.stopPropagation()}); $('body').append(d); }else window.location = "/book/preview/41034/x9788490649626EPUB-4?"+d.getTime(); } } return false; } $(".prevpage").click(function(){ return gotoPrevPage(); }); $(".nextpage").click(function(){ return gotoNextPage(); }); $(document).keydown(function(e){ // <- if (e.keyCode == 37) { gotoPrevPage(); return false; } // -> if (e.keyCode == 39) { gotoNextPage(); return false; } // + if ((e.keyCode == 107) || (e.keyCode == 187)) { zoomInText(); return false; } // - if ((e.keyCode == 109) || (e.keyCode == 189)) { zoomOutText(); return false; } }); var currentFontFamily = '0'; var fontFamilyChanged = false; $(iframe).contents().find('head').append('<style type="text/css"> @font-face { font-family: "SansForgetica Regular"; src: url("/media/font/SansForgetica-Regular.otf"); font-weight: normal; font-style: normal; } .font-family-selected-Arial{ font-family: Arial, Helvetica, sans-serif !important; } .font-family-selected-Courier{ font-family: Courier, monospace !important; } .font-family-selected-Georgia{ font-family: Georgia, serif !important; } .font-family-selected-Palatino{ font-family: Palatino, serif !important; } .font-family-selected-SansForgetica{ font-family: SansForgetica Regular !important; } .font-family-selected-Tahoma{ font-family: Tahoma, Geneva, sans-serif !important; } .font-family-selected-Times{ font-family: Times, serif !important; } .font-family-selected-Verdana{ font-family: Verdana, Geneva, sans-serif !important; } </style>'); $("#font_select").change(function(){ selectedFamily = $(this).val(); if (fontFamilyChanged) { $(iframe).find('*').removeClass('font-family-selected-' + currentFontFamily); } if (selectedFamily == 0) { fontFamilyChanged = false; currentFontFamily = '0'; } else { $(iframe).find('*').addClass('font-family-selected-' + selectedFamily); fontFamilyChanged = true; currentFontFamily = selectedFamily; } storeFamily(selectedFamily); calculatePages(); }); function setFamily(font_family){ $(iframe).find('*').addClass('font-family-selected-' + font_family); currentFontFamily = font_family; fontFamilyChanged = true; calculatePages(); $("#font_select").val(font_family); } if('' != '') setFamily(''); function storeFamily(font_family){ $.ajax({ type: 'POST', url: "/font_family/", data: "&font_family="+font_family, cache: false }); } // ==================== Links process =============================== var external = RegExp('^((f|ht)tps?:)?//(?!' + location.host + ')'); $(iframe).find('a').each(function(index, el){ if(external.test(el)){ $(el).attr('target', '_blank'); }else{ $(el).bind('click', function(ev){ ev.preventDefault(); evento = ev; if(ev.currentTarget.pathname == iframewindow.location.pathname){ if(ev.currentTarget.hash != ''){ var target = $(iframeBody).find(ev.currentTarget.hash).position().left; var offset = target % $(iframeBody).width(); $('#book_ifr').contents().scrollLeft(target - offset); } }else{ //var target = getObjectByAttribute(toc_index, 'href', ev.currentTarget.origin+ev.currentTarget.pathname); var target = getObjectByAttribute(toc_index, 'href', 'http://'+ev.currentTarget.host+ev.currentTarget.pathname); au = toc_index; //console.log(ev.currentTarget.href); //console.log(ev.currentTarget.origin+ev.currentTarget.pathname); if(target){ var d = new Date(); //console.log('imos a '+"/book/41034/"+target.id+'?'+d.getTime()+ev.currentTarget.hash); window.location = "/book/41034/"+target.id+'?'+d.getTime()+ev.currentTarget.hash; } } }); } }); $('#toc').find('a').each(function(index, el){ if(!external.test(el)){ $(el).bind('click', function(ev){ evento = ev; if(ev.currentTarget.pathname == window.location.pathname){ if(ev.currentTarget.hash != ''){ ev.preventDefault(); if($(iframeBody).find(ev.currentTarget.hash).is('div')){ var t = $(iframeBody).find(ev.currentTarget.hash).children(':first'); var t1 = Math.ceil($(t).position().left); var o = t1 % $(iframeBody).width(); $('#book_ifr').contents().scrollLeft(t1); }else{ var target = Math.ceil($(iframeBody).find(ev.currentTarget.hash).position().left); var offset = target % $(iframeBody).width(); //console.log(target); $('#book_ifr').contents().scrollLeft(target - offset); } } }else{ ev.preventDefault(); var d = new Date(); window.location = ev.currentTarget.pathname+'?'+d.getTime()+ev.currentTarget.hash; } }); } }); $('#search_results a').live('click', function(ev){ ev.preventDefault(); var d = new Date(); window.location = ev.currentTarget.pathname+'?'+d.getTime()+ev.currentTarget.hash; }); $('#submenu-4 a').live('click', function(ev){ ev.preventDefault(); var d = new Date(); window.location = ev.currentTarget.pathname+'?'+d.getTime()+ev.currentTarget.hash; }); // ==================== Font size =============================== // Reset Font Size var originalFontSize = book.css('font-size'); $(".resetFont").click(function(){ book.css('font-size', originalFontSize); storeSize(originalFontSize); calculatePages(); return false; }); function zoomInText() { var currentFontSize = book.css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*1.2; book.css('font-size', newFontSize); storeSize(newFontSize); calculatePages(); return false; } function zoomOutText() { var currentFontSize = book.css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*0.8; book.css('font-size', newFontSize); storeSize(newFontSize); calculatePages(); return false; } function setSize(size){ if(size < 15) size = 15; book.css('font-size', size); book.find('table').css('font-size', size); } if('' != '') setSize(''); else{ var s = parseInt(originalFontSize)+2; setSize(s); console.log('setting size to: '+s); } $('#slider_text_size').slider({ //value: parseInt(''), value: parseInt(book.css('font-size')), min: 15, max: 30, slide: function(ev, ui) { if(ui.value < 15) ui.value = 15; book.css('font-size', ui.value); book.find('table').css('font-size', ui.value); storeSize(ui.value); calculatePages(); } }); function storeSize(size){ var d = new Date(); $.ajax({ type: 'POST', url: "/size/"+size+"?"+d.getTime(), cache: false, success: function(data) { return false; }, error: function(data) { return false; } }); } // Increase Font Size $(".increaseFont").click(function(){ return zoomInText(); }); // Decrease Font Size $(".decreaseFont").click(function(){ return zoomOutText(); }); // =================================== Avoiding copy ====================================== var ctrlDown = false; var ctrlKey = 17, vKey = 86, cKey = 67; $(iframe).keydown(function(e){ if (e.keyCode == ctrlKey) ctrlDown = true; }).keyup(function(e){ if (e.keyCode == ctrlKey) ctrlDown = false; }); $(iframe).keydown(function(e){ if (ctrlDown && e.keyCode == cKey) return false; }); //security level if ("1"==2){ // Key access $(iframe).keydown(function(evt){ // IE support evt = evt||window.event var c = evt.keyCode // Mac support var ctrlDown = evt.ctrlKey||evt.metaKey // Alt+Gr if (ctrlDown && evt.altKey) return true // Check for ctrl+key else if (ctrlDown && c==65) return false //evt.preventDefault(); // a (select all) else if (ctrlDown && c==67) return false // c else if (ctrlDown && c==86) return false // v else if (ctrlDown && c==19) return false // cmd else if (ctrlDown && c==115) return false // else if (ctrlDown && c==88) return false // x else if (ctrlDown && c==83) return false // s save as else if (ctrlDown && c==85) return false // u see source code else if (ctrlDown && c==80) return false // p print else if (ctrlDown && c==73) return false // i web dev tools else if (ctrlDown && c==74) return false // j web dev tools else if (c==19) return false // OS X webkit browsers cmd+s else if (evt.wich ==19) return false // /=/ // Otherwise allow return true }); $(iframe).bind({ copy : function(evt){ evt.preventDefault(); }, paste : function(evt){ evt.preventDefault(); }, cut : function(evt){ evt.preventDefault(); } }); //avoid dragging text outside the book $("#book_ifr").contents().find("*").bind("dragstart", function(e) { e.preventDefault(); }); //disable all selection, not only dragging /* $("#book_ifr").contents().find("*").on('mousedown', function(e) { e.preventDefault(); });*/ //limit options in our own context Menu (all the share ones) $("#ctxMenu li:not(:contains('Insert note'),:contains('Highlight'))").remove() //right click on images $('body').on('contextmenu', 'img', function(e){ return false; }); //$('img').bind('contextmenu', function(e) {return false; }); $('img').live('contextmenu', function(e){ return false; }); // FF // no context menu outside the book $('body').on('contextmenu', function(e){ return false }); $('#book_ifr').on('contextmenu', function(e){ return true; }); // allow context menu in the book } // =================================== link changing in the contextMenu ====================================== if ("amabook-30-espana" == 'ebeway'){ $("#ctxMenu li:contains('Quiero Leer')").html('<a href="#ctxQuieroleer">Ebelink</a>'); } // =================================== Night mode (CLASSES) ========================================== $(iframe).contents().find('head').append("<style type='text/css'> .iframe_night{background-color:black !important; color: white !important;} .iframe_sepia{background-color:#FBF0D9 !important; color: #5F4B32 !important;} .iframe_grey{background-color:#D2D2D2 !important; color: black !important;} .highlight_mode{background:#ff0 !important; color: black !important; border:1px solid #aa0; border-radius:5px; -moz-border-radius:5px;} </style>"); $(".highlight", book).addClass('highlight_mode'); $(".highlight *", book).addClass('highlight_mode'); var current_mode = 'day' function displayMode(mode){ if (current_mode != 'day') { $("#book_ifr").contents().find("*").removeClass('iframe_'+current_mode); $("#book_ifr").contents().find("body").find('*').removeClass('iframe_'+current_mode); $("#iframe_container").removeClass('iframe_'+current_mode); $("body").removeClass('body_'+current_mode) } if (mode != 'day') { $("#book_ifr").contents().find("*").addClass('iframe_'+mode); $("#book_ifr").contents().find("body").find('*').addClass('iframe_'+mode); $("#iframe_container").addClass('iframe_'+mode); $("body").addClass('body_'+mode) $(".highlight", book).addClass('highlight_mode'); $(".highlight *", book).addClass('highlight_mode'); $("#book_ifr").contents().find("table").filter(function(){ return $(this).css('background-image') != 'none'} ).css('background-color','transparent').find('*').css('background-color','transparent'); } current_mode = mode; } $(".nightMode").click(function(){ displayMode('night'); setMode('night'); }); $(".dayMode").click(function(){ displayMode('day'); setMode('day'); }); $(".greyMode").click(function(){ displayMode('grey'); setMode('grey'); }); $(".sepiaMode").click(function(){ displayMode('sepia'); setMode('sepia'); }); $(iframewindow).bind('scroll', function(ev){ calculatePages(); }); // ==================== Insert highlight texts and notes marks ============================= var SEL_LEN = 7; var iframejs = document.getElementById("book_ifr"); var win = iframejs.contentWindow; var doc = iframejs.contentDocument || win.document; // TO-DO. Esto se resolverá con Python // Order selected strings by reverse order // Define marks var marks = new Array(); var marks_coords = new Array(); var marks_id = new Array(); var marks_text = new Array(); var marks_type = new Array(); var to_attach_event = new Array(); var inner_highlights = new Array(); for(pos=0; pos<marks_coords.length; pos++) { var coor = marks_coords[pos].split(','); var initNode = coor[0].split('>').slice(0,-1).join('>'); var firstNode = getNodeFromCoord(coor[0]); var endNode = coor[1].split('>').slice(0,-1).join('>'); var lastNode = getNodeFromCoord(coor[1]); if((firstNode == null) || (lastNode == null)) continue; var initOffset = parseInt(coor[0].split('>').pop(),10); var endOffset = parseInt(coor[1].split('>').pop(),10); var text = unescape(marks_text[pos]); var hl_id = marks_id[pos]; var class_mark = ''; var type = ''; if(marks_type[pos] == 'h'){ class_mark = 'highlight'; type = 'Resaltado'; }else{ if(marks_type[pos] == 'n'){ class_mark = 'notesmark'; type = 'Nota'; } } if(marks_type[pos] == 'n'){ marks.push(new Array(coor[0], "<span class='"+class_mark+"' id='nt" + hl_id + "'>*</span>", text, type, pos, hl_id, 'nt'+hl_id,text,coor[1])); }else{ if(initNode != endNode){ var aux = text.substr(-endOffset); var aux_coor = coor[1].split('>'); aux_coor[aux_coor.length-1] = zeroFill(0,10); if(endOffset != 0){ marks.push(new Array(aux_coor.join('>'), "<span class='"+class_mark+"' id='hl" + hl_id + "_00" + "'>", aux, type, pos, hl_id,'hl'+hl_id+'_00', text,coor[1])); } var inbetween_nodes = null; if((firstNode != null)&&(lastNode != null)){ inbetween_nodes = getElementsBetweenTree(firstNode, lastNode); } $(inbetween_nodes).each(function(index, el){ if((el!=firstNode) && (el!=lastNode) && ($(lastNode).parents().index(el) == -1) && ($(firstNode).parents().index(el) == -1)){ inner_highlights.push({ element: el, tag: '<span class="'+class_mark+'" id="hl'+hl_id+'_'+index+'"></span>' }); /* if(el.nodeType == 3){ $(el).wrap('<span class="'+class_mark+'" id="hl'+hl_id+'_'+index+'"></span>'); }else{ $(el).wrapInner('<span class="'+class_mark+'" id="hl'+hl_id+'_'+index+'"></span>'); }*/ to_attach_event.push(new Array('','<span class="" id="" >',$(el).text(),type,pos,hl_id,'hl'+hl_id+'_'+index,text)); } }); aux = text.substr(0,$(getNodeFromCoord(coor[0])).text().length-initOffset); marks.push(new Array(coor[0], "<span class='"+class_mark+"' id='hl" + hl_id + "_01'>", aux, type, pos, hl_id,'hl'+hl_id+'_01',text,coor[1])); // marks.push(new Array(coor[0], "<span class='"+class_mark+"' id='hl" + hl_id + "_01'>", aux, type, pos, hl_id,'hl'+hl_id+'_01',text,coor[1])); }else{ if (initOffset != endOffset) { // Highlight marks.push(new Array(coor[0], "<span class='"+class_mark+"' id='hl" + hl_id + "'>", text, type, pos, hl_id,'hl'+hl_id,text,coor[1])); } } } } marcas = marks; // Sort marks.sort(); var overlapped_notes = new Array(); var overlapped_notes_array = new Array(); var i = 0; // Merge marks in case they are overlapped while(true){ if(marks[i] && marks[i+1]){ if((marks[i][3]=='Nota') || (marks[i+1][3]=='Nota')){ var merge = mergeMarks(marks[i][0],marks[i+1][0],marks[i][2].length,marks[i+1][2].length,marks[i][3],marks[i+1][3],marks[i][6], marks); if(merge.status == 3){ marks[i+1][0] = merge.mark; var note = {note: marks[i+1], append_to:merge.append_to}; overlapped_notes.push(note); overlapped_notes_array.push(marks[i+1]); //marks.splice(i+1,1); } i++; continue; } var merge = mergeMarks(marks[i][0],marks[i+1][0],marks[i][2].length,marks[i+1][2].length,marks[i][3],marks[i+1][3],marks[i][5]); if(merge.status == 1) { var params = { "id_mark": marks[i+1][5], "mark_type":'h', "page":0, "id_book": 41034, "chapter": "x9788490649626EPUB-3" }; manipulateMark(actions['delete'], params); marks.splice(i+1,1); } else { if(merge.status == 2){ marks[i][0] = merge.mark; marks[i][2] = merge.text; var aux_coord = merge.mark+','+marks[i+1][0] var params = { "id_mark": marks[i][5], "mark_type":'h', "page":0, "id_book": 41034, "chapter": "x9788490649626EPUB-3", text: merge.text, coords: merge.mark+','+marks[i+1][8]}; manipulateMark(actions.update, params); params = { "id_mark": marks[i+1][5], "mark_type":'h', "page":0, "id_book": 41034, "chapter": "x9788490649626EPUB-3" }; manipulateMark(actions['delete'], params); marks.splice(i+1,1); }else{ i++; } } }else{ break; } }; marks.sort().reverse(); var modifiedNodes = new Array(); var modifiedNodesObjects = new Array(); // Define modified nodes for (mark_pos in marks) { var mark = marks[mark_pos][0]; var mark_tag = marks[mark_pos][1]; // Iterate over DOM until selected node var offset = parseInt(mark.split(">").slice(-1), 10); var markNode = mark.split(">").slice(0,-1).join(">"); // also if this node has inside it another modified node.. catch it var current_node = getNodeFromCoord(mark); var text = ''; if (current_node) { modifiedNodes[markNode] = $(current_node).text(); modifiedNodesObjects[markNode] = current_node; if(marks[mark_pos][3] == 'Resaltado'){ text = marks[mark_pos][2]; //insertText(current_node,text,offset,offset+marks[mark_pos][2].length,'hl'+marks[mark_pos][5],'highlight'); insertText(current_node,text,offset,offset+marks[mark_pos][2].length,marks[mark_pos][6],'highlight'); }else{ //insertText(current_node,text,offset,offset,'hl'+marks[mark_pos][5],'notesmark'); if($.inArray(marks[mark_pos], overlapped_notes_array) != -1) continue; console.log('displaying note '+markNode+' '+offset); insertText(current_node,text,offset,offset,marks[mark_pos][6],'notesmark'); } } } // Insert overlapped notes $.each(overlapped_notes, function(index, el){ var newNode; newNode = doc.createElement('span'); newNode.className = 'notesmark'; newNode.setAttribute("id",el.note[6]); $(doc).contents().find('#'+el.append_to).after(newNode); }); $.each(inner_highlights, function(index, el){ if(el.element.nodeType == 3){ $(el.element).wrap(el.tag); }else{ $(el.element).wrapInner(el.tag); } }); var nt = $('#book_ifr').contents().find('.notesmark'); $.each(nt, function(index, el){ $(el).parents('.highlight').first().after(el); }); // ================= Add overlays ============================= marks = marks.concat(to_attach_event); for (mark_pos in marks) { // Add tip var text = ""; var mark = marks[mark_pos][0]; var mark_tag = marks[mark_pos][1]; var title = marks[mark_pos][3]; text = marks[mark_pos][7]; var mark_id = marks[mark_pos][5]; var type= ''; if (title == "Nota") { title = "Note" text = "<form id='frmNotes' method='post'>" +"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='a9391c6945f1c3a6872df0c5a823e34f' /></div>"+ "<textarea class='notes_textarea' id='notes_textarea_" + mark_id + "'>" + unescape(text) + "</textarea><br /><br />" + "<input type='submit' style='background-color: #965ddc;' name='btnDeleteMark' class='btnDeleteMark note' id='btnDeleteMark-" + mark_id + "' value='Delete' /> " + "<input type='submit' style='background-color: #965ddc;' name='btnUpdateMark' class='btnUpdateMark' id='btnUpdateMark-" + mark_id + "' value='Update' />" + "</form>"; type = 'n'; } else { title = "Highlight" text = "<form id='frmNotes' method='post'>" +"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='a9391c6945f1c3a6872df0c5a823e34f' /></div>"+ "<b>Highlighted text</b><br /><br />" + unescape(text) + "<br /><br />" + "<input type='submit' style='background-color: #965ddc;' name='btnDeleteMark' class='btnDeleteMark high' id='btnDeleteMark-" + mark_id + "' value='Delete' /> " + "</form>"; type = 'h'; } counter = marks[mark_pos][5]; if (mark_tag.length > 10) { // Avoid </span> marks //alert("Adding tip: " + text + " to " + '#hl' + arr_value[mark_pos] + " - " + mark_tag + " - " + mark); //$('#hl' + counter, book).qtip({ $('[id^='+marks[mark_pos][6]+']', book).qtip({ content: { title: { text: title, //button: 'Close' button: 'X' }, text: text, }, position: { target: $(document.body), // Position it via the document body... corner: 'center' // ...at the center of the viewport }, show: { when: 'click', // Show it on click solo: true // And hide all other tooltips }, hide: false, style: { width: 500, padding: '14px', border: { width: 2, radius: 2, color: '#666666' }, name: 'light' }, api: { beforeShow: function() { // Fade in the modal "blanket" using the defined show speed $('#qtip-blanket').fadeIn(this.options.show.effect.length); }, beforeHide: function() { // Fade out the modal "blanket" using the defined hide speed $('#qtip-blanket').fadeOut(this.options.hide.effect.length); }, onShow: function(event) { // Control mark events $(".btnDeleteMark").on('click', function(e) { $(this).hasClass('note') && (type = 'n'); $(this).hasClass('high') && (type = 'h'); var id_mark = parseInt($(this).attr('id').split('-')[1]); var page = getCurrentPage(); // Delete mark $.ajax({ type: 'POST', url: "/mark/delete/", data: { "id_mark": id_mark, "mark_type":type, "page":page, "id_book": 41034, "chapter": "x9788490649626EPUB-3" }, cache: false, success: function(data) { window.location.hash = ''; if(window.location.pathname != data.url) window.location.pathname = data.url; else window.location.reload(); return false; }, error: function(data) { //alert("Error deleting " + data.toString()); } }); e.preventDefault(); }); $(".btnUpdateMark").on('click', function(e) { var id_mark = parseInt($(this).attr('id').split('-')[1]); var note = escape($("#notes_textarea_" + id_mark).val()); var page = getCurrentPage(); // Update mark $.ajax({ type: 'POST', url: "/mark/update/", data: { "id_book": 41034, "chapter": "x9788490649626EPUB-3", "note": note, "id_mark": id_mark, "mark_type":'n', "page":page, "text":note }, cache: false, success: function(data) { // Reload page //window.location = window.location; window.location.pathname = data.url; return false; }, error: function(data) { alert("Error updating " + data.toString()); } }); e.preventDefault(); }); } } }); } } // Create the modal backdrop on document load so all modal tooltips can use it $('<div id="qtip-blanket">').css({ position: 'absolute', top: 0, left: 0, height: $(document).height(), // Span the full document height... width: '100%', // ...and full width opacity: 0.5, // Make it slightly transparent backgroundColor: 'black', zIndex: 5000 // Make sure the zIndex is below 6000 to keep it below tooltips! }).appendTo(document.body) // Append to the document body .hide(); // Hide it initially // ================= Text selection ============================= function zeroFill(number, width) { width -= number.toString().length; if ( width > 0 ) { return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number; } return number; } function getLengthOfNode(node) { var retval = 0; var aux = node; while (aux = aux.previousSibling) { if (aux.nodeValue) { retval += aux.nodeValue.length; if(aux.nodeName == 'SPAN'){ alert('entra'); } } else { //retval += $(aux).outerHTML().length; if((aux.nodeName == 'SPAN') && (aux.className == 'highlight')){ retval += aux.outerText.length; }else{ retval += $(aux).outerHTML().length; } } } return retval; } function getSelectedText() { var selInitParents = Array(); var selEndParents = Array(); var selRangeParents = Array(); var iframe = document.getElementById("book_ifr"); var win = iframe.contentWindow; var doc = iframe.contentDocument || win.document; var selections = win.getSelection(); var text = ""; // Iterate over selections for (x=0; x<selections.rangeCount; x++) { var selection = selections.getRangeAt(x); // Determine real position of text var offset = selection.startOffset + getLengthOfNode(selection.startContainer); selInitParents.push(zeroFill(offset, SEL_LEN)); if (selection.startContainer.previousSibling) { selInitParents.push(zeroFill(0, SEL_LEN)); } else { selInitParents.push(zeroFill($(selection.startContainer).prevAll().length, SEL_LEN)); } var offset = selection.endOffset + getLengthOfNode(selection.endContainer);; selEndParents.push(zeroFill(offset, SEL_LEN)); if (selection.endContainer.previousSibling) { selEndParents.push(zeroFill(0, SEL_LEN)); } else { selEndParents.push(zeroFill($(selection.endContainer).prevAll().length, SEL_LEN)); } $(selection.startContainer).parents().each(function() { // MODIFIED // var entryposition = $(this).prevAll().length; var entryposition = $(this).prevAll().not('.highlight').length; selInitParents.push(zeroFill(entryposition, SEL_LEN)); }); $(selection.endContainer).parents().each(function() { // MODIFIED // var entryposition = $(this).prevAll().length; var entryposition = $(this).prevAll().not('.highlight').length; selEndParents.push(zeroFill(entryposition, SEL_LEN)); }); // Insert range selInitParents.reverse(); var selInitString = selInitParents.join(">"); selEndParents.reverse(); var selEndString = selEndParents.join(">"); var selRangeString = selInitString + "," + selEndString; var retval = new Array(); retval['level'] = selRangeString; retval['text'] = selection; return retval; } } // Function to capture selection coords using DOM navigation $(".getSelectedText").click(function() { return getSelectedText(); }); $(".highlight", book).css('background', '#ff0').css('border', '1px solid #aa0').css('border-radius', '5px').css('-moz-border-radius', '5px'); $(".notesmark", book).css('background', 'url("/media/img/icons/icon_notepad2.png")').css('width','15px').css('height','15px').css('display','inline-block'); switch(current_mode){ case 'night': displayMode('night'); break; case 'sepia': displayMode('sepia'); break; case 'grey': displayMode('grey'); break; default: break; } /* switch(current_mode){ case 'day': displayMode(modes.day); break; case 'night': displayMode(modes.night); break; case 'sepia': displayMode(modes.sepia); break; case 'grey': displayMode(modes.grey); break; default: displayMode(modes.day); break; } */ // ==================== Bookmark ======================== function getBookmarkedPages(chapter, bookmarks){ var bookmarked = new Array(); if(bookmarks[chapter]){ var doc = document.getElementById('book_ifr').contentDocument; $.each(bookmarks[chapter], function(index, el){ bookmarked.push({ bookmark: el, page: getPageByNode($(doc.body).width(), getNodeFromCoord(el.coord)) }); }); } var aux = ''; return bookmarked; } function isBookmarked(bookmarks){ var b = getBookmarkedPages('x9788490649626EPUB-3', bookmarks); var current = getCurrentPage()-1; if(b.length > 0){ var page = false; var element = null; $.each(b, function(index, el){ if(el.page == current){ page = true; element = el; } }); if(page){ deleteBookmark(current, element.bookmark.id); $('.bookmark_icon_big').attr({'src':'/media/img/reader/icons/buttons/bookmark2.png', 'title':'Unmark'}); }else{ bookmarkPage(current); $('.bookmark_icon').attr({'src':'/media/img/reader/icons/buttons/bookmark.png', 'title':'Mark'}); } }else{ bookmarkPage(current); } } function bookmarkPage(page_number){ $('.bookmark_icon_big').unbind('click').attr('class', 'bookmark_icon'); $('.bookmark_icon').unbind('click').bind('click', function(e){ var page = page_number; var doc = document.getElementById('book_ifr').contentDocument; var pos = $(document.getElementById('book_ifr').contentWindow).scrollLeft(); var coord = getCoordFromNode(getFirstNodeOfPage(doc.body, pos),0); // alert($(getFirstNodeOfPage(doc.body, pos).previousSibling).text()); var data = { "id_book": 41034, "chapter": "x9788490649626EPUB-3", "coords": coord, "mark_type":'b', "page":page }; $.ajax({ type: 'POST', url: '/mark/add/', data: data, cache: false, success: function(d){ //bookmarks[data.chapter].push({ coord: data.coords, id:d.mark_id , chapter: data.chapter, page: data.page }); //isBookmarked(bookmarks); if(window.location.pathname != d.url) window.location.pathname = d.url; else window.location.reload(); return false; }, error: function(){alert('fail')} }); }); } function deleteBookmark(page_number, bookmark_id){ $('.bookmark_icon').unbind('click'); $('.bookmark_icon').attr('class', 'bookmark_icon_big'); $('.bookmark_icon_big').unbind('click'); $('.bookmark_icon_big').bind('click',function(e){ var id_mark = bookmark_id; var type = 'b'; var page = page_number; // Delete mark $.ajax({ type: 'POST', url: "/mark/delete/", data: { "id_mark": id_mark, "mark_type":type, "page":page, "id_book": 41034, "chapter": "x9788490649626EPUB-3" }, cache: false, success: function(d) { //window.location = window.location; window.location.hash = ''; if(window.location.pathname != d.url) window.location.pathname = d.url; else window.location.reload(); return false; }, error: function(data) { //alert("Error deleting " + data.toString()); } }); }); } // ==================== Search highlighting and go to results ============================== function showSearchHighlights() { var search_coords = ""; search_coords = search_coords.split(',')[0]; var search_text = ""; // Highlight search text if (search_text!="") { // $(book).highlight(search_text); doHighlight(book[0], 'highlight highlight_search', search_text); } // Go to page if there are search_coords selected if ((search_coords!="") && (!beginsWith("-", search_coords)) && (!beginsWith("+", search_coords)) && (!beginsWith("_", search_coords))) { //var node = getNodeFromCoord(search_coords); //var page = parseInt(1 + $(node).position().left / book.width()); var node = getNodeFromCoord(search_coords); var page = getPageByNode($(doc.body).width(), node); page = page + 1; scrollToPage(page); calculatePages(); } if ((search_coords!="") && beginsWith("_", search_coords)) { var node = getElementFromCoord(search_coords.substring(1)); var page = getPageByNode($(doc.body).width(), node); page = page + 1; scrollToPage(page); calculatePages(); } var num_pages = parseInt(iframe.width() / book.width()); if (beginsWith("-", search_coords)) { if (search_coords.length == 1) { num_page = num_pages; } else { num_page = num_pages - parseInt(search_coords.substring(1)); } if (num_page < 0) { num_page = 0; } scrollToPage(num_page); calculatePages(); } if (beginsWith("+", search_coords)) { if (search_coords.length == 1) { num_page = 0; } else { num_page = parseInt(search_coords.substring(1)); } if (num_page > num_pages) { num_page = num_pages; } scrollToPage(num_page + 1); calculatePages(); } $(".highlight_search", book).css('background', '#ccf').css('border', '1px solid #77f').css('border-radius', '5px').css('-moz-border-radius', '5px'); } // ==================== Contextual menu ========================= // New note var text = "<form id='frmNotes' method='post'>" + "<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='a9391c6945f1c3a6872df0c5a823e34f' /></div>" + "<textarea class='notes_textarea' id='notes_textarea'></textarea><br /><br />" + /* "<input type='checkbox' name='chkShare' class='chkShare' /> Share<br /><br />" +*/ "<input type='submit' style='background-color: #965ddc;' name='btnPostMark' class='btnPostMark' id='btnPostMark' value='Save' />" + "</form>"; $("#newNote").qtip({ content: { title: { text: 'Insert note', //button: 'Close' button: 'X' }, text: text, }, position: { //target: $(document.body), target: $(".fullscreen-wrapper"), corner: 'center' }, show: { when: 'click', solo: true }, hide: false, style: { width: 500, padding: '14px', border: { width: 2, radius: 2, color: '#666666' }, name: 'light' }, api: { beforeShow: function() { // Fade in the modal "blanket" using the defined show speed $('#qtip-blanket').fadeIn(this.options.show.effect.length); }, beforeHide: function() { // Fade out the modal "blanket" using the defined hide speed $('#qtip-blanket').fadeOut(this.options.hide.effect.length); }, onShow: function() { // Add btnPostMark controller $(".btnPostMark").on('click', function(e) { var id_book = 41034; var chapter = "x9788490649626EPUB-3"; var sel = getUserSelection(); var co = getCoordFromNode(sel['range'].startContainer,sel['range'].startOffset); var coord_end = getCoordFromNode(sel['range'].endContainer,sel['range'].endOffset); coords = co+','+coord_end; var text = sel['text']; var page = getCurrentPage(); var note = escape($("#notes_textarea").val()); var data = { "note":note, "id_book":id_book, "chapter":chapter, "mark_type":'n', "coords":coords, "text":text , "page":page}; // Add mark $.ajax({ type: 'POST', url: "/mark/add/", data: data, cache: false, success: function(data) { // Reload page if(window.location.pathname != data.url) window.location.pathname = data.url; else window.location.reload(); return false; }, error: function(data) { window.location.reload(); alert("Error posting " + data.toString()); } }); e.preventDefault(); }); } } }); isBookmarked(bookmarks); $(book).click(function(){ $('#ctxMenu').hide(); hideSubmenu() }); $(".fullscreen-wrapper").click(function(){ $('#ctxMenu').hide(); hideSubmenu(); }); $("#navigation").click(function(){ $('#ctxMenu').hide(); hideSubmenu(); }); function hideSubmenu() { if ($('#nav-sub').width() == 400) { // Tabs style $("#nav-sub").animate({width:'400px'}).animate({width:'0'},'400', function(){ $(this).find('.submenu').hide(); // Fix for IE7, not hiding form elements $('#nav-main-navigation .small-notification').fadeIn('fast'); } ); $('.nav-main-subnav').removeClass('active'); } else if ($('#nav-sub').height() == 370) { $("#nav-sub").animate({height:'370px'}).animate({height:'0'},'370', function(){ $(this).find('.submenu').hide(); // Fix for IE7, not hiding form elements $('#nav-main-navigation .small-notification').fadeIn('fast'); } ); $('.nav-main-subnav').removeClass('active'); $(".menu_tri").fadeOut(); } } $(book).contextMenu({ menu: 'ctxMenu', book_iframe: $("#book_ifr"), iframe: iframe, }, function(action, el, pos) { if (action == "ctxHighlight") { var usersel = getUserSelection(); var coord = getCoordFromNode(usersel['range'].startContainer,usersel['range'].startOffset); var coord_end = getCoordFromNode(usersel['range'].endContainer,usersel['range'].endOffset); var page = getCurrentPage(); // Post mark //var parameters = { "id_book": 41034, "chapter": "x9788490649626EPUB-3", "coords": sel['level'].toString(), "note":sel['text'].toString(), "text":sel['text'].toString() }; var parameters = { "id_book": 41034, "chapter": "x9788490649626EPUB-3", "coords": coord+','+coord_end, "note":usersel['text'], "text":usersel['text'], "mark_type":'h', "page":page }; $.ajax({ type: 'POST', url: "/mark/add/", data: parameters, cache: false, success: function(data) { // Reload page if(window.location.pathname != data.url) window.location.pathname = data.url; else window.location.reload(); return false; }, error: function(data) { window.location.reload(); alert("Error highlighting: " + data); } }); } else if (action == "ctxNote") { var text = getUserSelection()["text"]; $('#newNote').trigger("click"); } else if (action == "ctxWikipedia") { var sel = getSelectedText(); if (sel['text'] != "") { window.open(lan.wikipedia + encodeURIComponent(sel['text'])); }else{ alert('Please, select text'); } } else if (action == "ctxDictionary") { var sel = getSelectedText(); var text = escape(sel['text'].toString()); if (text != "") { window.open(lan.dictionary + text); }else{ alert('Please, select text'); } } else if (action == "ctxFacebook") { var sel = getSelectedText(); var text = sel['text'].toString(); text = text.replace(/(\r\n|\n|\r)/gm,""); if (text != "") { url = "https://www.facebook.com/dialog/feed?app_id=1408471595872439" + "&link=" + encodeURIComponent("https://www.amabook.es/catalogo/editorial-uoc-s-l/seo-introduccion-a-la-disciplina-del-posicionamiento-en-buscadores ")+ "&name=" + encodeURIComponent('') + "&caption=" + encodeURIComponent('Shared from Amabook España 4.0') + "&description=" + encodeURIComponent(text) + "&message=" + encodeURIComponent(text) + "&redirect_uri=https://www.facebook.com"; window.open(url); }else{ alert('Please, select text'); } } else if (action == "ctxTwitter") { var sel = getSelectedText(); if (sel['text'] != "") { window.open("http://twitter.com/home?status=" +'"'+sel['text']+'" Read on SEO. Introducción a la disciplina del posicionamiento en buscadores '+ encodeURIComponent("https://www.amabook.es/catalogo/editorial-uoc-s-l/seo-introduccion-a-la-disciplina-del-posicionamiento-en-buscadores ")); }else{ alert('Please, select text'); } } else if (action == "ctxLinkedin") { var sel = getSelectedText(); if(sel['text'] != ""){ window.open("http://www.linkedin.com/shareArticle?mini=true&url="+ encodeURIComponent("https://www.amabook.es/catalogo/editorial-uoc-s-l/seo-introduccion-a-la-disciplina-del-posicionamiento-en-buscadores")+ "&title="+'Read on "SEO. Introducción a la disciplina del posicionamiento en buscadores"'+ "&summary="+sel['text'] ); }else{ alert('Please, select text'); } } else if (action == "ctxQuieroleer") { var sel = getSelectedText(); if(sel['text'] != ""){ //window.open("http://lector.amabook.es/share_quieroleer?id=41034"+"&text="+encodeURI('"'+sel['text']+'"')); window.open("/share_quieroleer" + "?id=41034"+"&text="+encodeURI('"'+sel['text']+'"')); }else{ alert('Please, select text'); } } } ); $("#scroll-pane-toc").jScrollPane(); setTimeout( showSearchHighlights, 300); setTimeout(function(){ isBookmarked(bookmarks);},300); setTimeout(function(){ if(window.location.hash.split('/')[0] != ''){ /* var target = $(iframeBody).find(window.location.hash.split('/')[0]).position().left; var offset = target % $(iframeBody).width(); $('#book_ifr').contents().scrollLeft(target - offset);*/ if($(iframeBody).find(window.location.hash.split('/')[0]).is('div')){ var t = $(iframeBody).find(window.location.hash.split('/')[0]).children(':first'); var t1 = Math.ceil($(t).position().left); var o = t1 % $(iframeBody).width(); $('#book_ifr').contents().scrollLeft(t1); }else{ var target = Math.ceil($(iframeBody).find(window.location.hash.split('/')[0]).position().left); var offset = target % $(iframeBody).width(); //console.log(target); $('#book_ifr').contents().scrollLeft(target - offset); } } $('#loader').hide(); $('#iframe_container').css('visibility','visible'); $('.arrow_forward,.arrow_back,.arrow').css('visibility','visible'); //pageIcoShow(); }, 500); }); }); setTimeout(function(){ $('#loader').hide(); $('#iframe_container').css('visibility','visible'); $('.arrow_forward,.arrow_back,.arrow').css('visibility','visible'); //pageIcoShow(); }, 5000); function adjustSVGSize() { var iframe = $("iframe"); iframe.contents().find("svg").each(function() { var _percentage = $(this).attr("height").slice(0, -1) / 100; $(this).height(_percentage * iframe.height()); }); } $(window).resize(function() { adjustSVGSize(); }); </script> </section> </section> </section> </section> <!--<script src="/media/js/reader_t/jquery/jquery.adminmenu.js"></script>--> <script type="text/javascript" src="/media/js/reader_t/jquery/jquery.adminmenu.min.js"></script> <!--<script src="/media/js/reader/libs/selectivizr.js"></script> <script src="/media/js/reader/jquery/jquery.visualize.js"></script> <script src="/media/js/reader/jquery/jquery.visualize.tooltip.js"></script> <script src="/media/js/reader/jquery/jquery.tipsy.js"></script> <script src="/media/js/reader/jquery/jquery.nyromodal.min.js"></script> <script src="/media/js/reader/jquery/jquery.ui.totop.js"></script> <script src="/media/js/reader/jquery/jquery.snippet.js"></script> <script src="/media/js/jquery.mousewheel.js"></script> <script src="/media/js/jquery.jscrollpane.min.js"></script> <script src="/media/js/reader/jquery.fullscreen.js"></script> <script src="/media/js/reader/script.js"></script>--> <script type="text/javascript" src="/media/js/reader/minified/all.min.js"></script> <script>!window.jQuery && document.write(unescape('%3Cscript src="/media/js/reader/jquery-1.7.1.min.js"%3E%3C/script%3E'))</script> <!--<script>!window.jQuery && document.write(unescape('%3Cscript src="/media/js/reader/jquery-1.7.1.min.js"%3E%3C/script%3E'))</script>--> <script type="text/javascript"> $(document).ready(function(){ if (!(fullScreenOn())) { $("#scroll-pane-toc").jScrollPane(); $("#scroll-pane-marks").jScrollPane(); } if($.support.fullscreen){ $('#fullscreen').toggle(true); $('#fullscreen').click(function(e){ // Use the plugin var background_color = $("body").css('background-color'); $('.fullscreen-wrapper').fullScreen({ 'background':background_color }); e.preventDefault(); if (fullScreenOn()) { $('#fullscreen span').text('v'); } else { $('#fullscreen span').text('u'); } }); } function fullScreenOn(){ return document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen; } }); </script> </body> </html>