// JavaScript Document

$(function() {
	
	$('.tooltips').tooltip({
		track: true,
		delay: 0, 
		showURL: false, 
		showBody: " - ", 
		fade: 250				   
	});
	
	$('.tooltips_imagen').tooltip({
	    track: true,
		delay: 0, 
		showURL: false, 
		bodyHandler: function() { 
			return $("<img/>").attr("src", this.src); 
		} 
	});

	$('.tooltips_imagen_titulo').tooltip({
	    track: true,
		delay: 0, 
		showURL: false, 
		bodyHandler: function() { 
			return $("<img/>").attr("src", this.rel); 
		} 
	});
	
	$('#txtbusqueda').focus(function() {
		if ($("#txtbusquedamsg").val() == '') {
			$("#txtbusquedamsg").val(this.value);
		}
		if ($("#txtbusqueda").val() == $("#txtbusquedamsg").val()) {
			this.value = '';
		}
	});
	$('#txtbusqueda').blur(function() {
		if ($.trim(this.value) == '') {
			this.value = $('#txtbusquedamsg').val();
		}
	});
	
	$('.auto-submit-star').rating(
	  /*{ callback: function(value, link) { 
	  	var arr = this.name.split('_');
	  	AbreVotacion(arr[1], value);
	  } 
	}*/
	);
        $("#submit_newsletter").click(newsletter_usuario_alta);
        $("#anterior_oportunidad").click(function (){MoveOportunidad('left')});
        $("#siguiente_oportunidad").click(function (){MoveOportunidad('right')});
        $("#login_usuario, #login_clave").keydown(function(e) {if (e.keyCode == 13) {loginportal();}});
        $("#txtbusqueda").keydown(function(e) {if (e.keyCode == 13) {buscar();}});
        $("#button_display_refinarbusqueda").click(function (){
            if($("#listafamilias_bloque").hasClass('showrefinar')){
                $("#listafamilias_bloque").removeClass('showrefinar');
                $("#listafamilias_bloque").slideUp('slow');
            }else{
                $("#listafamilias_bloque").addClass('showrefinar');
                $("#listafamilias_bloque").slideDown('slow');
            }
        });
    
    $("#txtbusquedamsg").val(jQuery("#txtbusqueda").val());
    $("#cbx_controlorden").change(function(){
        //console.debug($("#cbx_controlorden").val());
        location.href = $(this).val();
        return;
    });
});

function changeView(mode){
    jQuery.ajax({
    type: "GET",
    url: 'http://'+HTTP_HOST+"/grabar_seteos.php",
    data: { v: mode },
    dataType: "json",
    success: function(data){
            if(data.result != undefined){
                if(data.result == 'ok'){
                    window.location.reload();
                }else{
                    alert('No es posible cambiar la vista');
                }
            }else{
                alert('No es posible cambiar la vista');
            }
        }

    });
}
function enviar_llamada(){
    msg = "";
    if($.trim($('#llamada_telefono').val()) == ""){
        msg = '<?=translation::traduce("Debe ingresar el teléfono.")?>';
    }
    if($.trim($('#llamada_nombre').val()) == ""){
        msg = '<?=translation::traduce("Debe ingresar el nombre.")?>';
    }
    if(msg == ""){
        $('#form_llamada').hide();
        $('#ajax_loader').show();
        jQuery.ajax({
        type: "GET",
        url: 'http://'+HTTP_HOST+"/envio_llamada.php",
        data: { nombre: $('#llamada_nombre').val(), telefono: $('#llamada_telefono').val() },
        dataType: "json",
        success: function(msg){
                $('#ajax_loader').hide();
                if(msg == 1) {
                    $('#llamada_nombre').val('');
                    $('#llamada_telefono').val('');
                    $('#resp_llamada_ok').show().animate({opacity: 1.0}, 5000).fadeOut('slow', function() {
                        jQuery('#form_llamada').show();
                    });
                } else {
                    $('#resp_llamada_error').show().animate({opacity: 1.0}, 5000).fadeOut('slow', function() {
                        jQuery('#form_llamada').show();
                    });
                }
            }
        });
    }else{
            $('#frm_msg_validate').html(msg);
            jQuery('#form_llamada').hide();
            jQuery('#frm_msg_validate').show().animate({opacity: 1.0}, 3000).fadeOut('slow', function() {
                    jQuery('#form_llamada').show();
            });
        }
    }


