var deliciousobj = null;
var acordeon = null;
var cartel = null;
var cartelflag = true;
var comenvio = null
var comcarga = null;
var ayax = null;


var autocompletion = {
    snippets: {
        "strong" :  ["<strong>",        "", "</strong>"],
        "b" :       ["<b>",             "", "</b>"],
        "em" :      ["<em>",            "", "</em>"],
        "u" :       ["<u>",             "", "</u>"],
        "cite" :    ["<cite>",          "", "</cite>"],
        "code" :    ["<code>",          "", "</code>"],
        "a" : {
            snippet:['<a href="', 'http://">texto', '</a> '],
            tab:['http://', 'texto', '']
        },
        "bq" :      ["<blockquote>",    "", "</blockquote>"],
        "pre" :     ["<pre>",           "", "</pre>"],
        "@" :      {
            snippet: ["", "#", ""],
            tab: ['#'],
            completion: {
                '#': []
            },
            loop: true
        }
    },

    smartTypingPairs: {
        '"' : '"',
        '(' : ')',
        '{' : '}',
        '[' : ']',
        "<" : ">",
        "`" : "`",
        "'" : {
            scope:{
                "<code>" :  "</code>",
                "<pre>" :   "</pre>"
            },
            pair:"'"
        }
    }
};

//window.onload = function() {
Window.onDomReady(function() {
    if ($E('#delicious')) {
        deliciousobj = new Fx.Opacity('uwdiu', {duration: 500}).toggle().chain(function() {
            new ajax('/delicious.php?c=16', {method: 'get', onComplete: delicious}).request()
        });
    }
    
    if ($E('#comform')) {
        //$E('#comload').innerHTML = '';
        comenvio = new Fx.Opacity('divenviocom', {duration: 200});
        comcarga = new Fx.Opacity('comload', {duration: 200}).hide();
        acordeon = new Fx.Accordion($S('.comtitle'), $S('.comarea'), {firstBlock: 2, opacity: false});
        // hacer como gmail, que si no se ve el formulario le salga un label
    }
    
    if ($E('#contextarea')) {
        for (var key in comentaristas) {
            if (!autocompletion.snippets['@'].completion['#'].test(comentaristas[key]))
                autocompletion.snippets['@'].completion['#'].push(comentaristas[key]);
            autocompletion.snippets['#'+key] = [comentaristas[key] + ' ', "", ""];
//            autocompletion.snippets['#'+key] = ['<strong>'+comentaristas[key] + '</strong> ', "", ""];
//            autocompletion.snippets[key] = [comentaristas[key] + ' ', "", ""];
        }

        //new postEditor('contextarea', snippets, smartTypingPairs);
        new postEditor.create('contextarea', 'nombre', autocompletion);
    }
    
    if ($E('#comcartelito')) {
        window.onresize = window.onscroll = function() {
            var tmpflag = cartelflag;

            if (Window.getHeight() + Window.getScrollTop() > $('contextarea').getTop())
                tmpflag = false;
            else
                tmpflag = true;

            if (tmpflag != cartelflag) {
                cartel.toggle();
                cartelflag = !cartelflag;
            }
        }

        cartel = new Fx.Opacity('comcartelito', {duration: 100});
    }
/*
    if ($E('#comform')) {
        window.onresize = window.onscroll = function() {
            if (Window.getScrollTop() > $('comform').getTop()) {
                if (!$('comformin').hasClass('formfijo'))
                    $('comformin').addClass('formfijo');

            } else {
                if ($('comformin').hasClass('formfijo'))
                    $('comformin').removeClass('formfijo');
            }
        }
    }
*/
    if ($E('#editorcom')) {
        $E('#editorcom').onsubmit = function() {
            if ($('contextarea').value == "")
                return false;
                
            comenvio.toggle();
            comcarga.toggle();
            //ayax = new Ajax("http://xergio.net/test.php", {postBody: $('editorcom'), onComplete: comentarioEnviado});
            ayax = new Ajax(location.href, {postBody: $('editorcom'), onComplete: comentarioEnviado});
            ayax.request();
            
            return false;
        };
    }
    
    
    if ($E('#resuvota')) {
        $E('.votosi').onclick = function() {
            new Ajax("http://"+location.host+"/voto-" + $E('#resuvota').className + "-10.html", {method: 'get', update: $('resuvota')}).request();
            return false;
        }
        $E('.votono').onclick = function() {
            new Ajax("http://"+location.host+"/voto-" + $E('#resuvota').className + "-1.html", {method: 'get', update: $('resuvota')}).request();
            return false;
        }
    }
});


