
/* navbar.js */
/*
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);



var navBar = {
	init:function(){
		var nav = $("#navBar");
		var _this = null;
		var itemsSub = nav.find(".more");
		var tm = 0;
		//Set custom configurations
		var config = {
     		sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
     		interval: 100, // number = milliseconds for onMouseOver polling interval
     		over: this.over, // function = onMouseOver callback (REQUIRED)
     		timeout: 300, // number = milliseconds delay before onMouseOut
     		out: this.out // function = onMouseOut callback (REQUIRED)
		};
	
		itemsSub.hoverIntent(config); 
		
	
		
	},
	over:function(){
		var _this = $(this);		
		_this.find("a:first").addClass("fix");
		_this.find("a:eq(0)").next().stop().show(); 
		_this.addClass("show");
    
	},
	out:function(){
		var _this = $(this);		
		_this.removeClass("show");		
		_this.find("a:first").removeClass("fix");
		_this.find("a:eq(0)").next().stop().hide();  
		
  	
	}
}



/* funcioncomparador.js */

var cajaComparar =
{
//    comphref:'',
    data:null,
    fixedd:null,
    movilesAcomparar:0,
    topInicial:0,
    hBox:0,
    margenInf:6,
    isIE6:false,

    init:function()
    {
        var __this = this;
        var chks = $("div.check input");
        this.isIE6 = (typeof document.body.style.maxHeight === "undefined");

		if (comp_ini == '1')
		{
			$.ajax({
				'url': "/usuarios/ajax/aj_comparadorTerminales.php",
				'dataType': 'html',
				'type': 'POST',
				'data': "accion=inicio",
				'success': function(data){
					__this.data = $(data);
					if (data != "")
					{
						__this.fixedd = $("#cajaComparar");
						__this.fixedd.remove();
						__this.createBox(0);
					}
				}
			});
		}

        chks.bind("click",function()
        {
            if (this.checked)
            {
                if (__this.fixedd != null && __this.fixedd.find("li").length >= 3)
                {
                    alert("Lo sentimos, de momento sólo puedes comparar 3 móviles como máximo");
                    $(this).removeAttr("checked");
                    return true;
                }

                acc_comp = 'anade_term';
                $.ajax({
                    'url': "/usuarios/ajax/aj_anadeAlComparador.php",
                    'dataType': 'html',
                    'type': 'POST',
                    'data': "accion=compara_estadoVentana&estado=max",
                    'success': function(data){
                    }
                });
            }
            else
                acc_comp = 'quita_term';

            __this.topInicial = parseInt($(this).offset().top);

            $.ajax({
                'url': "/usuarios/ajax/aj_comparadorTerminales.php",
                'dataType': 'html',
                'type': 'POST',
                'data': "accion="+acc_comp+"&urlm=" + $(this).val(),
                'success': function(data){
                    __this.data = $(data);
                    __this.fixedd = $("#cajaComparar");
                    __this.fixedd.remove();
                    __this.createBox(1);
                }
            });
        })
    },
    removeAll:function()
    {
        var __this = this;

        $.ajax({
            'url': "/usuarios/ajax/aj_comparadorTerminales.php",
            'dataType': 'html',
            'type': 'POST',
            'data': "accion=quita_todos",
            'success': function(data){
                __this.fixedd = $("#cajaComparar");
                __this.fixedd.remove();
            }
        });
    },
    removeThis:function(obj)
    {
        var items = this.fixedd.find("li").length;
        var aux = this.fixedd.find(".boton");
        var li = obj.parent().parent();
        var neutro = this.fixedd.find(".neutro").length;

        if(neutro == 1)
        {
            this.removeAll();
        }
        else
        {
            if(items == 2)
            {
                this.fixedd.find(".reset").removeClass("reset");
                li.parent().append($('<li class="reset neutro"><span class="sprite spImgMscavacCont" href="/"><img class="spriteImg spImgMscavacImg" src="http://ww1.moviles.com/images/sprite10.gif" alt="" width="584" height="273" /></span><span class="sel">'+literal["sel"]+'</span></li>'))
                neutro = 1;
                aux.addClass("desactive");
                aux.empty();
                aux.append($("<span>"+literal["comparar"]+"</span>"))
            }

            $.ajax({
                'url': "/usuarios/ajax/aj_comparadorTerminales.php",
                'dataType': 'html',
                'type': 'POST',
                'data': "accion=quita_term&urlm=" + obj.attr("id"),
                'success': function(data){
					/*
                    __this.data = data;
                    __this.fixedd = $("#cajaComparar");
                    __this.fixedd.remove();
                    __this.createBox(1);          */      }
            });

            li.remove();
            items--;
            this.hBox = this.fixedd.height();
        }
    },
    changeToolBar:function(obj, maximiz)
    {
        var parentt = obj.parent();
        var neutro = this.fixedd.find(".neutro").length;
        var items = this.fixedd.find("li").length - neutro;
        var msg = null;
        var aux = parentt.find("a:eq(0)").next();

        aux.remove();

        if(!maximiz)
        {
            msg = ((items) > 1) ? "<span>" + literal["comparar"] + "</span> " + items + " " + literal["telefonos"] : "<span>" + literal["comparar"] + "</span> " + items + " " + literal["telefono"];

            $("#moscoj").removeClass('IcoMinimizarMos').addClass('IcoMaximizarMos');
            parentt.append($('<span class="boton"><a href="/comparar">'+msg+'</a></span>'))
        }
        else
        {
            $("#moscoj").removeClass('IcoMaximizarMos').addClass('IcoMinimizarMos');
            parentt.append($('<span>'+literal["comparar"]+ ' ' +literal["telefonos"] + '</span>'))
        }
    },
    refreshPos:function(obj){		// refrescamos posición tras borrar elementos y acortar la caja
        var bottom = $(window).height() - this.hBox - this.margenInf;
        var y = $(window).scrollTop();
        if(this.isIE6) this.fixedd.css("top", y+bottom);
    },
    createBox:function(chkpul)
    {
        this.data.appendTo("body");
        this.data.bgIframe();
        this.fixedd = this.data;
        var __this = this;
        var _this = aux = inner = null;
        var hToolBar = 0;
        this.hBox = this.fixedd.height();	// altura de la caja de comparar
        var items = this.fixedd.find("li");
        var toolBar = this.fixedd.find(".toolBar a");

        var topDiv = this.fixedd.offset().top;	// top de la caja de comparar
        var wrapperOtros = $("#wrapperOtros");
        var wrapperFooter = $("#wrapperFooter");
        var alturaBod = document.body.offsetHeight;
        var trigger_down = 50;
        var trigger_up = 160;
        var tope =  leftInicial = 0;
        var duracion = 500;
        var neutro = this.fixedd.find(".neutro").length;
        var elementos = this.fixedd.find("li").length - neutro;

        if (chkpul == 0 && elementos >= 1 )
            duracion = 0;

        if($("#wrapperOtros").length!= 0){
            tope = (parseInt(wrapperOtros.offset().top) + wrapperOtros.height()) - $("#wrapperOtros #wrapper > div:eq(1)").height();
                // averiguo la coordenada x para ajustar la caja en mayores resoluciones. La caja está en absoluto dentro del body en lugar del contenedor central.
            leftInicial = wrapperOtros.offset().left + wrapperOtros.outerWidth() - this.fixedd.outerWidth();
        }else{
            tope = (parseInt(wrapperFooter.offset().top) + wrapperFooter.height());
            leftInicial = wrapperFooter.offset().left + wrapperFooter.outerWidth() - this.fixedd.outerWidth();
        }

        var topSideBar = $("#sideBar").offset().top;
        var bottom = $(window).height() - __this.hBox; // para posicionarlo al final del área visible siempre
        var y = $(window).scrollTop();


        //Animacion inicial - al pulsar en el checkbox compruebo que muestro la caja dentro del area visible posicionada abajo

        if(this.isIE6)
        {
            this.fixedd.css("top",$(window).height())
            if( (this.topInicial+this.hBox) > (y + bottom) ){
                this.fixedd.animate({"top":y+bottom-this.margenInf},duracion);
            }else{
                this.fixedd.animate({"top":this.topInicial-this.margenInf},duracion);
            }
        }else{
            this.fixedd.css({"position":"fixed", "bottom":"-50px", "top":"auto"});
            this.fixedd.animate({"bottom":0},duracion);
        }

        this.fixedd.css("left",leftInicial);
        this.fixedd.css("right","auto");

        // fin Animacion inicial
        items.find(".borrar a").bind("click",function(){
                cajaComparar.removeThis($(this));
                cajaComparar.refreshPos();
                return false;
        })

        inner = __this.fixedd.find(".wrap");
        
/*        if (elementos > 1 )
           this.comphref = $("#idbtn_comp").attr("href");  
  */     
        if($("#cajaComparar").hasClass("max"))
        {
            inner.show();
            cajaComparar.changeToolBar(toolBar, true);
        }
        else
        {    
            inner.hide();
            cajaComparar.changeToolBar(toolBar, false)
        }

        toolBar.bind("click",function()
        {
            var top = parseInt(__this.fixedd.offset().top) - 10;
            var efectoOcultar = 0;
            _this = $(this);
            aux = _this.parent().parent();
            hToolBar = $(".toolBar").outerHeight();
            inner = __this.fixedd.find(".wrap");

            if(_this.parent().parent().hasClass("max"))
            {
                $.ajax({
                    'url': "/usuarios/ajax/aj_anadeAlComparador.php",
                    'dataType': 'html',
                    'type': 'POST',
                    'data': "accion=compara_estadoVentana&estado=min",
                    'success': function(data){
                    }
                });
                aux.removeClass("max");
                aux.addClass("min");
                efectoOcultar = inner.outerHeight() + hToolBar;
                inner.hide();
                cajaComparar.changeToolBar(_this, false);
                if(__this.isIE6)
                    __this.fixedd.css("top",  top + efectoOcultar);
                __this.hBox = __this.fixedd.height();
            }
            else
            {
                $.ajax({
                    'url': "/usuarios/ajax/aj_anadeAlComparador.php",
                    'dataType': 'html',
                    'type': 'POST',
                    'data': "accion=compara_estadoVentana&estado=max",
                    'success': function(data){
                    }
                });
                aux.removeClass("min");
                aux.addClass("max");
                efectoOcultar = inner.outerHeight() - hToolBar + __this.margenInf;
                inner.show();
                if(__this.isIE6)
                    __this.fixedd.css("top", top - efectoOcultar);
                cajaComparar.changeToolBar(_this, true)
                __this.hBox = __this.fixedd.height();
            }
           
            return false;
        })

        if(this.isIE6)
        {
            $(window).scroll(function (event)
            {
                bottom = $(window).height() - __this.hBox; // para posicionarlo al final del área visible siempre
                y = $(this).scrollTop();
                topDiv = __this.fixedd.offset().top;

                __this.fixedd.css("top", y + bottom - __this.margenInf);

                if(y < trigger_up){	// cuando llego arriba
                        __this.fixedd.css("top", topSideBar - __this.margenInf);
                }
            });
        }
    }
}


