var COMENTARIOS = {};
COMENTARIOS.getComentarios = function (h, j, k) {
    if (typeof h == 'undefined') {
        return
    }
    $.get(BARRIOSYVECINOS.carpetadominio + '/backend/COMENTARIOS.getComentarios.php', {
        id: h,
        by: j,
        r: Math.random()
    }, function (c) {
        var i = 0;
        var d = '';
        var e = Array();
        var f = new Date();
        var g = $(c).find('comment').length;
        $(c).find('comment').each(function () {
            var a = $(this);
            var b = a.find('date').text().split(' ');
            e[i] = {
                fecha: b[2] + '/' + b[1] + '/' + b[5],
                hora: b[3],
                author: a.find('author').find('name').text(),
                content: a.find('content').text(),
                id: a.find('id').text(),
                positive_votes: a.find('positive_votes').text(),
                negative_votes: a.find('negative_votes').text(),
                load_time: f.getTime()
            };
            i++
        });
        $.ajax({
            type: 'GET',
            url: '/plantillas/comentarios.html',
            async: false,
            success: function (a) {
                d = a
            }
        });
        COMENTARIOS.muestraComentarios(e, d, k, g);
        if (j == 'date') {
            $('#lomasreciente').addClass('activo');
            $('#lomasvalorado').removeClass('activo')
        } else {
            $('#lomasvalorado').addClass('activo');
            $('#lomasreciente').removeClass('activo')
        }
    })
};
COMENTARIOS.muestraComentarios = function (a, b, c, d) {
    var e = 5;
    var f = ((((c - 1) * e) + e) > d) ? d : (((c - 1) * e) + e);
    var g = (c - 1) * e;
    var h = Math.ceil(d / e);
    var j = $('<div></div>');
    for (i = g; i < f; i++) {
        var t = $.template(b);
        if (i == g) {
            j.html(t, {
                fecha: a[i].fecha,
                hora: a[i].hora,
                author: a[i].author,
                content: a[i].content,
                id: a[i].id,
                positive_votes: a[i].positive_votes,
                negative_votes: a[i].negative_votes,
                load_time: a[i].load_time
            })
        } else {
            j.append(t, {
                fecha: a[i].fecha,
                hora: a[i].hora,
                author: a[i].author,
                content: a[i].content,
                id: a[i].id,
                positive_votes: a[i].positive_votes,
                negative_votes: a[i].negative_votes,
                load_time: a[i].load_time
            })
        }
        if ($.cookie('admin') == 1) {
            j.find('#moderacion-' + a[i].id).show()
        }
    }
    window.document.getElementById('bloque-opiniones').innerHTML = j.html();
    var k = $('.num_opiniones').text().split(' ');
    if ($('.num_opiniones').text().indexOf(' ') != -1) {
        $('.num_opiniones').text(d + ' ' + k[1])
    } else {
        $('.num_opiniones').text(d + ' ' + $('.num_opiniones').text())
    }
    var l = $('.listado_seguimiento');
    l.find('strong').text((c < 10) ? '0' + c : c);
    l.html(l.find('strong'));
    l.append('/' + ((h < 10) ? '0' + h : h));
    var m = $('#anterior');
    var n = $('#siguiente');
    m.attr('href', 'javascript:void(0)');
    n.attr('href', 'javascript:void(0)');
    if (c > 1) {
        m.unbind('click');
        m.bind('click', function () {
            COMENTARIOS.muestraComentarios(a, b, (c - 1), d)
        })
    }
    if (c != h) {
        n.unbind('click');
        n.bind('click', function () {
            COMENTARIOS.muestraComentarios(a, b, (c + 1), d)
        })
    }
};
COMENTARIOS.mostrarDenunciar = function (a) {
    $('#formdenunciar-' + a).slideDown("slow")
};
COMENTARIOS.votarComentario = function (b, c) {
    $.post(BARRIOSYVECINOS.carpetadominio + '/backend/COMENTARIOS.votarComentario.php', {
        id: b,
        tipo: c
    }, function (a) {
        if (a == 'ok') {
            $('#favorcontra-' + b).parent().html('Gracias por votar')
        } else {
            alert(a)
        }
    })
};
COMENTARIOS.denunciarComentario = function (a) {
    var b = new Date();
    var c = /^[A-Za-z][A-Za-z0-9_.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
    eval("var formu = document.getElementById('formdenunciar-" + a + "')");
    if (formu.nombre.value == '') {
        alert('Por favor, introduzca su nombre');
        formu.nombre.focus();
        return
    }
    if (formu.email.value == '') {
        alert('Por favor, introduzca su email');
        formu.email.focus();
        return
    }
    if (!c.test(formu.email.value)) {
        alert('El email introducido no es válido');
        formu.email.value.focus();
        return
    }
    if (formu.denuncia.value == '') {
        alert('Por favor, introduzca su denuncia');
        formu.denuncia.focus();
        return
    }
    formu.submit_time.value = b.getTime();
    formu.submit();
    alert('Gracias por denunciar el comentario')
};
COMENTARIOS.enviarComentario = function () {
	 	if(BARRIOSYVECINOS.carpetadominio != '')
	 		window.document.formulario.action = window.document.formulario.action.replace('/backend',BARRIOSYVECINOS.carpetadominio + '/backend');
	 	
    var a = new Date();
    if (typeof REGISTRO == 'undefined') {
        $.getScript('/js_comun/registro.js', function () {
            REGISTRO.getXML($.cookie('registro'));
            if (typeof REGISTRO.xml == 'undefined') {
                alert('Tienes que estar registrado para poder comentar.');
                return
            }
            window.document.formulario.author_name.value = $(REGISTRO.xml).find('user').text();
            window.document.formulario.author_email.value = $(REGISTRO.xml).find('user_email').text();
            if (window.document.formulario.message.value == '') {
                alert('Por favor, introduce tu opinión');
                window.document.formulario.message.focus();
                return
            }
            if (!window.document.formulario.acepto.checked) {
                alert('Tienes que aceptar las condiciones legales');
                return
            }
            window.document.formulario.message.value = window.document.formulario.message.value;
            window.document.formulario.submit_time.value = a.getTime();
           
            
            window.document.formulario.submit()
        })
    } else {
        if (typeof REGISTRO.xml == 'undefined') {
            alert('Tienes que estar registrado para poder comentar.');
            return
        }
        window.document.formulario.author_name.value = $(REGISTRO.xml).find('user_nombre').text();
        window.document.formulario.author_email.value = $(REGISTRO.xml).find('user_email').text();
        if (window.document.formulario.message.value == '') {
            alert('Por favor, introduce tu opinión');
            window.document.formulario.message.focus();
            return
        }
        window.document.formulario.message.value = window.document.formulario.message.value;
        window.document.formulario.submit_time.value = a.getTime();
       
        window.document.formulario.submit()
    }
};
COMENTARIOS.setNumComentariosPortada = function () {
    var g = '';
    $('.num_comentarios').each(function () {
        var a = $(this).attr('id').split('-');
        if (typeof a[2] != 'undefined') {
            g = g ? g + '|' + a[2] : a[2]
        }
    });
    $('.num-comentarios').each(function () {
        var a = $(this).attr('id').split('-');
        if (typeof a[2] != 'undefined') {
            g = g ? g + '|' + a[2] : a[2]
        }
    });
    if (g != '') {
        $.get(BARRIOSYVECINOS.carpetadominio + "/backend/COMENTARIOS.getComentariosPortada.php", {
            id: g,
            by: 'date'
        }, function (a) {
            var b = a.split('|');
            var c = b.length;
            var i = c - 1;
            do {
                var d = b[i].split('@');
                var e = d[1];
                var f = '';
                switch (true) {
                case (e == 0 || e == ''):
                    f = document.getElementById('num-comentarios-' + d[0]).innerHTML;
                    break;
                case (e == 1):
                    f = '1 Comentario';
                    break;
                default:
                    f = e + '  Comentarios';
                    break
                }
                if (document.getElementById('num-comentarios-' + d[0])) {
                    document.getElementById('num-comentarios-' + d[0]).innerHTML = f
                }
            } while (i--)
        })
    }
};
COMENTARIOS.desaprobar = function (d) {
    if (confirm('Quiere desaprobar este comenario?')) {
        $.post(BARRIOSYVECINOS.carpetadominio + '/backend/COMENTARIOS.desaprobar.php', {
            id: d
        }, function (a) {
            var b = $(a).find('estado').text();
            if (b == 'OK') {
                $('#opinion-' + d).remove();
                var c = $('.num_opiniones').text().split(' ');
                $('.num_opiniones').text((parseInt(c[0]) - 1) + ' ' + c[1])
            } else {
                alert($(a).find('desc').text())
            }
        })
    }
};
COMENTARIOS.eliminar = function (d) {
    if (confirm('Quiere eliminar este comenario?')) {
        $.post(BARRIOSYVECINOS.carpetadominio + '/backend/COMENTARIOS.eliminar.php', {
            id: d
        }, function (a) {
            var b = $(a).find('estado').text();
            if (b == 'OK') {
                $('#opinion-' + d).remove();
                var c = $('.num_opiniones').text().split(' ');
                $('.num_opiniones').text((parseInt(c[0]) - 1) + ' ' + c[1])
            } else {
                alert($(a).find('desc').text())
            }
        })
    }
};
COMENTARIOS.str_replace = function (a, b, c) {
    var f = a,
        r = b,
        s = c;
    var d = r instanceof Array,
        sa = s instanceof Array,
        f = [].concat(f),
        r = [].concat(r),
        i = (s = [].concat(s)).length;
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i] + '').split(f[j]).join(d ? r[j] || "" : r[0]), ++j in f) {}
        }
    };
    return sa ? s : s[0]
};
$(document).ready(function () {
    if ($('[name=id_item]').length) {
        COMENTARIOS.getComentarios($('[name=id_item]').val(), 'date', 1)
    }
    COMENTARIOS.setNumComentariosPortada()
});
