// Variables a utilizar en las funciones futuras // Url de las paginas generadas por netsuite, para obtener los items var pagesLinks = new Array(); var allItems = new Array(); var itemsToShow = new Array(); // Filtros var filters = new Array(); var currentFilter = new Object(); var filtersApplied = new Array(); var sortApplied = ''; // Variables para el paginador var itemsPerPage = null; var pagesNum = null; var nsPagesNum = null; var totalItems = null; var currentPage = 0; var pages = new Array(); function getShowingFirstItem() { return showingFirstItem; } function getShowingLastItem() { return showingLastItem; } function getTotalItems() { return itemsToShow.length; } function setCallBack() { if(narr_callback) { narr_callback(); } } var errors = new Array(); // Ejecuta los procesos function startProcess() { try { // Inicializo las variables _initVars(); // Creo el layout de items _createLayout(); // Obtengo los items _getItems(); // Genero la lista de items a mostrar generateItemsToShowList(); } catch(e) { setTimeout(startProcess, 100); } } // Inicializa los valores necesarios para los procesos function _initVars() { pagesLinks = _getPagesLinks(_getPaginationBox()); totalItems = _getTotalItems(); if(!itemsPerPage) itemsPerPage = (dftItemsPerPage && dftItemsPerPage != 0)?dftItemsPerPage:totalItems; rowsNum = Math.ceil(itemsPerPage / colsNum); pagesNum = Math.ceil(totalItems / itemsPerPage); } // Genera el layout para colocar los items y los paginadores function _createLayout() { var itemsContainerBox = document.getElementById(itemsContainer); document.sc_clearElement(itemsContainerBox); var bodyItemsLayout = document.sc_createElement('table','table_itemsLayout',null); if(tableWidth && tableWidth != '') { bodyItemsLayout.setAttribute('width',tableWidth); } if(tableAlign && tableAlign != '') { bodyItemsLayout.setAttribute('align',tableAlign); } if(pagesPosition == 'both' || pagesPosition == 'top') { var pagesBarThead = document.sc_createElement('thead','thead_pagesBar',null); var pagesBarTR = document.sc_createElement('tr','tr_pagesBar',null); var pagesBarTD = document.sc_createElement('td','td_pagesBar',null); pagesBarTD.setAttribute('colSpan',colsNum); pagesBarTR.appendChild(pagesBarTD); pagesBarThead.appendChild(pagesBarTR); bodyItemsLayout.appendChild(pagesBarThead); } var itemsTable = document.sc_createElement('tbody','tbody_itemsLayout','tbody_itemsLayout'); var itemsTableInner = document.sc_createElement('div','itemsLayout','itemsLayout'); itemsTable.appendChild(itemsTableInner); bodyItemsLayout.appendChild(itemsTable); if(pagesPosition == 'both' || pagesPosition == 'bottom') { var pagesBarTfoot = document.sc_createElement('tfoot','tfoot_pagesBar',null); var pagesBarTR = document.sc_createElement('tr','tr_pagesBar'); var pagesBarTD = document.sc_createElement('td','td_pagesBar',null); pagesBarTD.setAttribute('colSpan',colsNum); pagesBarTR.appendChild(pagesBarTD); pagesBarTfoot.appendChild(pagesBarTR); bodyItemsLayout.appendChild(pagesBarTfoot); } itemsContainerBox.appendChild(bodyItemsLayout); } // Recorre las paginas de netsuite y obtiene los items de cada una function _getItems() { var tempNetsuitePages = pagesLinks.length; for(var i = 0; i < tempNetsuitePages; i++) { _getItemsFromUrl(pagesLinks[i]); } } // Recibe una url de netsuite y hace un pedido a la misma retornando el html de esta con los items function _getItemsFromUrl(urlStr) { var response = null; var ret = false; var req = AJAXObject(); req.onreadystatechange = function() { if(req.readyState == 4) { _parseItems(req.responseText,urlStr); } else { loadingProcess('Loading...'); } } req.open('GET',urlStr); req.send(null); } var pageProcesed = 0; // Parseador de los items recibidos // Proceso todos los items uno por uno creando un objeto de cada uno y guardandolos en el array de items allItems function _parseItems(html,urlStr) { // Guardo la variable html en un contenedor de xmlstring mio var xmlstring = html; // parseo xmlstring quedandome solo con la etiqueta body var scriptTagRegExp = /]*>([\x00-\x7F]*?)<\/script>/gi; var styleTagRegExp = /]*>([\x00-\x7F]*?)<\/style>/gi; xmlstring = xmlstring.replace(scriptTagRegExp,''); xmlstring = xmlstring.replace(styleTagRegExp,''); html = xmlstring; // Agarro del html recibido las cadenas de configuracion de los items var itemsConfig = new Array(); var itemConfigPatern = /\[\!([^\[\]])*\]/gi; itemsConfig = html.match(itemConfigPatern); if(itemsConfig) { var currentItem = { id : null, fields : new Array(), html : null } // Recorro todos los items var itemsNum = itemsConfig.length; itemsNum == 1; for(var i = 0; i < itemsNum; i++) { // Reinicio currentItem currentItem = { id : null, fields : new Object(), html : null } // Purifico la cadena del item, quitando los marcadores var tempItem = itemsConfig[i].replace('[!',''); tempItem = tempItem.replace(']',''); // Recorro todos los campos del item actual var tempItemParts = tempItem.split(fieldsSeparator); if(tempItemParts) { // Guardo el id currentItem.id = (tempItemParts[0])?tempItemParts[0]:null; // Si el id del item actual es valido continuo con el proceso // de lo contrario paso al siguiente item if(currentItem.id) { // Obtengo el html del item actual a partir de la siguiente expresion var itemTagRegExp = new RegExp("]*id=(\"|\')containerItem_" + currentItem.id + "(\"|\')[^>]*>([\x00-\x7F]*?)<\/c:item>","gi"); while(html.indexOf('º') != -1) { html = html.replace('º',''); } if(html.match(itemTagRegExp)) { if(html.match(itemTagRegExp).length > 0) { var itemHTML = html.match(itemTagRegExp)[0]; itemHTML = (parseLogic(itemHTML))?parseLogic(itemHTML):itemHTML; } else { var itemHTML = 'HTML Error in item'; } } else { var itemHTML = 'HTML Error in item'; } // Guardo el html del item actual en la propiedad html del currentItem currentItem.html = (itemHTML)?itemHTML:''; var itemPartsNum = tempItemParts.length; for(var p = 1; p < itemPartsNum; p++) { // separo las propiedades del campo y creo un currentField para agregar al currentItem var tempFieldParts = tempItemParts[p].split(fieldValuesSeparator); if(tempFieldParts) { // Creo el currentField en forma dinamica var currentFieldStr = ''; currentFieldStr += 'currentItem.fields.' + tempFieldParts[0] + ' = {'; // Recorro las partes del field y las agrego al currentField var fieldPartsNum = tempFieldParts.length; for(var f = 1; f < fieldPartsNum; f++) { var partName = ''; switch(f) { case 1: partName = 'value'; break; case 2: partName = 'type'; break; } if(partName == 'type' && tempFieldParts[f].indexOf('money') != -1) { var typeTempParts = tempFieldParts[f].split(','); var tempType = typeTempParts[0]; var tempCurrency = typeTempParts[1]; currentFieldStr += 'type : \'' + tempType + '\','; currentFieldStr += 'currency : \'' + tempCurrency + '\','; } else { var tempFieldPartParsed = tempFieldParts[f]; while(tempFieldPartParsed.match(/<[^>]*>[\x00-\x7F]*<\/[a-z]*>/gi)) { tempFieldPartParsed = tempFieldPartParsed.replace(/<[^>]*>[\x00-\x7F]*<\/[a-z]*>/gi,''); } currentFieldStr += partName + ' : \'' + tempFieldPartParsed + '\','; } } currentFieldStr += '};'; currentFieldStr = currentFieldStr.replace(',};','};'); eval(currentFieldStr); } } allItems.push(currentItem); if(!dftItemsPerPage || dftItemsPerPage == 0) { //alert(dftItemsPerPage); itemsPerPage = 0; //dftItemsPerPage = 0; itemsPerPage = allItems.length; //dftItemsPerPage = allItems.length; } _changeItemsPerPage(itemsPerPage) //drawItems(); } else { continue; } } else { continue; } } _createFilters(); _applyFilters(); showFiltersControls(); showPage(0); if(showPerPageSelect) { getChangeItemsPerPageControlHTML(); } } else { return; } } // Reemplaza funciones logicas por sus respectivos resultados function parseLogic(tHtml) { var functionIfReg = new RegExp("IF\\(.*\[@].*\[@].*[^\\)][^\\}]\\)","gi"); try { while(tHtml.match(functionIfReg)) { if(tHtml.match(functionIfReg)[0]) { var currentIf = tHtml.match(functionIfReg)[0]; var tempCurrentIf = currentIf; tempCurrentIf = tempCurrentIf.replace('IF(',''); tempCurrentIf = tempCurrentIf.replace(')',''); var tempIfParts = tempCurrentIf.split('[@]'); var ifCondition = tempIfParts[0]; if(tempIfParts[1]) ifTrueValue = tempIfParts[1]; else return; if(tempIfParts[2]) ifFalseValue = tempIfParts[2]; else return; // Limpio la condicion de etiquetas si las tiene while(ifCondition.match(/<[^>]*>[\x00-\x7F]*<\/[a-z]*>/gi)) { ifCondition = ifCondition.replace(/<[^>]*>[\x00-\x7F]*<\/[a-z]*>/gi,''); } var processLogic = false; try { eval(ifCondition); processLogic = true; } catch(e) {} while(ifFalseValue.indexOf(')') == (ifFalseValue.length - 1)) { ifFalseValue = ifFalseValue.substring(0,ifFalseValue.length - 1); } while(ifTrueValue.indexOf(')') == (ifTrueValue.length - 1)) { ifTrueValue = ifTrueValue.substring(0,ifTrueValue.length - 1); } if(processLogic) { if(eval(ifCondition)) { if(ifTrueValue.indexOf('Error processing') != -1) { tHtml = tHtml.replace(currentIf,ifFalseValue); } else { tHtml = tHtml.replace(currentIf,ifTrueValue); } } else { tHtml = tHtml.replace(currentIf,ifFalseValue); } } else { if(ifFalseValue.indexOf('[Error processing') != -1) ifFalseValue = ''; tHtml = tHtml.replace(currentIf,ifFalseValue); } } else return; } var parserSyntax = new RegExp("\{![^\}]*\}","gi"); while(tHtml.match(parserSyntax)) { var currentVar = tHtml.match(parserSyntax)[0]; var cleanerVar = currentVar.replace('{!',''); cleanerVar = cleanerVar.replace('}',''); while(cleanerVar.indexOf('\'') != -1) { cleanerVar = cleanerVar.replace('\'',''); } tHtml = tHtml.replace(currentVar,cleanerVar); } return(tHtml); } catch(e) { errors.push(e); } } // Cambia la cantidad de items que se ven por pagina function _changeItemsPerPage(itemsNum) { itemsPerPage = itemsNum; rowsNum = Math.ceil(itemsNum / colsNum); var toPage = 0; showPage(toPage); if(showPerPageSelect) { getChangeItemsPerPageControlHTML(); } } function getChangeItemsPerPageControlHTML() { var changeSelectHTML = ''; if(cppSteps == 'all' || !isNaN(cppSteps)) { cppSteps = Math.ceil(totalItems / cppStepBy); } changeSelectHTML += 'Per pages: '; changeSelectHTML += ''; changePerPageContainer = _getElementsByClass('perPageControlBox'); if(changePerPageContainer) { for(var pp in changePerPageContainer) { changePerPageContainer[pp].innerHTML = changeSelectHTML; } } } // Retorna una coleccion con las url de las paginas de netsuite function _getPagesLinks(obj) { var pagesLinks = new Array(); if(obj) { as = obj.getElementsByTagName('a'); nsPagesNum = as.length; for(var i in as) { if(as[i].innerHTML) { //alert(as[i].innerHTML); if(as[i].innerHTML.match(/^[0-9]*/i) != '') { if(as[i].href.match(/range=[0-9]*,[0-9]*,[0-9]*/i)) { // Quito el rango actual de esta url para generar las proximas urls var tempUrl = as[i].href.replace(/range=[0-9]*,[0-9]*,[0-9]*/i,'[!range]'); // Me quedo con el rango actual de la url, para obtener los pasos y poder calcular el resto de urls var tempRange = as[i].href.match(/range=[0-9]*,[0-9]*,[0-9]*/i); // Separo el string que es de tipo range=from,to,of y me quedo con los valores from,to,of respectivamente var partsOfRange = tempRange[0].split('=')[1].split(','); // Separo los valores y los guardo en variables para trabajar var tempFrom = partsOfRange[0]; var tempTo = partsOfRange[1]; var tempOf = partsOfRange[2]; if(dftItemsPerPage && dftItemsPerPage != '' && dftItemsPerPage != 0) { itemsPerPage = dftItemsPerPage; } else { itemsPerPage = (parseInt(tempTo) - parseInt(tempFrom) + 1); } // Obtengo los items por pagina segun netsuite a partir del rango var tempItemsPerPage = (parseInt(tempTo) - parseInt(tempFrom)) + 1; // Obtengo la cantidad de paginas segun netsuite de la cuenta Cantidad de items total divido los items por pagina y redondeando hacia arriba var tempPagesFromNetsuite = Math.ceil(tempOf / tempItemsPerPage); // Acumulador que guarda los items para cada pagina var itemsFrom = 0; // Genero las url para la cantidad de paginas for(var page = 1; page <= tempPagesFromNetsuite; page++) { // Genero el parametro range para la url actual var actualRange = 'range=' + (((page * tempItemsPerPage) - tempItemsPerPage) + 1) + ',' + (((page * tempItemsPerPage) < tempOf)?(page * tempItemsPerPage):tempOf) + ',' + tempOf; // Incremento itemsFrom en la cantidad de items por pagina itemsFrom += tempItemsPerPage; // Agrego la url generada a pagesLinks pagesLinks.push(tempUrl.replace('[!range]',actualRange)); } break; } } } } } else { nsPagesNum = 0; pagesLinks.push(document.location); } return pagesLinks; } // Retorna el total de items segun el paginador de netsuite function _getTotalItems() { if(_getPaginationBox()) var tempTotal = _getPaginationBox().innerHTML.match(/of [0-9]{1,4}/i); else { if(totalItems && totalItems != 0) return totalItems; else { var bodyExist = false; while(!bodyExist) { if(document.getElementsByTagName('body')) bodyExist = true; } if(bodyExist) { if(document.getElementsByTagName('body')[0]) var html = document.getElementsByTagName('body')[0].innerHTML; else return 0; var itemConfigPatern = /\[\!([^\[\]]*)\]/gi; itemsConfig = html.match(itemConfigPatern); if(itemsConfig) return itemsConfig.length; else return 0; } else return 0; } } if(tempTotal) return parseInt(tempTotal[0].match(/[0-9]{1,4}/i)); else return 0; } // Retorna el elemento html que contiene el paginador de netsuite function _getPaginationBox() { try { var tds = document.getElementsByTagName("td"); for (var i=0; i parseFloat(endsVariant.minimum)) { if(endsVariant.maximum != -1 && (parseFloat(currentFieldValue) < parseFloat(endsVariant.maximum))) { filters[f].variants[variant].push(itemsToShow[it]); } else if(endsVariant.maximum == -1) { filters[f].variants[variant].push(itemsToShow[it]); } } break; default: break; } } // Si el filtro es del tipo string, comparo la variante con el valor del campo del item, y si aplica // agrego el item al array de items de esa variante else if(filters[f].type == 'string') { if(currentItemFields[cField].value == variant) { filters[f].variants[variant].push(itemsToShow[it]); } } // Si el filtro es del tipo boolean, verifico el campo del item, y si aplica a la variante actual // agrego el item al array de items de esa variante else if(filters[f].type == 'boolean') { switch(variant) { case 'areTrue': if(currentItemFields[cField].value == 'Yes') { filters[f].variants[variant].push(itemsToShow[it]); } break; case 'areFalse': if(currentItemFields[cField].value == 'No') { filters[f].variants[variant].push(itemsToShow[it]); } break; } } } } } } } } } else return; showPage(0); } // Resetea los filtros, solo se debe usar si se van a aplicar los filtros denuevo, ya que si no se acumulan los items function resetFilters() { if(filtersContainer && filtersContainer != '') { // Recorro los filtros var filtersLength = filters.length; for(var f = 0; f < filtersLength; f++) { // Recorro las variantes for(var cVariant in filters[f].variants) { // Renuevo el array a cero filters[f].variants[cVariant] = new Array(); } } } else return; } // Resetea los filtros aplicados, en definitiva, quita todos los filtros y deja todos los items sin filtrar function resetAppliedFilters() { if(filtersContainer && filtersContainer != '') { filtersApplied = new Array(); itemsToShow = allItems; } } // Reaplica y redibuja los filtros function reapplyFilters() { if(filtersContainer && filtersContainer != '') { var filtersAppliedLength = filtersApplied.length; for(var fa = 0; fa < filtersAppliedLength; fa++) { if(filtersApplied[fa]) { var currentFilter = filtersApplied[fa]; applyFilter('!' + currentFilter.split(':')[0]); applyFilter(currentFilter); } } showFiltersControls(); if(itemsPerPage > itemsToShow.length) { itemsPerPage = itemsToShow.length; } else { if(document.getElementById('narr_changeItemsPerPage')) { if((parseInt(document.getElementById('narr_changeItemsPerPage').value) % cppStepBy) != 0) { itemsPerPage = itemsToShow.length; } else { itemsPerPage = document.getElementById('narr_changeItemsPerPage').value; } } else { itemsPerPage = (dftItemsPerPage && dftItemsPerPage != 0)?dftItemsPerPage:allItems.length; } } if(showPerPageSelect) { getChangeItemsPerPageControlHTML(); } _changeItemsPerPage(itemsPerPage) } } // Aplica el filtro especificado y genera la lista de items a mostrar segun los filtros aplicados function applyFilter(filterField) { // Obtengo del filtro el nombre y la variante solicitada var requestedFilter = filterField.split(':'); var reqFilterName, reqFilterVariant; if(requestedFilter.length > 1) { reqFilterName = requestedFilter[0]; reqFilterVariant = requestedFilter[1]; if(reqFilterName.indexOf('!') != -1) { if(!reqFilterVariant || reqFilterVariant == '') { alert('You must specify a valid variant for the specified filter'); return; } } } else { reqFilterName = filterField; if(reqFilterName.indexOf('!') == -1) { alert('You must specify a variant for the specified filter'); return; } } // Recorro la lista de filtros if(reqFilterName && reqFilterName != '') { var removeFilter = false; var filtersLength = filters.length; for(var i = 0; i < filtersLength; i++) { // Si tengo el parametro que indica que debo remover if(reqFilterName.indexOf('!') != -1) { removeFilter = true; filterField = filterField.replace('!',''); reqFilterName = reqFilterName.replace('!',''); } // Si el filtro actual es el filtro que recibe por parametro if(filters[i].field == reqFilterName) { // Recorro los filtros aplicados y verifico que no este var aplyFilter = true; var filtersAppliedLength = filtersApplied.length; for(var j = 0; j < filtersAppliedLength; j++) { if(removeFilter) aplyFilter = false; if(filtersApplied[j]) { if(filtersApplied[j].indexOf(filterField) != -1) { aplyFilter = false; if(removeFilter) { filtersApplied[j] = null; } else { alert('The filter that tries to apply is already applied'); } break; } else if(removeFilter) { aplyFilter = false; } else if(filtersApplied[j]) { if(filtersApplied[j].indexOf(reqFilterName) != -1) { aplyFilter = false; alert('The filter that tries to apply is already applied'); } } } } // Si aplyFilter es verdadero, procedo a verificar las variantes if(aplyFilter) { // Verifico las variantes de este filtro a ver si la especificada es valida var varDontExist = true; for(var cVariant in filters[i].variants) { if(cVariant == reqFilterVariant) { varDontExist = false; } } if(varDontExist && !removeFilter) { alert('The specified filter does not exist'); } if(!varDontExist) { var dontPush = false; // Al aplicar el filtro busco lugares vacios, si no lo hay lo agrego al final for(var fa = 0; fa < filtersAppliedLength; fa++) { if(!filtersApplied[fa]) { filtersApplied[fa] = filterField; dontPush = true; break; } } if(!dontPush) filtersApplied.push(filterField); } } break; } else { if(i == (filtersLength - 1)) { alert('The specified filter does not exist'); } } } } else { alert('You must specify a valid filter'); } generateItemsToShowList(); _applyFilters(); if(sortApplied && sortApplied != '') { applySorting(sortApplied) } if(showPerPageSelect) { getChangeItemsPerPageControlHTML() } } // ordena los filtros function sortFilter(filterField,inOrder,typeOrder) { // Recorro los filtros for(var cFil in filters) { // Si el filtro que recibo es el filtro actual if(filterField == filters[cFil].field) { // Creo un array de las variantes var variants = new Array(); // Recorro las variantes del filtro for(var cVar in filters[cFil].variants) { // Agrego el nombre de la variante al array de variantes variants.push(cVar); } // Si el tipo de orden es numerico if(typeOrder == 'number') { // Debo convertir todos los elementos del array a un numero for(var i_ in variants) { if(variants[i_].indexOf('_') == 0) { variants[i_] = variants[i_].substring(1,variants[i_].length); } variants[i_] = parseInt(variants[i_]); } } // Ordeno el array de variantes if(typeOrder == 'number') { variants = variants.sort( function(a,b) { return a - b } ); } else { variants = variants.sort(); } // Si el orden es descendente revierto el orden if(inOrder == 'desc') { variants = variants.reverse(); } // Creo un objeto de variantes var tempVariants = new Object(); // Recorro las variantes del filtro for(var cVar_ in filters[cFil].variants) { // Agrego la variante actual y su contenido al objeto de variantes tempVariants[cVar_] = filters[cFil].variants[cVar_]; } // Limpio las variantes del filtro filters[cFil].variants = new Object(); // Recorro el array de variantes ordenadas for(var i in variants) { if(typeOrder == 'number') { // Si el tipo es numero debo recorrer todos las variantes del ver cual coincide for(var cVar___ in tempVariants) { if(variants[i] == (parseInt((cVar___.indexOf('_')==0)?cVar___.substring(1,cVar___.length):cVar___))) { filters[cFil].variants[cVar___] = tempVariants[cVar___]; } } } else { filters[cFil].variants[variants[i]] = tempVariants[variants[i]]; } } } } showFiltersControls(); } // Genera la lista de items a mostrar segun los filtros aplicados function generateItemsToShowList() { // Tomo el total de filtros aplicados var filtersAppliedLength = filtersApplied.length; // Creo una varialbe que guarde la cantidad de filtros validos var fAppliedValidsLength = 0; // y un array que guarde los filtros validos var fAppliedValids = new Array(); // Recorro los filtros y si son validos los sumo a la variable de cantidad y los agrego al array for(var fa = 0; fa < filtersAppliedLength; fa++) { if(filtersApplied[fa]) { fAppliedValidsLength++; fAppliedValids.push(filtersApplied[fa]); } } // Si la cantidad de filtros validos son 0 debo mostrar todos los items sin filtros if(fAppliedValidsLength == 0) { // Reseteo los filtros, ya que no hay validos resetAppliedFilters(); // Asigno a los items a mostrar, todos los items itemsToShow = allItems; } else { // Si la cantidad de filtros validos aplicados es distinta de cero // Creo un array que guardara las listas de items de cada filtro aplicado var itemsFiltered = new Array(); // Voy a los filtros y obtengo las listas segun las variantes de los filtros aplicados for(var fav = 0; fav < fAppliedValidsLength; fav++) { // Guardo el nobmre del filtro var filterName = fAppliedValids[fav].split(':')[0]; // Y la variante var filterVariant = fAppliedValids[fav].split(':')[1]; // Recorro los filtros y proceso el que estoy buscando ahora (filterName) var filtersLength = filters.length; for(var fil = 0; fil < filtersLength; fil++) { // Una vez que tengo el filtro que busco if(filters[fil].field == filterName) { // Recorro las variantes en busca de la variante actual del filtro aplicado (filterVariant) for(var cVariant in filters[fil].variants) { // Una vez que llego a la variante, esta es la lista de items de el filtro aplicado if(cVariant == filterVariant) { // La guardo en el array de items filtrados (itemsFiltered) itemsFiltered.push(filters[fil].variants[cVariant]); } } } } } // Tengo en itemsFiltered todas las listas de items segun los filtros, ahora tengo // que comparar todas las listas y quedarme con los items que aparezcan en todas ellas // y esta ultima pasarla a itemsToShow // Creo una lista que va a ser la que utilice para comparar con la siguiente var listToCompare = new Array(); // Creo una lista, que va a ser la que guarde los items en comun entre todas las listas var finalList = new Array(); // Recorro las listas var itemsFilteredLength = itemsFiltered.length; // Si tengo mas de una lista, si no asigno la unica lista que tengo al itemsToShow if(itemsFilteredLength > 1) { for(var itf = 0; itf < itemsFilteredLength; itf++) { // Si estoy en la primer lista (lo que implica que lsitToCompare esta vacia y finalList tambien) agrego // la primer lista a listToCompare if(itf == 0) { listToCompare = itemsFiltered[0]; } else { // De lo contrario, quiere decir que finalList ya tiene items, que son los comunes entre la lista anterior y la actual listToCompare = new Array(); listToCompare = finalList; finalList = new Array(); } // Ya tengo items en listToCompare, ahora recorro todos estos items y los comparo con los de la lista siguiente, si hay lista siguiente if(itf < (itemsFilteredLength - 1)) { // Recorro los items de listToCompare var listToCompareLength = listToCompare.length; for(var itc = 0; itc < listToCompareLength; itc++) { // Recorro los items de la lista siguiente var currentItemsFilteredLength = itemsFiltered[itf + 1].length; for(var nil = 0; nil < currentItemsFilteredLength; nil++) { if(listToCompare[itc].id == itemsFiltered[itf + 1][nil].id) { finalList.push(listToCompare[itc]); break; } } } itemsToShow = finalList; } } } else { itemsToShow = itemsFiltered[0]; } } } // Metodo que muestra los filtros de la forma que se defina function showFiltersControls() { // Obtengo el contenedor definido por el usuario para los filtros if(filtersContainer && filtersContainer != '') { var narrControlsContainer = document.getElementById(filtersContainer); document.sc_clearElement(narrControlsContainer); // Dentro del contenedor tengo que crear mi propio contenedor, por si el usuario desea poner algo mas ahi var narrControlsInner = document.sc_createElement('div','narrControlsInner',null); // Lo agrego al contenedor definido por el usuario narrControlsContainer.appendChild(narrControlsInner); // Creo una lista que va a contener siempre a todos los conjuntos de filtros var filtersList = document.sc_createElement('ul','filtersList',null); // La agrego al contenedor de filtros narrControlsInner.appendChild(filtersList); // Defino la clase cebra var cebraClass = ' cebraFilter'; var currentFilterField; var isAppliedVariant = false; var numFiltersShowed = 0; // Recorro los filtros para crear los titulos y los links var filtersLength = filters.length; for(var f = 0; f < filtersLength; f++) { isAppliedVariant = false; // Clase que se aplica al filtro si esta aplicado var appliedFilter = ''; var isApplied = false; var currentApFilter, apFilterField, apFilterVariant; // Recorro los filtros aplicados para ver si el filtro que intento mostrar esta en la lista var filtersAppliedLength = filtersApplied.length; for(var fa = 0; fa < filtersAppliedLength; fa++) { if(filtersApplied[fa]) { currentApFilter = filtersApplied[fa]; apFilterField = currentApFilter.split(':')[0]; apFilterVariant = currentApFilter.split(':')[1]; if(filters[f].field == apFilterField) { appliedFilter = ' applied'; isApplied = true; } } } currentFilterField = ''; // Verifico si es el turno de agregar la clase cebra o no if(cebraClass != '') cebraClass = ''; else cebraClass = ' cebraFilter'; // Para cada filtro, creo un item de lista (li) que contendra el titulo del filtro y dentro // una lista con las variantes, segun la manera en que se deban mostrar estas var filterCase = document.sc_createElement('li','filterCase' + cebraClass + appliedFilter,'filter_' + filters[f].field); // Creo el titulo del filtro var filterTitle = document.sc_createElement('h3','filterTitle',null); // Al titulo le agrego el texto que corresponde al titulo filterTitle.innerHTML = 'Filter by ' + filters[f].title; // Al contenedor del filtro actual le agrego el titulo filterCase.appendChild(filterTitle); var makeRemoveLink = false; // Creo la list o el select para el conjunto de variantes del filtro var variantsGroup; switch(showFiltersLike) { case 'links': variantsGroup = document.createElement('ul'); // Recorro los filtros aplicados para ver si el filtro que intento mostrar esta en la lista var filtersAppliedLength = filtersApplied.length; for(var fa = 0; fa < filtersAppliedLength; fa++) { if(filtersApplied[fa]) { currentApFilter = filtersApplied[fa]; apFilterField = currentApFilter.split(':')[0]; apFilterVariant = currentApFilter.split(':')[1]; if(filters[f].field == apFilterField) { makeRemoveLink = true; } } } break; case 'dropdown': variantsGroup = document.createElement('select'); if(isApplied) { if(document.all) variantsGroup.setAttribute('className','filterIsApplied'); else variantsGroup.setAttribute('class','filterIsApplied'); } variantsGroup.onchange = function() { // Obtengo el campo del filtro currentFilterField = this.id.replace('group_',''); // Como es un select, cada vez que cambio de link, debo quitar el filtro y luego aplicar el nuevo applyFilter('!' + currentFilterField); // Al quitar un filtro debo reiniciar todos los filtros, ya que si no el applyFilters utiliza la lista // reducida de items y no la completa itemsToShow = allItems; _applyFilters(); // Aplico el filtro if(this.value) { applyFilter(currentFilterField + ':' + this.value); } if(sortApplied != '') { applySorting(sortApplied); } // Redibujo los accesos a los filtros reapplyFilters(); } // Recorro los filtros aplicados var filtersAppliedLength = filtersApplied.length; for(var fa = 0; fa < filtersAppliedLength; fa++) { if(filtersApplied[fa]) { currentApFilter = filtersApplied[fa]; apFilterField = currentApFilter.split(':')[0]; apFilterVariant = currentApFilter.split(':')[1]; if(isApplied) { if(filters[f].field == apFilterField) isAppliedVariant = true; } } } variantsSubtitle = document.createElement('option'); variantsSubtitle.innerHTML = (isAppliedVariant)?' -- Remove filter -- ':' -- Select filter -- '; variantsSubtitle.value = ''; variantsGroup.appendChild(variantsSubtitle); break; } variantsGroup.setAttribute('class','variantsList'); variantsGroup.setAttribute('className','variantsList'); variantsGroup.setAttribute('id','group_' + filters[f].field); var numofVariants = 0; // Recorro las variantes for(var cVariant in filters[f].variants) { numofVariants++; var currentFilterV = filters[f].variants; var isAppliedVariant = false; // Recorro los filtros aplicados para ver si el filtro que intento mostrar esta en la lista var filtersAppliedLength = filtersApplied.length; for(var fa = 0; fa < filtersAppliedLength; fa++) { if(filtersApplied[fa]) { currentApFilter = filtersApplied[fa]; apFilterField = currentApFilter.split(':')[0]; apFilterVariant = currentApFilter.split(':')[1]; if(isApplied) { if(cVariant == apFilterVariant) isAppliedVariant = true; } } } // Control de creacion de acceso a la variante //var createVariantAccess = true; if(!makeRemoveLink) { // Creo el variantCase actual para el filtro actual var variantCase; switch(showFiltersLike) { case 'links': variantCase = document.createElement('li'); break; case 'dropdown': variantCase = document.createElement('option'); variantCase.value = cVariant; if(isAppliedVariant) { variantCase.selected = true; } break; } variantCase.setAttribute('class','variantCase'); variantCase.setAttribute('className','variantCase'); variantCase.setAttribute('id','variant_' + cVariant); // Creo el contenido del variantCase segun el tipo de filtro y la forma en que se debe mostrar var variantCaseHTML; var variantCaseText; var variantRangeTypePatern = /^\_[0-9]*to[0-9]*$/gi; var variantRangeTypePatern2 = /^\_[0-9]*more$/gi; // Si es range if(cVariant.match(variantRangeTypePatern) || cVariant.match(variantRangeTypePatern2)) { if(cVariant.match(variantRangeTypePatern)) { variantCaseText = cVariant.replace('_',''); variantCaseText = variantCaseText.replace('to',' to ') + ' (' + currentFilterV[cVariant].length + ')'; } else if(cVariant.match(variantRangeTypePatern2)) { variantCaseText = cVariant.replace('_',''); variantCaseText = variantCaseText.replace('more',' more') + ' (' + currentFilterV[cVariant].length + ')'; } } // Si es boolean else if(cVariant == 'areTrue' || cVariant == 'areFalse') { switch(cVariant) { case 'areTrue': variantCaseText = 'Are ' + filters[f].title + ' (' + currentFilterV[cVariant].length + ')'; break; case 'areFalse': variantCaseText = 'Are not ' + filters[f].title + ' (' + currentFilterV[cVariant].length + ')'; break; } } // Si es string else { variantCaseText = cVariant; var firstLetter = variantCaseText.substring(0,1); var restText = variantCaseText.substring(1,variantCaseText.length); variantCaseText = firstLetter.toUpperCase() + restText + ' (' + currentFilterV[cVariant].length + ')'; } var beforeVariantCase = ''; var afterVariantCase = ''; if(showFiltersLike == 'links') { var currentFilterField; var currentFilterVariant = cVariant; var variantCaseLink = document.sc_createElement('a','filterLink','link_' + filters[f].field); variantCaseLink.setAttribute('href','javascript:;'); variantCaseLink.setAttribute('rel',cVariant); variantCaseLink.onclick = function() { currentFilterField = this.id.replace('link_',''); // Aplico el filtro applyFilter(currentFilterField + ':' + this.rel); // Redibujo los accesos a los filtros reapplyFilters(); } } switch(showFiltersLike) { case 'links': variantCaseLink.innerHTML = variantCaseText; variantCase.appendChild(variantCaseLink); break; case 'dropdown': variantCaseHTML = variantCaseText; variantCase.innerHTML = variantCaseHTML; break; } // Lo agrego al variantGroup if(currentFilterV[cVariant].length > 0) { variantsGroup.appendChild(variantCase); } } else { var removeLinkItem = document.sc_createElement('li','li_removeLink',null); var removeLink = document.sc_createElement('a','a_removeLink','link_' + filters[f].field); removeLink.setAttribute('href','javascript:;'); removeLink.onclick = function() { currentFilterField = this.id.replace('link_',''); // Quito el filtro applyFilter('!' + currentFilterField); // Al quitar un filtro debo reiniciar todos los filtros, ya que si no el applyFilters utiliza la lista // reducida de items y no la completa itemsToShow = allItems; _applyFilters(); if(sortApplied != '') { applySorting(sortApplied); } // Redibujo los accesos a los filtros reapplyFilters(); } // Creo el nombre de la variante para agregarlo al link var variantCaseText; var variantRangeTypePatern = /^\_[0-9]*to[0-9]*$/gi; var variantRangeTypePatern2 = /^\_[0-9]*more$/gi; var currentVariant; // Recorro los filtros aplicados para ubicar la variante var FALength = filtersApplied.length; for(var fa = 0; fa < FALength; fa++) { if(filtersApplied[fa]) { if(filtersApplied[fa].indexOf(filters[f].field) != -1) { currentVariant = filtersApplied[fa].split(':')[1]; } } } // Si es range if(currentVariant.match(variantRangeTypePatern) || currentVariant.match(variantRangeTypePatern2)) { if(currentVariant.match(variantRangeTypePatern)) { variantCaseText = currentVariant.replace('_',''); variantCaseText = variantCaseText.replace('to',' to ') + ' (' + currentFilterV[currentVariant].length + ')'; } else if(currentVariant.match(variantRangeTypePatern2)) { variantCaseText = currentVariant.replace('_',''); variantCaseText = variantCaseText.replace('more',' more') + ' (' + currentFilterV[currentVariant].length + ')'; } } // Si es boolean else if(currentVariant == 'areTrue' || currentVariant == 'areFalse') { switch(currentVariant) { case 'areTrue': variantCaseText = 'Are ' + filters[f].title + ' (' + currentFilterV[currentVariant].length + ')'; break; case 'areFalse': variantCaseText = 'Are not ' + filters[f].title + ' (' + currentFilterV[currentVariant].length + ')'; break; } } // Si es string else { variantCaseText = currentVariant; var firstLetter = variantCaseText.substring(0,1); var restText = variantCaseText.substring(1,variantCaseText.length); variantCaseText = firstLetter.toUpperCase() + restText + ' (' + currentFilterV[currentVariant].length + ')'; } removeLink.innerHTML = 'Remove filter ' + variantCaseText; removeLinkItem.appendChild(removeLink); variantsGroup.appendChild(removeLinkItem); break; } } // Lo agrego al filterCase filterCase.appendChild(variantsGroup); // Agrego el filtro (y su conjunto de variantes) a la lista de filtros if(numofVariants > 0 && variantsGroup.childNodes.length > 0) { numFiltersShowed++; filtersList.appendChild(filterCase); } } if(numFiltersShowed == 0) { filtersList.innerHTML = '
  • No filters available