/* buscadorRapido.js */
var YA = false;

function iniciaBuscadorRapido ()
{        
    $("select#busrap_marca").change(function()
    {        
        $.ajax({
           type: "POST",
           url: "/usuarios/ajax/aj_buscadorRapido.php",
           data: "accion=dame_modelos&marca=" + $(this).val(),
           success: function(msg) 
           { 
               $("select#busrap_modelo").html(msg);
           }
        }); 
    });

    $('#buscador').submit(function()
    {
        if ($('#busrap_marca').val() == "" || $('#busrap_marca').val() == "Seleccionar")
        {
            alert("Debes seleccionar una marca.");
            $('#busrap_marca').focus();
            return false;
        }

        if ($('#busrap_modelo').val() == "" || $('#busrap_modelo').val() == "Seleccionar")
        {
            alert("Debes seleccionar un modelo.");
            $('#busrap_modelo').focus();
            return false;
        }

        if ( YA == true )
        {
            alert("Un momento por favor, ya estamos procesando tu peticion.");
            return false;
        }
        YA = true;

        window.location.href='/' + $('#busrap_marca').val() + '/' + $('#busrap_modelo').val();
        return false;
    });
}

/* filtrohome.js */
function iniciaFiltroHome ()
{       
    $('#elige').submit(function() 
    {
        var nc=0;
        var ArrUrls = new Array() 
        $('input:checkbox:checked').each(function(i) 
        {   
            ArrUrls[nc]=this.value;                
            nc++;
        });

        if (nc == 0)
        {
            alert ("Debe seleccionar un criterio.");
            return false;
        }        

        ArrUrls.sort();
        url = "";
        for (c=0;c<nc;c++)         
        {   
            if (c>0)
               url = url + "-";

            url = url + ArrUrls[c];
        }

        window.location.href=$("#url_ini").val() + '/' + url;
        return false;
    });
}