function newsletter_usuario_alta(){
    if($.trim($("#email_newsletter").val()) != ''){
        $.ajax({
                type: "GET",
                url: 'http://'+HTTP_HOST+"/newsletter_usuarios.php",
                data:{
                        action:'alta',
                        email_newsletter:$("#email_newsletter").val()
                } ,
                dataType:"json",
                success: function(msg){
                        if (msg.grabacion == 'ok') {
                            jQuery(".form_subscription").hide('slow',function(){
                                jQuery(".result_subscription").show('slow',function(){
                                    $(this).animate({display:'inherit'},2000,function(){
                                        jQuery(".result_subscription").hide('slow',function(){
                                            jQuery("#email_newsletter").val('');
                                            jQuery(".form_subscription").show('slow');
                                        })
                                    });
                                });
                            })
                        }
                }
        })
    }
}

function AbreBienvenida(url, titulo) {
    Shadowbox.open({
        player:     'iframe',
        title:      titulo,
        content:    url,
        height:     300,
        width:      525
    });
}
function AbrePromocionesEspeciales(url, titulo) {
    Shadowbox.open({
        player:     'img',
		gallery:	'promociones_especiales',
        content:    url,
		title:		titulo
    });
}
function AbreVista3D(url, titulo) {
    Shadowbox.open({
        player:     'iframe',
		title: 		titulo,
        content:    url,
        height:     245,
        width:      525
    });
}
function AbreShadowCondiciones(pagina){
	Shadowbox.open({
        player:     'iframe',
        content:    pagina,
        height:     400,
        width:      400
    });		
}
function ImprimirDetalle(id) {
    var parametros = "id="+id+"&accion=imprimir";	
	Shadowbox.open({
        player:     'iframe',
        content:    'http://'+HTTP_HOST+'/productos_detalle_formulario.php?'+parametros,
        height:     600,
        width:      800
    });		
}
function cambiaImagenCliente() {
	alert("En Construcción");
}
function EnviarCliente(id, idproducto) {
    Shadowbox.open({
        player:     'iframe',
        content:    'http://'+HTTP_HOST+'/listclientes_envios.php?id='+id+'&idproducto='+idproducto,
        height:     400,
        width:      600
    });
};

function AbreVotacion(id, valor) {
    Shadowbox.open({
        player:     'iframe',
        content:    'http://'+HTTP_HOST+'/listproductos_votacion.php?id='+id+'&valor='+valor,
        height:     340,
        width:      600
    });
};

// Descargar Tarifas (Link: top.php)
function DescargarTarifas(pagina) {
    Shadowbox.open({
        player:     'iframe',
        content:    pagina,
        height:     340,
        width:      600
    });
};


function EstadoSplash(estado) {
	if (estado == 1) {
		$('html, body').animate({scrollTop:0}, 'slow'); 
		$('#overlay').height($(document).height());
		$('#overlay, #modal').fadeIn('slow');
	} else {
		$('#overlay, #modal').fadeOut('slow'); 
	}
}

function EstadoProyector(estado) {
	if (estado == 1) {
		jQuery("#funcion_proyector_abrir").hide();
		jQuery("#funcion_proyector_cerrar").show();
		jQuery("#swftopportal").slideDown('slow', SeteaVariableSession('proyector_abierto', '1'));
	} else {
		jQuery("#funcion_proyector_abrir").show();
		jQuery("#funcion_proyector_cerrar").hide();
		jQuery("#swftopportal").slideUp('slow', SeteaVariableSession('proyector_abierto', '0'));
	}
}

function SeteaVariableSession(variable, valor) {
	var parametros = "variable=" + variable + "&valor=" + valor;
	jQuery.ajax({
		type: "GET",
		url: 'http://'+HTTP_HOST+"/ajax/ajax_setea_variable_session.php",
		data: parametros
	});
}

