$(function(){
    
    $.support.transition = (function () {
        var thisBody = document.body || document.documentElement
        , thisStyle = thisBody.style
        , support = thisStyle.transition !== undefined || thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.MsTransition !== undefined || thisStyle.OTransition !== undefined
        return support
    })()

    // set CSS transition event type
    if ( $.support.transition ) {
        transitionEnd = "TransitionEnd"
        if ( $.browser.webkit ) {
            transitionEnd = "webkitTransitionEnd"
        } else if ( $.browser.mozilla ) {
            transitionEnd = "transitionend"
        } else if ( $.browser.opera ) {
            transitionEnd = "oTransitionEnd"
        }
    }
    
    $('#btn_notificaciones').click(function(event){
        event.preventDefault();
        verDropDown("notificaciones",this);
    });
    
    $('#btn_mis-postulaciones').click(function(event){
        event.preventDefault();
        verDropDown("mis-postulaciones",this);
    });
    
    
    //Links para los paises del footer (SEO)

    $('.selectPais li').click(function(){
		   var hrefPais = $(this).find('a').attr('href');
		   window.location.href = hrefPais;
	   });
	   $('.selectPais li').mouseover(function(){
		  $(this).find('a').css('color','#fff');
	   });
	   $('.selectPais li').mouseout(function(){
		  $(this).find('a').css('color','#000');
	   });
    
});

function verDropDown(id,boton) {
    if ($(boton).hasClass('AjaxRunnig')) {
        return false;
    } else {
        var notificacionesNoLeidas = $('#dropdown-'+id+' .noLeida');
        var n = notificacionesNoLeidas.size();
        if (n) {
            $(boton).addClass('AjaxRunnig');
            $(boton).removeClass('danger');
            var numeroNotif = $(boton).find('.contador');
            var resta = parseInt($(numeroNotif).html())-n;
            if (resta) $(numeroNotif).html(resta); 
            else $(numeroNotif).html("");
            var params = '';
            $("#dropdown-"+id+" .noLeida input[name=idNotificacion]").each(function(){
                params += $(this).attr("name")+"="+$(this).attr("value")+"&";
            });
            marcarNotificacionesLeidas(params,numeroNotif,notificacionesNoLeidas,boton);
        }
    }
}
    
function marcarNotificacionesLeidas(params,numeroNotif,notificacionesNoLeidas,boton,todas) {
    $.ajax({
        type: "POST",
        url: "/postulantes/notificaciones_marcarLeidas.ajax",
        data: params ,
        success: function(data){
            var result = false;
            var msgError = "Sucedio algun inconveniente";
            if ( typeof data.status != "undefined" ){
                var status = data.status.status;
                switch ( status ){
                    case 3:
                        $(numeroNotif).html(notificacionesNoLeidas.size());
                        result = true;
                        break;
                    case 200:
                        setTimeout(function(){
                            notificacionesNoLeidas.removeClass('noLeida');  
                            notificacionesNoLeidas.addClass('marcar leido');
                            if($.support.transition){
                                notificacionesNoLeidas.bind(transitionEnd, function(){
                                    $(this).removeClass('panel_list_item_nuevo');
                                });
                            }
                        },1000);
                        result = true;
                        break;
                }
            }
            if (!result) bumexAlert(msgError);
            else $(boton).removeClass('AjaxRunnig');
        }
    });
}


function insertarNotificacion(notificacion, templateRow) {
    if (notificacion.leida){
        $(templateRow).removeClass("panel_list_item_nuevo");
        $(templateRow).addClass("marcar leido");
    } else {
        $(templateRow).addClass("noLeida");
    }
    var anchor = $(templateRow).find("a.panel_block_link");
    $(anchor[0]).attr('href',notificacion.linkPerfilEmisor);
    $(anchor[0]).find("img").attr('src',notificacion.fotoUrlEmisor);
    $(anchor[1]).attr('href',notificacion.linkObjeto);
    $(anchor[1]).find(".notificacion_cuerpo").html(notificacion.nombreEmisor+notificacion.textoNotificacion+" "+notificacion.textoLink);
    $(anchor[1]).find(".hace_cuanto").html(notificacion.fechaTwitter);
    var tableData = $(templateRow).find("td.panel_list_td_content");
    for (var i in notificacion.idsNotificaciones) {
        $(tableData).append('<input type="hidden" name="idNotificacion" value="'+notificacion.idsNotificaciones[i]+'">');
    }
}

function traerNotificaciones() {
    //ME FIJO QUE NO TENGA ABIERTO EL DROPDOWN SINO SE LE VA A ACTUALIZAR Y EL USUARIO SE PUEDE CONFUNDIR
    var dropNotiTolki = $('div#dropdown-notificaciones');
    var dropNotiPost = $('div#dropdown-mis-postulaciones');
    if(!$(dropNotiTolki).parents('div.dropdown.pull_right').hasClass('abierto') &&
        !$(dropNotiPost).parents('div.dropdown.pull_right').hasClass('abierto')) {
        var ultimoUpdateTolki = $(dropNotiTolki).find('.panel_title_wrap input[name=ultimoUpdateNotificaciones]');
        var ultimoUpdatePostulaciones = $(dropNotiPost).find('.panel_title_wrap input[name=ultimoUpdateNotificaciones]');
        var params = $(ultimoUpdateTolki).attr('name')+"="+$(ultimoUpdateTolki).attr('value');
        $.ajax({
            type: "POST",
            url: "/postulantes/notificaciones_traerNotificaciones.ajax",
            data: params,
            success: function(data){
                if ( typeof data.status != "undefined" ){
                    var status = data.status.status;
                    switch ( status ){
                        case 200:
                            $(ultimoUpdateTolki).attr('value',data.contenido.ultimoUpdate);
                            $(ultimoUpdatePostulaciones).attr('value',data.contenido.ultimoUpdate);
                            updateDropDown("notificaciones",data);
                            updateDropDown("mis-postulaciones",data);
                            break;
                        default:
                            break;
                    }
                    setTimeout("traerNotificaciones()", 25000 );
                }
			    	
            }
        });
    } else setTimeout("traerNotificaciones()", 500 );
}


function updateDropDown(id,data) {
    var noLeidas = $("a#btn_"+id);
    var cantNoLeidas = (id=="notificaciones"?data.contenido.noLeidasTolki:data.contenido.noLeidasPostulaciones);
    if(cantNoLeidas > 0){
        $(noLeidas).addClass("danger");
        $(noLeidas).find(".contador").html(cantNoLeidas);
    } else {
        if ($(noLeidas).hasClass("danger")) {
            $(noLeidas).removeClass("danger");
            $(noLeidas).find(".contador").html('');
        }
    }
    var notificacionesContainer = $("div#dropdown-"+id);
    var tablaNotificaciones = $(notificacionesContainer).find("table.panel_list tbody");
    $(tablaNotificaciones).html('');
    var templateRow;
    var notificaciones = (id=="notificaciones"?data.contenido.notificacionesTolki:data.contenido.notificacionesPostulaciones);
    for (var i in notificaciones) {
        templateRow = $(notificacionesContainer).find("table.templateNotificacion .panel_list_item_nuevo").clone();
        insertarNotificacion(notificaciones[i],templateRow);
        $(tablaNotificaciones).append(templateRow);
    }
}