'; } } else return; } function createSortingControls(sortByField, sortOrder, sortByTitle, sortBySubtitle, slItemType, currentEvent, functionName, functionOpen, functionClose) { // Variables var htmlReturn = '', slItemAttributes = ' '; // Defino los atributos del elemento slItemAttributes += currentEvent + '="' + functionName + functionOpen + sortByField + ':' + sortOrder + functionClose + '"'; // Si es link agrego la etiqueta a, si no no if(showSortLike == 'links') htmlReturn += '\t<' + slItemType + '>' else htmlReturn += '\t<' + slItemType + slItemAttributes + sortBySelected +'>\n'; // Pongo el titulo y el subtitulo htmlReturn += '\t\t' + sortByTitle + sortBySubtitle + '\n'; // Si es link cierro la etiqueta a if(showSortLike == 'links') htmlReturn += ''; // Cierro el elemento htmlReturn += '\t\n'; // Lo retorno return htmlReturn; } // Metodo que crea las opciones de ordenamiento (sort) segun la configuracion function showSortingControls() { var sortContainerDivs = _getElementsByClass(sortContainer); if(sortContainerDivs) { for(var sContDiv in sortContainerDivs) { if(sortContainerDivs[sContDiv]) { var sortListHTML = '' + ((sortTitle && sortTitle!= '')?sortTitle:'Sort by:') + ''; var slItemType; var slItemAttributes = ' '; var currentEvent = ''; // Creo el contenedor de los sort by segun showSortLike switch(showSortLike) { case 'links': sortListHTML += '
    \n'; slItemType = 'li'; slItemAttributes += ''; currentEvent += 'onclick'; break; case 'dropdown': sortListHTML += ''; break; } sortListHTML += ''; // Pongo el sort list generado en donde corresponda sortContainerDivs[sContDiv].innerHTML = sortListHTML; } } } } // Metodo que aplica la opcion de ordenamiento que se le pase por parametro function applySorting(sortToApply) { if(sortToApply != '') { sortApplied = sortToApply; // Me hago una copia de itemsToShow var localItemsToShow = new Array(); // Relleno localItemsToShow for(var its_ in itemsToShow) { localItemsToShow.push(itemsToShow[its_]); } var tempItemsToShow = new Array(); // Obtengo el campo por el cual hay que ordenar y la direccion var sortByField = sortApplied.split(':')[0]; var sortInOrder = ((sortApplied.split(':')[1])?sortApplied.split(':')[1]:null); // Recorro los items a mostrar var itemsToShowLength = localItemsToShow.length; var cItem = 0; var tempItemsAreTrue = new Array(); var tempItemsAreNotTrue = new Array(); var tempStringItems = new Array(); var arrounds = 0; var cantidadDeItems = 0; while(cItem < itemsToShowLength) { var continueNext = false; if(localItemsToShow[cItem]) { // Recorro los campos del item actual y me quedo con el campo por el cual estoy ordenando var currentItem = localItemsToShow[cItem]; var currentItemField, currentItemFieldValue; for(var cField in currentItem.fields) { if(cField == sortByField) { currentItemField = cField; currentItemFieldType = (currentItem.fields[cField].type)?((currentItem.fields[cField].type=='money')?'number':currentItem.fields[cField].type):'boolean'; currentItemFieldValue = (currentItem.fields[cField].type!='money')?currentItem.fields[cField].value.replace(',',''):currentItem.fields[cField].value.replace(currentItem.fields[cField].currency,'').replace(',',''); if(currentItemFieldType == 'number') currentItemFieldValue = (isNaN(parseFloat(currentItemFieldValue)))?0:parseFloat(currentItemFieldValue); break; } } if(currentItemFieldType) { if(currentItemFieldType == 'boolean') { if(currentItemFieldValue == 'Yes') tempItemsAreTrue.push(localItemsToShow[cItem]); if(currentItemFieldValue == 'No') tempItemsAreNotTrue.push(localItemsToShow[cItem]); cItem++; } else if(currentItemFieldType == 'string') { tempStringItems.push(currentItemFieldValue + ':' + currentItem.id); cItem++; } else { // Recorro los items a mostrar y comparo el primero con todos var _itemsToShowLength = localItemsToShow.length; for(var _cItem = 0; _cItem < _itemsToShowLength; _cItem++) { if(localItemsToShow[_cItem] && _cItem != cItem) { // Recorro los campos del item actual y me quedo con el campo por el cual estoy ordenando var _currentItem = localItemsToShow[_cItem]; var _currentItemField, _currentItemFieldValue; for(var _cField in _currentItem.fields) { if(_cField == sortByField) { _currentItemField = _cField; _currentItemFieldType = (_currentItem.fields[_cField].type)?((_currentItem.fields[_cField].type=='money')?'number':_currentItem.fields[_cField].type):'boolean'; _currentItemFieldValue = (_currentItem.fields[_cField].type!='money')?_currentItem.fields[_cField].value.replace(',',''):_currentItem.fields[_cField].value.replace(_currentItem.fields[_cField].currency,'').replace(',',''); if(_currentItemFieldType == 'number') _currentItemFieldValue = (isNaN(parseFloat(_currentItemFieldValue)))?0:parseFloat(_currentItemFieldValue); break; } } if(currentItemFieldType == 'number') { switch(sortInOrder) { case 'asc': if(currentItemFieldValue > _currentItemFieldValue) { continueNext = true; } else { continueNext = false; } break; case 'desc': if(currentItemFieldValue < _currentItemFieldValue) { continueNext = true; } else { continueNext = false; } break; } } if(continueNext) break; } } if(continueNext) { cItem++; } else { tempItemsToShow.push(localItemsToShow[cItem]); localItemsToShow[cItem] = null; cItem = 0; } } } else return; } else { cItem++; } arrounds++; } if(currentItemFieldType == 'boolean') { if(sortInOrder == 'asc') { for(var i = 0; i < tempItemsAreTrue.length; i++) { tempItemsToShow.push(tempItemsAreTrue[i]); } for(var i = 0; i < tempItemsAreNotTrue.length; i++) { tempItemsToShow.push(tempItemsAreNotTrue[i]); } } else if(sortInOrder == 'desc'){ for(var i = 0; i < tempItemsAreNotTrue.length; i++) { tempItemsToShow.push(tempItemsAreNotTrue[i]); } for(var i = 0; i < tempItemsAreTrue.length; i++) { tempItemsToShow.push(tempItemsAreTrue[i]); } } } else if(currentItemFieldType == 'string') { tempStringItems = tempStringItems.sort(); if(sortInOrder == 'desc') { tempStringItems = tempStringItems.reverse(); } for(var i = 0; i < tempStringItems.length; i++) { var itemsToShowLength = localItemsToShow.length; for(var cIt = 0; cIt <= itemsToShowLength; cIt++) { if(localItemsToShow[cIt]) { var continueWithNext = false; for(var cF in localItemsToShow[cIt].fields) { var currentField = localItemsToShow[cIt].fields[cF]; if(cF == sortByField) { if(tempStringItems[i] == currentField.value + ':' + localItemsToShow[cIt].id) { tempItemsToShow.push(itemsToShow[cIt]); //localItemsToShow[cIt] = null; //tempStringItems[i] = null; continueWithNext = true; break; } } if(continueWithNext) break; } } if(continueWithNext) break; } if(continueWithNext) continue; } } // Por ultimo limpio el array de items a mostrar y le coloco los del array temporal // ya que estos ya estan ordenados itemsToShow = new Array(); itemsToShow = tempItemsToShow; //createPages(); if(showPerPageSelect) { getChangeItemsPerPageControlHTML(); } showPage(0); } } // Metodo que dibuja los items en pantalla, segun la pagina que se este mostrando y la disposicion de las // celdas segun filas y columnas function drawItems() { var rCebra = ' row_cebra'; var cCebra = ' col_cebra'; var tableItemsLayout = document.getElementById('tbody_itemsLayout'); var tbodyItemsLayout = document.getElementById('itemsLayout'); if(tbodyItemsLayout) { tableItemsLayout.removeChild(tbodyItemsLayout); } document.sc_clearElement(tableItemsLayout); // dibujo las filas para los items dentro de tbody_itemsLayout var cItem = 0; for(var r = 0; r < rowsNum; r++) { var cCebra = ' col_cebra'; if(rCebra == '') rCebra = 'row_cebra'; else rCebra = ''; var tableRow = document.sc_createElement('tr','tr_itemsLayout' + rCebra,null); for(var c = 0; c < colsNum; c++) { if(rCebra == '') rCebra = 'row_cebra'; else rCebra = ''; var itemCell = document.sc_createElement('td','td_itemsCell' + cCebra,null); itemCell.setAttribute('valign','top'); itemCell.innerHTML = (pages[currentPage])?((pages[currentPage][cItem])?pages[currentPage][cItem].html:''):''; tableRow.appendChild(itemCell); cItem++ } tableItemsLayout.appendChild(tableRow); } setCallBack(); } // Metodo que muestra el paginador function showPaginator() { if(pages.length > 1) { var firstLink = 0; var lastLink = pages.length; var showLimits = false; if(maxPages != 'all') { if((maxPages % 2) != 1) maxPages += 1; var endsPages = parseInt(maxPages / 2); if(maxPages < pagesNum) { var firstLink = currentPage - endsPages; var lastLink = (currentPage + endsPages) + 1; firstLink = (currentPage<(pages.length - endsPages))?((firstLink >= 0)?firstLink:0):(pages.length - maxPages); lastLink = (firstLink!=0)?((lastLink <= pages.length)?lastLink:pages.length):(maxPages); showLimits = true; } } showingFirstItem = (currentPage * itemsPerPage) + 1; showingLastItem = (showingFirstItem + itemsPerPage) - 1; // Creo el inner del paginador, para luego colocar el conjunto en los contenedores var paginatorInner = document.sc_createElement('div','inner_paginator',null); if(pagesPosition == 'both') { var paginatorInner2 = document.sc_createElement('div','inner_paginator',null); } var paginatorInnerInside = document.sc_createElement('span','pagesInner',null); paginatorInnerInside.innerHTML = 'Pages:'; paginatorInner.innerHTML = ((paginatorHTMLPosition == 'before')?('' + paginatorHTML + ''):''); paginatorInner.appendChild(paginatorInnerInside); // Creo el paginador // Primero creo el link para la 'First' var linkToFirstPage = document.createElement('span'); var linkToFirstClases = 'span_goFirst'; // Si no estoy en la pagina 0, creo el link, de lo contrario no lo creo if(currentPage != 0) { var linkToFirstPageLink = '<<'; linkToFirstPage.innerHTML = linkToFirstPageLink; } else { linkToFirstClases += ' spanDisabled'; linkToFirstPage.innerHTML = '<<'; } linkToFirstPage.setAttribute('class',linkToFirstClases); linkToFirstPage.setAttribute('className',linkToFirstClases); paginatorInnerInside.appendChild(linkToFirstPage); if(paginatorInner2) paginatorInner2.innerHTML = paginatorInner.innerHTML; // Luego creo el link para el 'Back' var linkToPreviousPage = document.createElement('span'); var linkToPreviousClases = 'span_goBack'; // Si no estoy en la pagina 0, creo el link, de lo contrario no lo creo if(currentPage != 0) { var linkToPreviousPageLink = '<'; linkToPreviousPage.innerHTML = linkToPreviousPageLink; } else { linkToPreviousClases += ' spanDisabled'; linkToPreviousPage.innerHTML = '<'; } linkToPreviousPage.setAttribute('class',linkToPreviousClases); linkToPreviousPage.setAttribute('className',linkToPreviousClases); paginatorInnerInside.appendChild(linkToPreviousPage); if(paginatorInner2) paginatorInner2.innerHTML = paginatorInner.innerHTML; // Creo los puntos suspencivos si es necesario ///////////////////////////////////////////////////////////////////////////////////////////////////// if(showLimits) { if(firstLink > 0) { var spaceAtBegin = document.sc_createElement('span','spaceAtBegin',null); spaceAtBegin.innerHTML = '...'; paginatorInnerInside.appendChild(spaceAtBegin); if(paginatorInner2) paginatorInner2.innerHTML = paginatorInner.innerHTML; } } ///////////////////////////////////////////////////////////////////////////////////////////////////// // Recorro el array de paginas y por cada una creo un link con el numero de la pagina var pagesLength = pages.length; for(var cPage = firstLink; cPage < lastLink; cPage++) { var pageLinkSpan = document.createElement('span'); var clases = ''; if(currentPage != cPage) { clases = 'span_goToPage'; var pageLinkLink = '' + (cPage + 1) + ''; pageLinkSpan.innerHTML = pageLinkLink; } else { clases = 'span_goToPage active'; pageLinkSpan.innerHTML = '' + (cPage + 1) + ''; } pageLinkSpan.setAttribute('class',clases); pageLinkSpan.setAttribute('className',clases); paginatorInnerInside.appendChild(pageLinkSpan); if(paginatorInner2) paginatorInner2.innerHTML = paginatorInner.innerHTML; } // Creo los puntos suspencivos si es necesario ///////////////////////////////////////////////////////////////////////////////////////////////////// if(showLimits) { if(lastLink < pages.length) { var spaceAtEnd = document.sc_createElement('span','spaceAtEnd',null); spaceAtEnd.innerHTML = '...'; paginatorInnerInside.appendChild(spaceAtEnd); if(paginatorInner2) paginatorInner2.innerHTML = paginatorInner.innerHTML; } } ///////////////////////////////////////////////////////////////////////////////////////////////////// // Luego creo el link para el 'Next' var linkToNextPage = document.createElement('span'); linkToNextClases = 'span_goNext'; // Si no estoy en la pagina 0, creo el link, de lo contrario no lo creo if(currentPage != (pagesNum - 1)) { var linkToNextPageLink = '>'; linkToNextPage.innerHTML = linkToNextPageLink; } else { linkToNextClases += ' spanDisabled'; linkToNextPage.innerHTML = '>'; } linkToNextPage.setAttribute('class',linkToNextClases); linkToNextPage.setAttribute('className',linkToNextClases); paginatorInnerInside.appendChild(linkToNextPage); if(paginatorInner2) paginatorInner2.innerHTML = paginatorInner.innerHTML; // Luego creo el link para la 'Last' var linkToLastPage = document.createElement('span'); var linkToLastClases = 'span_goLast'; // Si no estoy en la pagina 0, creo el link, de lo contrario no lo creo if(currentPage != (pagesNum - 1)) { var linkToLastPageLink = '>>'; linkToLastPage.innerHTML = linkToLastPageLink; } else { linkToLastClases += ' spanDisabled'; linkToLastPage.innerHTML = '>>'; } linkToLastPage.setAttribute('class',linkToLastClases); linkToLastPage.setAttribute('className',linkToLastClases); paginatorInnerInside.appendChild(linkToLastPage); paginatorInner.innerHTML += ((paginatorHTMLPosition == 'after')?('' + paginatorHTML + ''):''); if(paginatorInner2) paginatorInner2.innerHTML = paginatorInner.innerHTML; // Obtengo los contenedores del paginador var paginatorBoxes = _getElementsByClass('td_pagesBar'); // Los recorro para poner el paginador dentro var pagBoxesLength = paginatorBoxes.length; for(var cBox = 0; cBox < pagBoxesLength; cBox++) { document.sc_clearElement(paginatorBoxes[cBox]); if(cBox != 0) { paginatorBoxes[cBox].appendChild(paginatorInner2); } else { paginatorBoxes[cBox].appendChild(paginatorInner); } } } else { var paginatorBoxes = _getElementsByClass('td_pagesBar'); var pagBoxesLength = paginatorBoxes.length; for(var cBox = 0; cBox < pagBoxesLength; cBox++) { document.sc_clearElement(paginatorBoxes[cBox]); var customHTMLBox = document.sc_createElement('span','customHTML'); customHTMLBox.innerHTML = paginatorHTML; paginatorBoxes[cBox].appendChild(customHTMLBox); } } } // Metodo que crea las paginas y distribulle los items function createPages() { pages = new Array(); // Obtengo el numero total de items a paginar totalItems = itemsToShow.length; // Calculo la cantidad de paginas para la cantidad de items pagesNum = Math.ceil(totalItems / itemsPerPage); // Creo los arrays de items para cada pagina for(var page = 0; page < pagesNum; page++) { var cPage = page + 1; var startIn = (page * itemsPerPage); var finishIn = ((itemsPerPage) * (page + 1)); // Recorro los items a mostrar, desde el primer item de la pagina actual hasta la cantidad de items, y los guardo en el array de la pagina actual pages[page] = new Array(); for(var item = startIn; item < finishIn; item++) { if(itemsToShow[item]) { pages[page].push(itemsToShow[item]); } } } } // Metodo que muestra los items segun la pagina seleccionada function showPage(page) { currentPage = page; //alert('create page 2049 - ' + itemsPerPage) createPages(); showPaginator(); // Creo los Sort list showSortingControls(); drawItems(); if(showPerPageSelect) { getChangeItemsPerPageControlHTML(); } } // inicializo los procesos // IMPORTANTE Esta funcion debe estar en el evento onload del objeto window //if(window.attachEvent) { // window.attachEvent('onload',startProcess); //} else { // window.addEventListener('load',startProcess,true); //} function initiate() { try { startProcess(); } catch(e) { setTimeout(initiate, 300); } } setTimeout(initiate, 300);