function VisitadosLimpiar() {
	var parametros = "id=-1";
	jQuery.ajax({
		type: "GET",
		url: 'http://'+HTTP_HOST+"/ajax_visitados_borrar.php",
		data: parametros,
		dataType:"json",
		success: function(msg){
			if (msg.result == 'ok') {
				jQuery("#div_lateral_ultimos_visitados").load('http://'+HTTP_HOST+'/listvisitados_bloque.php');
			}
		}
	});	
}
function NotificacionStock(id,tipo,idproducto) {
	Shadowbox.open({
        player:     'iframe',
        content:    'http://'+HTTP_HOST+'/notificacion_stock.php?id=' + id + '&tipo=' + tipo + '&idproducto=' + idproducto,
        height:     230,
        width:      400
    });
}

function ComoLlegar() { 
	var _inicio = jQuery("#recorrido_inicio").val();
	var _fin =  jQuery("#recorrido_fin").val();
	if(_inicio == "") {
		alert("Complete la Dirección de Inicio");
		jQuery("#recorrido_inicio").focus();
		return;
	}
	if(_fin == "-1") {
		alert("Seleccione una Delegación");
		jQuery("#recorrido_fin").focus();
		return;
	}
	window.open("http://maps.google.com/maps?lsm=1&daddr=" + _fin + "&geocode=&dirflg=&saddr=" + _inicio + "&f=li&hl=es");
}

jQuery(document).ready(function(){
       mainmenu();
       menulateral();
       $("#btn_indentificarse").click(identificacion_portal);
       //displaysubmenulateral($("#menu_lateral li.lateral.grupo_0"));//para configurar que se muestre el grupo que esta seleccionado

       setInterval("moreSpotlight()", 5000);
       //setInterval("moreOportunidades()", 5000);
});

function moreSpotlight() {
        /*var mover = 0;
        var tamanodiv = 0;
        if(isNaN(parseInt($("#spotlight_container").css('left'),10))){
            $("#spotlight_container").css('left',0);
        }
        mover = parseInt($("#spotlight_container").css('left'),10) - 250;        
        tamanodiv = -parseInt($("#spotlight_container").css('width'),10);        
        if(mover-1000<tamanodiv){
            mover=0;
        }
        $("#spotlight_container").animate({left: mover}, 2000);*/
    var spot_position = isNaN(parseInt($("#spotlight_container").css('left'),10)) ? 0 : parseInt($("#spotlight_container").css('left'),10);
    var tamanodiv = 0;
    var totalitems = $("#spotlight_container div.spotlight_list_cell").length;
    tamanodiv = totalitems*250;
    $("#spotlight_container").css('width',tamanodiv);
    var side = $("#spotlight_container input#side").val();
    var new_spot_position = 0;
    if(totalitems>4){
        switch (side){
            case 'left':
                new_spot_position = spot_position - 250;
                if(new_spot_position-(4*250)<=-tamanodiv){
                    new_spot_position = -tamanodiv+(4*250);
                    $("#spotlight_container input#side").val('right');
                }
                break;
            case 'right':
                new_spot_position = spot_position + 250;
                if(new_spot_position>=0){
                    new_spot_position = 0;
                    $("#spotlight_container input#side").val('left');
                }
                break;

        }
        $("#spotlight_container").animate({left: new_spot_position}, 2000);
    }
        
}
function MoveOportunidad(side) {
    var spot_position = isNaN(parseInt($("#oportunidades_container").css('left'),10)) ? 0 : parseInt($("#oportunidades_container").css('left'),10);
    var tamanodiv = 0;
    var totalitems = $("#oportunidades_container div.spotlight_list_cell").length;
    tamanodiv = totalitems*264;
    $("#oportunidades_container").css('width',tamanodiv);    
    var new_spot_position = 0;
    if(totalitems>3){
        switch (side){
            case 'left':
                new_spot_position = spot_position - 264;
                if(new_spot_position-(3*264)<=-tamanodiv){
                    new_spot_position = -tamanodiv+(3*264);
                }
                break;
            case 'right':
                new_spot_position = spot_position + 264;
                if(new_spot_position>=0){
                    new_spot_position = 0;
                }
                break;
                
        }        
        $("#oportunidades_container").animate({left: new_spot_position}, 2000);
    }

}