function iniciaFiltroHome1 ()
{       
    $('#elige').submit(function() 
    {
        if ($('input:checkbox:checked').length == 0)
        {
            alert ("Debe seleccionar un criterio.");
            return false;
        }        

        return true;
    });
}



/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-21 18:45:56 -0500 (Sat, 21 Jul 2007) $
 * $Rev: 2447 $
 *
 * Version 2.1.1
 
 */
(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};})(jQuery);

var literal = [];
	
literal["masCar"] = "Más características";
literal["masOp"] = "Más opciones";
literal["masOpe"] = "Más operadoras";
literal["menCar"] = "Menos características";
literal["menOp"] = "Menos opciones";
literal["menOpe"] = "Menos operadoras";
literal["def"] = "Definir rangos";
literal["masMar"] = "Más marcas";
literal["masOpec"] = "Otras opciones de búsqueda";
literal["comparar"] = "Comparar";
literal["telefono"] = "teléfono";
literal["telefonos"] = "teléfonos";
literal["sel"] = "Selecciona otro móvil para comparar";

	
var behaviours = {
    init:function(){
        this.colapsables();
        this.movilesVisitados();        
    },
    colapsables:function(){
        var bloque = $(".mod");
        var filasOcultas = bloque.find(".hide");
        var acciones = parentt = null;
        var destacados = $(".destacado");
        var id = ""
        var aux = $(".comparate .imagen");
			
							
        $("#wrapperFooter").hide();
        filasOcultas.hide();
        $("#wrapperFooter").show();
			
			
        ($("#elige").find(":submit")).before($("<span class='more'><a href=''>"+literal["masCar"]+"</a></span>"));
			
        destacados.eq(0).append($("<span class='more'><a href=''>"+literal["masOp"]+"</a></span>"));
		
//        destacados.eq(2).append($("<span class='more'><a href=''>"+literal["def"]+"</a></span>"));
        destacados.eq(3).append($("<span class='more'><a href=''>"+literal["masOp"]+"</a></span>"));
			
        var puntos = $(".divMore > span span").html();
        $(".divMore > span").empty();
        $(".divMore > span").append($('<a href="">'+literal["masOpec"]+'</a><span>'+puntos+'</span>'));
			
        acciones = bloque.find(".more a");
			
        acciones.bind("click",function(){
            $("#wrapperFooter").hide();
            aux.css("position","static");
            parentt = $(this).parent().parent();
            parentt.find(".hide").toggle();
            var spamm = $(this).parent();
            if(parentt.attr("class") == "divMore"){
                parentt.find("li.hide").hide();
                spamm.remove();
					
            }
            var texto = $(this).text();
            switch (texto){
                case literal["masCar"]:
                    $(this).text(literal["menCar"]);
                    spamm.addClass("less");
                    break;
                case literal["menCar"]:
                    $(this).text(literal["masCar"]);
                    spamm.removeClass("less");
                    break;
                case literal["masOp"]:
                    $(this).text(literal["menOp"]);
                    spamm.addClass("less");
                    break;
                case literal["menOp"]:
                    $(this).text(literal["masOp"]);
                    spamm.removeClass("less");
                    break;
                case literal["def"]:
                    spamm.toggleClass("less");
                    break;
                default:
                    break;
            };
            $("#wrapperFooter").show();
            aux.css("position","relative");
            return false;
        })	
    },
    movilesVisitados:function(){
        var obj = $("#ultimos");
        var linkElement = obj.prev();
        obj.hide();
        obj.find("input:submit").parent().remove();
        linkElement.bind("click",function(){
            obj.toggle();
            $(this).toggleClass("less");
            return false;
        })
    }
}

