// <![CDATA[ 

	$(document).ready(
		function() {
          
            // funcion para colapsar menu y submenu
            var menuPadre = $("ul.menu-categorias:not('li.submenu-categorias')").find("li:first");
            if(menuPadre.length){
                $("li.submenu-categorias").hide();
                menuPadre.mouseover(function(){
                    // oculto todos los demas elmentos y muestro el hijo
                    $("li.submenu-categorias").hide();
                    $(this).parent().find(".submenu-categorias").show();
                    
                   
                });
            }
          
			// opacidad
			function opacidad(elemento, valor) {
				var valor_noie = valor / 100;
				$(elemento).css('filter', 'alpha(opacity=' + valor + ')');
				$(elemento).css('-moz-opacity', valor_noie);
				$(elemento).css('-khtml-opacity', valor_noie);
				$(elemento).css('opacity',valor_noie);
			}
			
			// centrar elemento en la pantalla verticalmente
			function centro(lo_que) {
				var x = parseFloat($(window).width()) / 2 - parseFloat($(lo_que).width()) / 2;
				var y = $(window).scrollTop() + $(window).height() / 2 - parseFloat($(lo_que).height()) / 2;
				x = x + 'px';
				y = y + 'px';
				$(lo_que).css({'left': x, 'top': y});
			}
			
			// centrar elemento en la pantalla verticalmente
			function centroVert(lo_que) {
				var y = $(window).scrollTop() + $(window).height() / 2 - parseFloat($(lo_que).height()) / 2;
				$(lo_que).css({'top': y});
			}
			
			// carga de imagenes
			function cargaImg(sID, sURL) {
				$(sID).unbind("load");
				$(sID).bind("load", function() { $(this).fadeIn(); } )
				$(sID).stop(true, true).fadeOut("normal", function () { $(sID).attr('src', sURL); } );
			}
            
            /** Menu imágenes - video */
            $('#ul_menu_fotos_video .fotos_btn').click(
                function(){
                    if($('#ul_menu_fotos_video .fotos_btn.activo').length == 0){
                        $('#video').css('display','none');
                        $('#photos').css('display','block');
                        $('#ul_menu_fotos_video .video_btn').attr('class','video_btn');
                        $('#ul_menu_fotos_video .fotos_btn').attr('class','fotos_btn activo');
                    }
                }
            );
            $('#ul_menu_fotos_video .video_btn').click(
                function(){
                    if($('#ul_menu_fotos_video .video_btn.activo').length == 0){
                        $('#photos').css('display','none');
                        $('#video').css('display','block');
                        $('#ul_menu_fotos_video .fotos_btn').attr('class','fotos_btn');
                        $('#ul_menu_fotos_video .video_btn').attr('class','video_btn activo');
                    }
                }
            );
            
			if($('#comprar_logueado').length){
                $('#comprar').click(
                    function(){
                       
                        var div_hidden = $(this).parent().find('div.hidden');
                        var producto_id = $(div_hidden).find('.hidden_producto_id').html();
                        var accion = $(div_hidden).find('.hidden_accion').html();
                        var cantidad = $('.cantidad').find('input').val();
                        //window.open(accion+'-p'+producto_id+'-c'+cantidad,accion+'-p'+producto_id+'-c'+cantidad,'width=450,height=102,left='+((screen.width-400)/2)+',top=250,resizable=0,directories=0,location=1,menubar=0,toolbar=0,scrollbars=1');
                        $.colorbox({href:accion+'-p'+producto_id+'-c'+cantidad, width:"600px", height:"320px", iframe:true, onClosed:function(){ window.location.reload(); }});
                    }
                );
            }
            
            if($('#denunciar_publicacion').length){
                $('#denunciar_publicacion').click(
                    function(){
                        var publicacion_id = $(this).attr('class');
                        publicacion_id = publicacion_id.substr(12);
                        $.colorbox({href:'denunciar_publicacion.php?id='+publicacion_id, width:"450px", height:"350px", iframe:true});
                    }
                );
            }
            
            $('.datos_vendedor_btn').click(
                function(){
                    var div_hidden = $(this).parent().find('div.hidden');
                    var compra_id = $(div_hidden).find('.hidden_compra_id').html();
                    $.colorbox({href: 'datos-vendedor-'+compra_id, width:"550px", height:"200px", iframe:true});
                    return false;
                }
            );
            
            $('.datos_comprador_btn').click(
                function(){
                    var div_hidden = $(this).parent().find('div.hidden');
                    var compra_id = $(div_hidden).find('.hidden_compra_id').html();
                    $.colorbox({href: 'datos-comprador-'+compra_id, width:"550px", height:"200px", iframe:true});
                    return false;
                }
            );
            
			 if($('.list_carousel').length){
            
    				//	Basic carousel
                    if($('#foo0').length)
    				    $('#foo0').carouFredSel();
                    
                    if($('#foo0').length){
                        //	Basic carousel + timer
        				$('#foo1').carouFredSel({
        					auto: {
        						pauseOnHover: 'resume',
        						onPauseStart: function( percentage, duration ) {
        							$(this).trigger( 'configuration', ['width', function( value ) { 
        								$('#timer1').stop().animate({
        									width: value
        								}, {
        									duration: duration,
        									easing: 'linear'
        								});
        							}]);
        						},
        						onPauseEnd: function( percentage, duration ) {
        							$('#timer1').stop().width( 0 );
        						},
        						onPausePause: function( percentage, duration ) {
        							$('#timer1').stop();
        						}
        					}
        				});
                    }
    				
                    if($('#foo2').length){
                        //	Scrolled by user interaction
        				$('#foo2').carouFredSel({
        					prev: '#prev2',
        					next: '#next2',
        					pagination: "#pager2",
        					auto: true,
                            width: 195,//adaptarCarrousel(),
                            onCreate: function(a,b){
                                $('.caroufredsel_wrapper').css('margin','0 auto');  
                                adaptarCarrousel(); 
                            }
        				});
                        
                    }
                    
            }
			
            
            /**
            *
            */
            if($("select[name='categoria']").length){
                $("select[name='categoria']").change(function(){
                    // cambio el texto del combo de subcategorias a cargando
                    $("select[name='subcategoria2']").html('<option value="-1">Seleccione...</option>');
                    $("select[name='subcategoria']").html("<option>cargando..</option>").attr('disabled','true');
                    $.ajax({
                        url:"ajax/subcategorias.php",
                        data:"categoria="+$("select[name='categoria']").val(),
                        success: function(html){
                            $("select[name='subcategoria']").html(html).attr('disabled','');
                        }
                    });
                })
                
                 $("select[name='subcategoria']").change(function(){
                    // cambio el texto del combo de subcategorias a cargando
                    $("select[name='subcategoria2']").html("<option>cargando..</option>").attr('disabled','true');
                    $.ajax({
                        url:"ajax/subcategorias.php",
                        data:"categoria="+$("select[name='subcategoria']").val(),
                        success: function(html){
                            if(html.indexOf('<option') != -1){
                                $("select[name='subcategoria2']").html(html).attr('disabled','');
                                $("select[name='subcategoria2']").parent().show();
                            }else{
                                $("select[name='subcategoria2']").parent().hide();
                            }
                        }
                    });
                })
                
                /** Valido antes de proceder */
                $('form[name="frm"]').submit(
                    function(){
                        if(!$('select[name="subcategoria"] option:selected').length || $('select[name="subcategoria"] option:selected').val() == '-1'){
                            alert("Por favor indique la sub-categor\u00EDa del producto.");
                            return false;
                        }else if($('select[name="subcategoria2"]').parent().css('display') != 'none' && (!$('select[name="subcategoria2"] option:selected').length || $('select[name="subcategoria2"] option:selected').val() == '-1')){
                            alert("Por favor indique la sub-categor\u00EDa del producto.");
                            return false;
                        }else{
                            if($('select[name="subcategoria2"]').parent().css('display') != 'none'){
                                $('input[name="categoria_id"]').val($('select[name="subcategoria2"]').val());
                            }else{
                                $('input[name="categoria_id"]').val($('select[name="subcategoria"]').val());
                            }
                        }
                    }
                );
            }
            
            $(".agregarFoto").click(function(){
                console.log($("input[type=file],img.imgPublicacion").length);
                if($("input[type=file],img.imgPublicacion").length==4){
                    $(this).remove();
                 
                }
                   $("input[type=file]:last").parent().after('<div class="fotos"><input type="file" name="img_'+$("input[type=file],img.imgPublicacion").length+'"/></div>');
                });
                
		  if( $(".agregarFoto").length){
		      if($("input[type=file],img.imgPublicacion").length==5){
                    $(".agregarFoto").remove();
                }
		  }
          
          $('.fotosImg .eliminarImgBtn').click(
            function(){
                var div_padre = $(this).parent();
            
                $(div_padre).hide();
                image = $(this).parent().attr("image");
              
                $(div_padre).find('img').remove();
                
                var indice = $(div_padre).attr('index');
                $(div_padre).html('<input type="file" name="img_'+$(div_padre).attr('index')+'"/><input type="hidden" name="eliminarFoto[]" value="'+indice+'"/>').removeClass("fotosImg").addClass("fotos");          
                $('.loading_img').css('visibility','visible');
                $('.nueva_div').css('visibility','hidden');
                $('.eliminarImgBtn').each(
                    function(){
                        $(this).css('visibility','hidden');
                       // alert('eliminar foto: '+imagen);
                       
          /* ELIMINO IMAGEN TEMPORAL */
                  $.ajax({
                                type: 'POST',
                               
                                url: '../ajax/opciones_ajax.php',
                                data: 'accion=eliminarimagentemporal&img='+image,
                                success: function(data){
                                   
                                  /*  window.location.href = window.location.href;*/
                                }
                            });
                $('#publicacionImagenes_div form').submit();
              
                               
                    }
                );
                
            }
          );
          
          $('.videosVdo .eliminarVdoBtn').click(
            function(){
                var div_padre = $(this).parent();
                $(div_padre).hide();
                $(div_padre).find('img').remove();
                var indice = $(div_padre).attr('index');
                $(div_padre).html('<input type="file" name="vdo_'+$(div_padre).attr('index')+'"/><input type="hidden" name="eliminarVideo[]" value="'+indice+'"/>').removeClass("videosVdo").addClass("videos");          
                $('.loading_img').css('visibility','visible');
                $('.nuevo_div').css('visibility','hidden');
                $('.eliminarVdoBtn').each(
                    function(){
                        $(this).css('visibility','hidden');
                    }
                );
                $('#publicacionVideos_div form').submit();
            }
          );
          
        if($('#seguimiento_btn').length){
            if($('#seguimiento_btn').html() != 'en seguimiento'){
                $('#seguimiento_btn').click(
                    function(){
                        $.ajax({
                            url: "ajax/opciones_ajax.php",
                            type: "POST",
                            data: "accion=marcarSeguimiento&publicacion_id="+$('#producto_id_hidden').html(),
                            success: function(data){
                                if(data == 'true'){
                                    $('#seguimiento_btn').html('en seguimiento');
                                    $('#seguimiento_btn').unbind('click');
                                    $('#seguimiento_btn').css('cursor','default');
                                    alert("La publicaci\u00F3n ha sido marcada en seguimiento. Para verla, ingresa en \"Mi Cuenta\"");
                                }else{
                                    alert("Ocurri\u00F3 un error al intentar marcar la publicaci\u00F3n en seguimiento. Lamentamos las molestias ocacionadas.");
                                }
                            }
                        });
                    }
                );
            }else{
                $('#seguimiento_btn').css('cursor','default');
            }
        }
        
        /** publicacionImagenes_div */
        if($('#publicacionImagenes_div').length){
            $('.loading_img').css('visibility','hidden');
            $('#publicacionImagenes_div .nueva_div input[type="file"]').each(
                function(){
                    $(this).change(
                        function(){
                            $('.loading_img').css('visibility','visible');
                            $(this).parent().css('visibility','hidden');
                            $('.eliminarImgBtn').each(
                                function(){
                                    $(this).css('visibility','hidden');
                                }
                            );
                            $('#publicacionImagenes_div form').submit();
                        }
                    );
                }
            );
        }
        
        /** publicacionVideos_div */
        if($('#publicacionVideos_div').length){
            $('.loading_img').css('visibility','hidden');
            $('#publicacionVideos_div .nuevo_div input[type="file"]').each(
                function(){
                    $(this).change(
                        function(){
                            $('.loading_img').css('visibility','visible');
                            $(this).parent().css('visibility','hidden');
                            $('.eliminarVdoBtn').each(
                                function(){
                                    $(this).css('visibility','hidden');
                                }
                            );
                            $('#publicacionVideos_div form').submit();
                        }
                    );
                }
            );
        }
        
        if($('#body_comprar_destacados').length){
            $('.tabla_compra_destacados input[type="checkbox"]').each(
                function(){
                    $(this).click(
                        function(){
                            switch($(this).attr('checked')){
                                case true:
                                    $(this).parent().parent().find('input.cantidad').val('1');
                                    break;
                                case false:
                                    $(this).parent().parent().find('input.cantidad').val('0');
                                    break;
                            }
                        }
                    );
                }
            );
            $('.tabla_compra_destacados input[type="text"]').each(
                function(){
                    $(this).keyup(
                        function(){
                            if(isNaN($(this).val())){
                                $(this).val('0');
                            }else{
                                $(this).val(parseInt($(this).val()));
                            }
                            if($(this).val() > 0){
                                $(this).parent().parent().find('input[type="checkbox"]').attr('checked',true);
                            }else{
                                $(this).parent().parent().find('input[type="checkbox"]').attr('checked',false);
                            }
                        }
                    );
                }
            );
        }
        
        /**
        * Muestro más opcions
        */
        $(".filtro_especial .mas_opciones a").click(function(){
            if($(this).parent().hasClass("mostrando")){ // si estoy desplezado
                $(this).parent().removeClass("mostrando");
                $(this).html("Más opciones");
                $(this).parent().parent().find(".filtro_item.oculto").removeClass("desplegado");   
            }else{ // si está oculto
                $(this).parent().addClass("mostrando");
                $(this).html("Menos opciones");
                $(this).parent().parent().find(".filtro_item.oculto").addClass("desplegado");
            }
        })
        
        if($('#preguntar_link_interno').length){
            $('#preguntar_link_interno').click(
                function(){
                    if($('#preguntar_form textarea').length){
                        $('#preguntar_form textarea').focus();
                    }
                }
            );
        }
        
        if($('#preguntar_form').length){
            var preguntar_form = $(this);
            $(preguntar_form).find('textarea').focus(
                function(){
                    if($(this).val() == 'Escribe tu pregunta...'){
                        $(this).val('');
                        $(preguntar_form).find('textarea').css('color','#000000');
                    }
                    $(this).animate({
                        height: 150
                    },200);
                }
            );
            $(preguntar_form).find('textarea').keyup(
                function(){
                    if($(preguntar_form).find('textarea').val().length > 1000){
                        var texto = $(preguntar_form).find('textarea').val();
                        texto = texto.substr(0,1000);
                        $(preguntar_form).find('textarea').val(texto);
                    }
                    $(preguntar_form).find('#preguntar_char_restantes strong').html(1000-$(preguntar_form).find('textarea').val().length);
                }
            );
            $(preguntar_form).find('textarea').bind('paste',
                function(){
                    var t = setTimeout(function(){
                        if($(preguntar_form).find('textarea').val().length > 1000){
                            var texto = $(preguntar_form).find('textarea').val();
                            texto = texto.substr(0,1000);
                            $(preguntar_form).find('textarea').val(texto);
                        }
                        $(preguntar_form).find('#preguntar_char_restantes strong').html(1000-$(preguntar_form).find('textarea').val().length);
                    },100);
                }
            );
            $(preguntar_form).find('textarea').blur(
                function(){
                    if($(preguntar_form).find('textarea').val().length > 1000){
                        var texto = $(preguntar_form).find('textarea').val();
                        texto = texto.substr(0,1000);
                        $(preguntar_form).find('textarea').val(texto);
                    }
                    $(preguntar_form).find('#preguntar_char_restantes strong').html(1000-$(preguntar_form).find('textarea').val().length);
                }
            );
            
            $(preguntar_form).find('textarea').css('color','#888888');
            $(preguntar_form).find('textarea').val('Escribe tu pregunta...');
        }
        
        if($('#video_nuevo_youtub_btn').length){
            $('#video_nuevo_youtub_btn').click(
                function(){
                    var youtube_link = prompt('El link debe ser el mismo que YouTube proporciona cuando se da click en "compartir":');
                    if(youtube_link && youtube_link != ''){
                        $('input[name="youtube_link"]').val(youtube_link);
                        $('#publicacionVideos_div form').submit();
                    }
                }
            );
        }
        
        if($('#reclamos_contenedor').length){
            $('#iniciar_reclamo_btn').click(
                function(){
                    $.colorbox({href:'reclamo.php',width:"450px",height:"350px",iframe:true,onClosed:function(){ window.location.reload(); }});
                }
            );
            $('.reclamo.responder textarea').focus(
                function(){
                    if($(this).val() == 'Escribe tu respuesta...'){
                        $(this).val('');
                        $(this).css('color','#000000');
                        $(this).animate({
                            height: 150
                        },200);
                    }
                }
            );
            $('.reclamo.responder textarea').blur(
                function(){
                    if($(this).val() == ''){
                        $(this).css('color','#888888');
                        $(this).val('Escribe tu respuesta...');
                        $(this).animate({
                            height: 18
                        },200);
                    }
                }
            );
            $('.reclamo.responder textarea').css('color','#888888');
            $('.reclamo.responder textarea').val('Escribe tu respuesta...');
            $('.reclamo.responder input.responder_btn').click(
                function(){
                    var form = $(this).parent().parent();
                    var textarea = $(form).find('textarea');
                    if($(textarea).val() != 'Escribe tu respuesta...' && $(textarea).val() != ''){
                        $(form).submit();
                    }else{
                        alert('Debes escribir una respuesta.');
                    }
                }
            );
        }
        
        if($('.np_tooltip_especifico').length){
            $('.np_tooltip_especifico').each(
                function(){
                    var tooltip = $(this);
                    $('#'+$(this).attr('for')).focus(
                        function(){
                            $(tooltip).css('background','#FFFFCC');
                        }
                    );
                    $('#'+$(this).attr('for')).blur(
                        function(){
                            $(tooltip).css('background','#EEEEEE');
                        }
                    );
                    $('#'+$(this).attr('for')).hover(
                        function(){
                            $(tooltip).css('background','#FFFFCC');
                        },
                        function(){
                            if(!$(this).is(":focus")){
                                $(tooltip).css('background','#EEEEEE');
                            }
                        }
                    );
                }
            );
        }
        
        if($('span.retomar_pago').length){
            $('span.retomar_pago').click(
                function(){
                    $(this).parent().find('form').submit();
                }
            );
        }
        
        if($('.eliminar_btn').length){
            $('.eliminar_btn').click(
                function(){
                    
                    var clase = $(this).attr('class');
                    
                    if(clase.indexOf('seguimiento') != -1){
                        var publicacion_id = $(this).parent().parent().attr('id');
                        publicacion_id = publicacion_id.substr(12);
                        if(confirm('\u00BFSeguro que desea dejar de seguir el art\u00EDculo seleccionado?')){
                            $.ajax({
                                type: 'POST',
                                cache: false,
                                url: '../ajax/opciones_ajax.php',
                                data: 'accion=eliminarSeguimiento&publicacion_id='+publicacion_id,
                                success: function(data){
                                    if(data !== 'true'){
                                        alert('Ha ocurrido un error al intentar realizar la acci\u00E1n solicitada. Disculpe las molestias ocacionadas.');
                                    }
                                    window.location.href = window.location.href;
                                }
                            });
                        }
                    }
                    
                }
            );
        }
        
        if($('.lista-productos').length){
            adaptarPublicacionesHome();
        }
        
        $(window).resize(
            function(){
                if($('.list_carousel').length){
                    adaptarCarrousel();
                }
                if($('.lista-productos').length){
                    adaptarPublicacionesHome();
                }
            }
        );
        if($('#detalle iframe').length){
            setInterval("ajustarTamanoDescripcion()",1000);
        }
        
        $('#buscarporprecio').click(function(){
            url = $(this).attr("url");
            url = url+'&precio_desde='+$('#precio_desde').val()+'&precio_hasta='+$('#precio_hasta').val();
            window.location.href=url;
       
        });
        
            $("#precio_desde").keypress(function(event) {
                if(event.which == 13){
                    $('#buscarporprecio').click();
                }else{
                    
                }
                if((event.which > 47 && event.which < 58)||(event.which == 46)||(event.which == 0)||(event.which > 7 && event.which < 16)){
                    return event.which;
                }else{
                    return false;
                }
            });
        
        
        
            
        
      
            
    });
    