function resetSpotlight() {
	/*$("#spotlight_container div.spotlight_list_cell:first").clone().appendTo(".spotlight_content");
	$("#spotlight_container div.spotlight_list_cell:first").remove();*/
	//$("#spotlight_container").removeAttr("style");
}

function moreOportunidades() {
	$("#oportunidades_container").animate({left: -263}, 2000, "", function() {/*resetSpotlightOportunidades();*/});
}

function resetSpotlightOportunidades() {
	$("#oportunidades_container div.spotlight_list_cell:first").clone().appendTo(".oportunidades_content");
	$("#oportunidades_container div.spotlight_list_cell:first").remove();
	$("#oportunidades_container").removeAttr("style");
}

function mainmenu(){
$("#menu_principal ul").css({display: "none"}); // Opera Fix
$("#menu_principal li.principal").hover(function(){
		$(this).addClass("hoverclass");
		$(this).find('a.link_menu').css({color:'#fff'});
		$(this).find('ul:first').css({visibility: "visible", display:'block'}).slideDown(400);
	},function(){
		$(this).find('a.link_menu').css({color:'#000'});
		$(this).removeClass("hoverclass");
		$(this).find('ul:first').css({visibility: "hidden"});
	});
$("#menu_categorias li.menucategorias").hover(function(){
		$(this).addClass("hoverclass");
		$(this).find('a.link_menu').css({color:'#fff'});
		$(this).find('ul:first').css({visibility: "visible", display:'block'}).slideDown(400);
	},function(){
		$(this).find('a.link_menu').css({color:'#000'});
		$(this).removeClass("hoverclass");
		$(this).find('ul:first').css({visibility: "hidden"});
	});

}
function menulateral(){
$("#menu_lateral li ul").css({display: "none"}); // Opera Fix
$("#menu_lateral li.lateral").hover(function(){
            displaysubmenulateral($(this));
	}, function(){	
            hidesubmenulateral($(this));
        });
}
function hidesubmenulateral(menu){
    menu.find('a.link_menu').css({color:'#000'});
    menu.removeClass("hoverclass");
    menu.find('ul:first').css({visibility: "hidden"});
    $("#menu_lateral li ul").css({display: "none"});
}
function displaysubmenulateral(menu){
    menu.addClass("hoverclass");
    menu.find('a.link_menu').css({color:'#fff'});
    menu.find('ul:first').css({visibility: "visible", display:'block'}).slideDown(400);
}

function loginportal() {
  VerificaLogin(jQuery('#login_usuario').val(), jQuery('#login_clave').val());
}

function identificacion_portal(){
    VerificaLogin(jQuery('#identificacion_usuario').val(), jQuery('#identificacion_clave').val());
}

function VerificaLogin(usu, cla) {
  jQuery('#clientes_respuesta_general, #clientes_respuesta_general_formulario').hide();  
  $.ajax({
		type: "GET",
	   	url: 'http://'+HTTP_HOST+"/login_ajax.php",
	   	data: {usuario:usu,clave:cla,url_from:location.href},
       	dataType: "json",
       	async:false,
		success: function(resp){

			if(resp.grabacion == 'ok'){                                
				location.href = resp.urlredirect;
			} else if(resp.grabacion == 'error') {
                            jQuery('#cuadrologin').hide();
                            jQuery('#clientes_respuesta_general, #clientes_respuesta_general_formulario').html(login_error);
                            jQuery('#clientes_respuesta_general, #clientes_respuesta_general_formulario').show().animate({opacity: 1.0}, 2000).fadeOut('slow', function() {
                                    jQuery('#cuadrologin').show();
                            });
			} else {
				jQuery('#clientes_respuesta_general, #clientes_respuesta_general_formulario').html('Error');
				jQuery('#clientes_respuesta_general, #clientes_respuesta_general_formulario').fadeIn();
			}
	   }

  });

}

function DisplayMenu() {
    $('#navmenu-v').show();
}