function comentarioEnviado(req) {
    comcarga.toggle();
    comenvio.toggle();
    
    myImage = new Image()
    myImage.src = "http://xergio.net/pin.php?"+Math.random();
    myImage.onload = function() { $('imgpin').src = myImage.src; };
    
    if (req == '0') {
        alert("Revisa los datos (como el PIN). No se ha añadido el comentario.");
        return;
    }

    var d = new Date();
    var fecha = d.getUTCDate()+'-'+d.getMonth()+'/'+d.getHours()+':'+d.getMinutes();
    
    var tmpdiv = new Element('div').addClass('comentario');
    var tmph4 = new Element('h4').injectInside(tmpdiv);
    var tmpsta = new Element('span').addClass('comstatus').injectInside(tmph4);
    var tmpstai = new Element('img').setProperties({alt: "Jabber Status", src: 'http://jabberland.com/status/'+hex_md5($('email').value)+'-info=2-pack=11'}).injectInside(tmpsta);
    if ($('web').value != "") {
        tmph4.appendText(' ');
        var tmph4a = new Element('a').setProperties({href: $('web').value}).appendText($('nombre').value).injectInside(tmph4);
        tmph4.appendText(' comentó:');
    } else {
        tmph4.appendText($('nombre').value+' comentó:').injectInside(tmpdiv);
    }
    var tmpavd = new Element('div').addClass('comavatar').injectInside(tmpdiv);
    var tmpavi = new Element('img').setProperties({alt: "[Avatar]", src: 'http://jabberland.com/status/'+hex_md5($('email').value)+'-info=1-w=30-h=30'}).injectInside(tmpavd);
    var tmpinfo = new Element('div').addClass('cominfo').injectInside(tmpdiv);
    var tmpul = new Element('ul').injectInside(tmpinfo);
    var tmpli1 = new Element('li').injectInside(tmpul);
    var tmpaid = new Element('a').setProperties({name: req, href: location.href+'#last'}).appendText('#'+$S('.comentario').length).injectInside(tmpli1);
    var tmpli2 = new Element('li').appendText(fecha).injectInside(tmpul);
    var tmptxt = new Element('div').addClass('comtexto').appendText($('contextarea').value).injectInside(tmpdiv);
    var tmpclear = new Element('div').addClass('clear').injectInside(tmpdiv);
    
    window.scrollTo(0, 9999);
    var tmpefe = new Fx.Height(tmpdiv, {duration: 500});
    tmpefe.hide();
    tmpdiv.injectInside($('comentarios'));
    tmpefe.toggle();
    $('editorcom').reset();
}

function delicious(req) {
    var data = eval(req);
    
    $E('#uwdiu').removeClass('scrolldiu').addClass('scrolldiu-ok').innerHTML = '';
    var elul = new Element('ul');
    data.each(function(item) {
        //$E('#uwdiu').innerHTML = $E('#uwdiu').innerHTML + item.d.substr(0, 25) + '<br />';
        var elli = new Element('li');
        elli.addClass('fg');
        var ela = new Element('a');
        ela.setProperty('href', item.u).appendText(item.d.substr(0, 25) + ((item.d.length>25)? '...': ''));
        elli.appendChild(ela);
        elul.appendChild(elli);
    });
    $E('#uwdiu').appendChild(elul);

    deliciousobj.toggle();
}


function envioFotosctl() {
	if (nombre = prompt("Nombre?", "")) {
		if (desc = prompt("Descripción?", "")) {
			if (confirm("Son correctos los siguientes datos?\nNombre: " + nombre + "\nDescripción: " + desc, "")) {
				var fotosctl = document.getElementById("fotosctl");
				fotosctl.nombre.value = nombre;
				fotosctl.desc.value = desc;
				return true;
			}
		}
	}
	return false;
}
