var ultima;
var primera;
var links;
 var $opciones;
 var numeros;

function openShadowbox(content) {
//    console.log(content)
    Shadowbox.open(content)
}

function contenidoCargado() {
    $("#sb-loading").show()
}

$(document).ready(function() {
    $opciones = $('select', '#opciones');
    if ($opciones.length > 0) {//hay opciones -> esconder cartelito y mostrar el span adecuado
        var chorizo = '';
        $opciones.each(function() {
            $attrID_ = $(this).attr('name').split('[')
            $attrID = $attrID_[1].replace(']', '');
            chorizo += ((chorizo == '') ? '' : ',') + $attrID + '-'+ $("option:selected", this).val()
        })
        var cartelID = document.getElementById(chorizo)
        $(cartelID).css('display', 'block')
    }
    $opciones.each(function() {
        $(this).change(function() {
            $(".disponible").hide();
//                alert($(this).attr('name') + ' - '+ $("option:selected", this).val())
            var psa = readCookie('atributos')
            var sspan = document.getElementById(psa)
            $(sspan).css('display', 'block')
        })
    })

    $(".shadow").live('click', function() {
        var link = $(this).attr('href');
        var opcionesShadowbox = {
            content: link,
            player:     'iframe',
            width: 950,
            options: {
                onFinish: contenidoCargado
            }
        }
        openShadowbox(opcionesShadowbox);
        return false;
    })

    var $tabs = $("#tabs").tabs();
    $.preLoadImages("http://www.amantis.net/imagenes/pleaseWait2.gif");
    var enlaces = $(".navegacionComentarios").children('a');

    $(".pageResults").live('click', function() {
    	if (!$(this).closest(".noAjax").size()) {//no para los listados "normales", sin ajax
	        var selectedTab = $("div.ui-tabs-panel:not(.ui-tabs-hide)", "#tabs")//id del tab que se esta viendo
	        
	        var numPag = $(this).children().html();//el link que ha sido clikeado
	        if(selectedTab.attr("id")=='comentarios'){
		        var current = $(".navegacionComentarios", "#" + selectedTab.attr('id'));//la pagina que estaba viendo
		        $("comentarios_textos", "#" + selectedTab.attr('id')).block({message : '<img src="https://www.amantis.net/imagenes/pleaseWait2.gif">'});
		        var currentNumber = parseInt(current.children('b').html());//el numero de la pagina que estaba viendo
		        
		        if ($(this).hasClass('siguiente') || $(this).hasClass('siguientes')) {
		            if ($(this).hasClass('siguiente')) {
		                numPag = (currentNumber+1);
		            } else if ($(this).hasClass('siguientes')) {
		                numeros = current.children('.numero').last()
		                if (numeros.hasClass('pageResults')) {
		                    numPag = parseInt(numeros.children('u').html())+1
		                } else {
		                    numPag = parseInt(numeros.html())+1
		                }
		            }
	
		            if (($('*:contains("' + numPag + '")', current).length == 0) || $(this).hasClass('siguientes')) {//mostrar los 5 siguientes
		                ultima = (current.children(".numero").last().children().html() !== null) ? parseInt(current.children(".numero").last().children().html()) : parseInt(current.children(".numero").last().html());
		                links = '';
		                for (var i=(ultima+2); i<=(ultima+5); i++) {
		                    if (i <= numOfPages) {
		                        links += '&nbsp;&nbsp;<a class="pageResults numero" href="#"><u>' + i + '</u></a>';
		                    }
		                }
		                current.html('P&aacute;ginas de Resultados: <a class="pageResults anterior" href="#" title="Anterior"><u>[<< Anterior]</u></a>&nbsp;&nbsp;' +
		                                                                       '<a class="pageResults anteriores" href="#" title="Anteriores 5 p&aacute;ginas">...</a>&nbsp;' +
		                                                                       '<b class="numero">' + (ultima+1) + '</b>' +
		                                                                       links +
		                                                                       ((i < numOfPages) ? '&nbsp;<a class="pageResults siguientes" href="#" title="Siguientes 5 p&aacute;ginas">...</a>&nbsp;' +
		                                                                       '&nbsp;<a class="pageResults siguiente" href="#" title="Siguientes"><u>[Siguiente >>]</u></a>' : '')
		                                                                       );
		            } else {
		//                console.log(numPag)
		                $('*:contains("' + numPag + '")', current).replaceWith('<b class="numero">' + numPag + '</b>');
		            }
		        } else if ($(this).hasClass('anterior') || $(this).hasClass('anteriores')) {
		            if ($(this).hasClass('anterior')) {
		                numPag = (currentNumber-1);
		            } else if ($(this).hasClass('anteriores')) {
		                numeros = current.children('.numero').first()
		                if (numeros.hasClass('pageResults')) {
		                    numPag = parseInt(numeros.children('u').html())-1
		                } else {
		                    numPag = parseInt(numeros.html())-1
		                }
		            }
		
		            if (($('*:contains("' + numPag + '")', current).length == 0) || $(this).hasClass('anteriores')) {//mostrar los 5 siguientes
		                primera = (current.children(".numero").first().children().html() !== null) ? parseInt(current.children(".numero").first().children().html()) : parseInt(current.children(".numero").first().html());
		                links = '';
		                for (var i=(primera-5); i<(primera-1); i++) {
		                    if (i > 0) {
		                        links += '&nbsp;&nbsp;<a class="pageResults numero" href="#"><u>' + i + '</u></a>';
		                    }
		                }
		                current.html(((i > 5) ? 'P&aacute;ginas de Resultados: <a class="pageResults anterior" href="#" title="Anterior"><u>[<< Anterior]</u></a>&nbsp;&nbsp;' +
		                                                                       '<a class="pageResults anteriores" href="#" title="Anteriores 5 p&aacute;ginas">...</a>&nbsp;' : '') +
		                                                                       links +
		                                                                       '&nbsp;&nbsp;<b class="numero">' + (primera-1) + '</b>' +
		                                                                       ((i < numOfPages) ? '&nbsp;<a class="pageResults siguientes" href="#" title="Siguientes 5 p&aacute;ginas">...</a>&nbsp;' +
		                                                                       '&nbsp;<a class="pageResults siguiente" href="#" title="Siguientes"><u>[Siguiente >>]</u></a>' : '')
		                                                                       );
		            } else {
		                $('*:contains("' + numPag + '")', current).replaceWith('<b class="numero">' + numPag + '</b>');
		            }
		        } else {
		            $('*:contains("' + numPag + '")', current).replaceWith('<b class="numero">' + numPag + '</b>');
		        }
		//        console.log()
		        current.children('b:contains("' + currentNumber + '")').replaceWith('<a class="pageResults numero" href="#"><u>' + currentNumber + '</u></a>');
		
		        //link Anterior
		        if (numPag != 1) {
		            if ($(".anterior", "#" + selectedTab.attr('id')).length < 1) {
		                current.children().first().before('<a class="pageResults anterior" href="#" title="Anterior"><u>[<< Anterior]</u></a>&nbsp;&nbsp;');
		                current.last().children().first().before('<a class="pageResults anterior" href="#" title="Anterior"><u>[<< Anterior]</u></a>&nbsp;&nbsp;');
		            }
		        } else {
		            $(".anterior", "#" + selectedTab.attr('id')).remove();
		        }
		
		        //link Siguiente
		        if (numPag != numOfPages) {
		            if ($(".siguiente", "#" + selectedTab.attr('id')).length < 1) {
		                current.first().children().last().after('&nbsp;&nbsp;<a class="pageResults siguiente" href="#" title="Siguientes"><u>[Siguiente >>]</u></a>');
		                current.children().last().after('&nbsp;&nbsp;<a class="pageResults siguiente" href="#" title="Siguientes"><u>[Siguiente >>]</u></a>');
		            }
		        } else {
		            $(".siguiente", "#" + selectedTab.attr('id')).remove();
		        }
		
		        $(".viendoDe", "#" + selectedTab.attr('id')).html('Viendo del <b>' + ((numOfRowsPerPage * (numPag - 1)) + 1) + '</b> al <b>' + (((numOfRowsPerPage * numPag) > numOfRows) ? numOfRows : (numOfRowsPerPage * numPag)) + '</b>')
	
		        //get datos por JSON
		        $.ajax({
		            url: 'checkout_json.php',
		            data: 'action=getComentarios&tab=' + selectedTab.attr('id') + ((prodID != 0) ? '&prodID=' + prodID : '&catID=' + catID) + '&pagina=' + (numPag - 1) + '&limit=' + numOfRowsPerPage + ((selectedTab.attr('id') == 'foro') ? '&busqForo=' + $("#busqueda_foro").html() : ''),
		            async: true,
		            type: 'get',
		            dataType: 'json',
		            beforeSend: function() {
		                $(".comentarios_textos", "#" + selectedTab.attr('id')).block({message : '<img src="https://www.amantis.net/imagenes/pleaseWait2.gif">'});
		            },
		            success: function(response) {
		                var respuesta = '<table border="0" width="100%" cellspacing="0" cellpadding="2">';
		                $(".comentarios_textos", "#" + selectedTab.attr('id')).html('')
		                $.each(response.response, function() {
		//                    console.log(this)
		                    respuesta += '<tr><td><table border="0" width="100%" cellspacing="0" cellpadding="2">';
		                    respuesta += '<tr><td class="main">'  + (((selectedTab.attr('id') == 'foro') || (selectedTab.attr('id') == 'probador')) ? '<a href="' + this['link'] + '" class="shadow" rel="shadowbox;width=950"><u><b>' : '') + 'por ' + this['cliente'] + (((selectedTab.attr('id') == 'foro') || (selectedTab.attr('id') == 'probador')) ? '</b></u></a>' : '') + ((this['producto'] != 'nope') ? ' a proposito de <a href="product_info.php?products_id=' + this['producto_id'] + '"><b>' + this['producto'] + '</b></a>' : '') + '</td>';
		                    respuesta += '<td class="smallText" align="right">' + this['fecha'] + '</td></tr>';
		                    respuesta += '</table></td></tr>';
		
		                    respuesta += '<tr><td><table border="0" width="100%" cellspacing="1" cellpadding="2">';
		                    respuesta += '<tr><td class="infoBoxProdInfoTabs"><table border="0" width="100%" cellspacing="0" cellpadding="2">';
		                    respuesta += '<tr><td width="10"><img height="1" border="0" width="10" alt="" src="../imagenes/pixel_trans.gif"></td>';
		//                    respuesta += '<td valign="top" class="main">' + this['texto'] + '<br><br><i>' + this['rating'] + '</i></td>';
		                    respuesta += '<td valign="top" class="main"><div class="contenedor">' + ((this['imagen'] != '') ? '<div class="imagenListado">' + this['imagen'] + '</div>' : '') + '<div class="textoListado">' + this['texto'] + ((this['rating'] != 'nope') ? '<br><br><i>' + this['rating'] + '</i>' : '') + '</div></div></td>';
		                    respuesta += '<td width="10"><img height="1" border="0" width="10" alt="" src="../imagenes/pixel_trans.gif"></td></tr>';
		                    respuesta += '</table></td></tr>';
		                    respuesta += '</table></td></tr>';
		                })
		                $(".comentarios_textos", "#" + selectedTab.attr('id')).append(respuesta)
		                $(".comentarios_textos", "#" + selectedTab.attr('id')).unblock()
		            }
		        })
	    	}else if(selectedTab.attr("id")=='enOferta'){ //para specials.php, llamándolo desde la pestaña "enOferta" de default.php
		        var current = $(".navegacionOfertas", "#" + selectedTab.attr('id'));//la pagina que estaba viendo
		        $("#enOferta").block({message : '<img src="https://www.amantis.net/imagenes/pleaseWait2.gif">'});
		        var currentNumber = parseInt(current.children('b').html());//el numero de la pagina que estaba viendo
		        
		        if ($(this).hasClass('siguiente') || $(this).hasClass('siguientes')) {
		            if ($(this).hasClass('siguiente')) {
		                numPag = (currentNumber+1);
		            } else if ($(this).hasClass('siguientes')) {
		                numeros = current.children('.numero').last()
		                if (numeros.hasClass('pageResults')) {
		                    numPag = parseInt(numeros.children('u').html())+1
		                } else {
		                    numPag = parseInt(numeros.html())+1
		                }
		            }
		        } else if ($(this).hasClass('anterior') || $(this).hasClass('anteriores')) {
		            if ($(this).hasClass('anterior')) {
		                numPag = (currentNumber-1);
		            } else if ($(this).hasClass('anteriores')) {
		                numeros = current.children('.numero').first()
		                if (numeros.hasClass('pageResults')) {
		                    numPag = parseInt(numeros.children('u').html())-1
		                } else {
		                    numPag = parseInt(numeros.html())-1
		                }
		            }
		        }
	    		$.ajax({
	    			url: 'specials.php?origen_pestania=true&'+'&catID=' + catID +'&page=' + numPag,
	    			beforeSend: function(){
	    				$(".ofertas_textos", "#" + selectedTab.attr('id')).block({message : '<img src="https://www.amantis.net/imagenes/pleaseWait2.gif">'});
	    			},
	    			success: function(data) {
	    				$('#enOferta').html(data);
	    			}
	    		}); 
	    	}
	        return false;
    	}
    })//endof navegacion pageResult AJAX
    if (document.location.href.indexOf('product_info') !== -1) {
        $('html, body').animate({scrollTop:0}, 'slow');
    }
})