var links={
	printLink:function(){
		var modHerramientas = $("#modHerramientas > ul");	
//		modHerramientas.append("<li class='print'><a href='javascript:window.print()'>"+literal["imprimir"]+"</a></li>")
	},    
    marcas:function(){
        $('.porOpe .mas a').bind("click", function(){
            $.ajax({
                type:"POST",
                dataType:"html",
                url:"/usuarios/ajax/aj_listaOperadores.php",
                success:function(html){

                    $('.porOpe').empty();
                    $('.porOpe').append(html);
                }
            });
            return false;
        });
        $('.porMar .mas a').bind("click", function(){
            $.ajax({
                type:"POST",
                dataType:"html",
                url:"/usuarios/ajax/aj_listaMarcas.php",
                success:function(html){

                    $('.porMar').empty();
                    $('.porMar').append(html);
                }
            });
            return false;
        });
    }
}



var customChks = {
		init:function(){
			var chks = $(".customChk");
			var parentt = _this = null;

			chks.bind("mousedown",function(){
				_this = $(this);
				parentt = _this.parent();
				_this.addClass("act");
			})

			chks.find(":checkbox").bind("click",function(){
				_this = $(this);
				parentt = _this.parent();
				parentt.removeClass("act");
				if(_this.is(":checked")){
					parentt.addClass("checked");
				}else{
					parentt.removeClass("checked");
				}

			})

		}
	}
	
jQuery(document).ready(function() {	
	navBar.init();	
    cajaComparar.init();
    behaviours.init();
	links.printLink();
    links.marcas();
    iniciaBuscadorRapido();
    iniciaFiltroHome1();	
})