function ajustarTamanoDescripcion(){

    if(jQuery.browser.msie){
        $('#iframedetalle').css('height', document.iframedetalle.document.body.scrollHeight+30);
    }else{
        $('#detalle iframe').css('height',$('#detalle iframe').contents().find("body").height()+15);
    }
    $('#detalle').css('visibility','visible');
    
}
window.size = function(){
	var w = 0;
	var h = 0;
	if(!window.innerWidth){
		if(!(document.documentElement.clientWidth == 0)){
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}else{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}else{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
}

function adaptarCarrousel(){
  
    var articulos_carrousel = Math.floor(((((window.size().width/10)*9)/10)*9)/195);
    if(articulos_carrousel >= 4){
        if(articulos_carrousel>5){
            articulos_carrousel = 5;
        }
        $('.caroufredsel_wrapper').css('width',195*articulos_carrousel);
        return 195*articulos_carrousel;
    }

}

function adaptarPublicacionesHome(){
    var publicaciones_home = Math.floor(((window.size().width/100)*54)/200);
    if(publicaciones_home < 3){
        $('.col-3').css('display','none');
        $('.col-2 ul.lista-productos li .detalle').css('border-right','none');
        $('.col-1,.col-2').css('width','50%');
    }else{
        $('.col-1,.col-2,.col-3').css('width','33%');
       /*  $('.col-2 ul.lista-productos li .detalle').css('border-right','1px dashed #C8C8C8'); */
       $('.col-2 ul.lista-productos li .detalle').css('border-right'); 
        $('.col-3').css('display','block');
    }
}
function ValidaIngresoNumerosDecimales(evt){
    
	// usar en el formulario: onKeyPress="return ValidaIngresoSoloNumeros(event)"
	var nav4 = window.Event ? true : false;
	var key = nav4 ? evt.which : evt.keyCode;
    if(key==13){
        $('#buscarporprecio').click();
    }
 
   // alert(key);
	return ((key > 47 && key < 58)||(key == 46)||(key == 0)||(key > 7 && key < 16));
}

// ]]>
