//Variables globales
var punteroX, punteroY;
var top10WebCounter= 0;
var top10ForoCounter= 0;
//Definimos el dominio
var domain='';
if(document.location.href.indexOf('/localhost/')==-1)
    domain='http://www.2pacsubs.com/';
else
    domain='http://localhost/3pacsubs/';
    
//Evitamos que el login quede superpuesto
if(window.top.location.href.include(domain+'login.aspx')&&!document.location.href.include(domain+'login_box.aspx'))
    window.top.location.href= document.location.href;
            
//Eventos
Event.observe(document, 'mousemove', function(event){
    punteroX=Event.pointerX(event);
    punteroY=Event.pointerY(event);
});
Event.observe(window, 'load', function(){
    try{
        //Bola de version
        new Draggable($('bolaVersion'), {revert:true});
        
        //Deshabilitamos el login en el foro
        /*if(document.location.href.indexOf('/foro')!=-1) {
            if($('username')!=null&&$('password')!=null&&$('autologin')!=null&$('viewonline')!=null) {
                $(document.documentElement).setStyle({
                    visibility: 'hidden'
                });
                var redir='../login.aspx?redir=';
                if(document.location.href.indexOf('/foro/ucp.php?mode=login')!=-1) {
                    if(document.location.href.indexOf('&blockredir=true')==-1) {
                        redir+=encodeURIComponent(document.location.href.substring(document.location.href.indexOf('/foro/')+6).replace('ucp.php?mode=login','index.php'));
                    }
                }else {
                    redir+=encodeURIComponent(document.location.href.substring(document.location.href.indexOf('/foro/')+6));
                }
                document.location.href=redir;
            }
        }*/
        
        //Establecemos las caracteristicas de los post
        if(document.location.href.toLowerCase()==domain||document.location.href.toLowerCase().indexOf(domain+'default.aspx')!=-1||document.location.href.indexOf('/noticias/')!=-1) {
            setPostProps();
        }
        
        //Minimizamos la firma, en el caso de que sea muy grande
        if(document.location.href.toLowerCase().include('/foro/viewtopic.php'))
            resizeSignatures();
    }catch(e){
        /*alert(e.message)*/
    };
});
Event.observe(document,'keypress', function(event) {
    if(document.location.href.indexOf('login_box.aspx')!=-1) {
        changeForumLoginSrc();
    }
});
		
//Funciones
getVideoHtml= function(url) {
    /* Preparando sistema */
    url= url.strip();
    var magicId= url.gsub(/http|:|\/|\.|&|=|%|_|\?|;/,'x');
    document.write('<input id="'+magicId+'" type="hidden" value="" />');
    /* Video templates */
    var youtube=     '<embed src="http://www.youtube.com/v/#{hash}&amp;rel=1&amp;fs=1" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" style="width:425px;height:355px;" pluginspage="http://get.adobe.com/es/flashplayer/"></embed>';
    var dailymotion= '<embed src="http://www.dailymotion.com/swf/#{hash}" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" style="width:425px;height:355px;" pluginspage="http://get.adobe.com/es/flashplayer/"></embed>';
    var google=      '<embed src="http://video.google.com/googleplayer.swf?docId=#{hash}&amp;hl=es" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" style="width:425px;height:355px;" pluginspage="http://get.adobe.com/es/flashplayer/"></embed>';
    var metacafe=    '<embed src="http://www.metacafe.com/fplayer/#{hash}.swf" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" style="width:425px;height:355px;" pluginspage="http://get.adobe.com/es/flashplayer/"></embed>';
    var stage6=      '<embed src="http://video.stage6.com/#{hash}/.divx" type="video/divx" height="355" width="425" pluginspage="http://go.divx.com/plugin/download/" showpostplaybackad="false" custommode="Stage6" autoplay="false"></embed>';
    var vimeo=       '<embed src="http://vimeo.com/moogaloop.swf?clip_id=#{hash}&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=ffffff&amp;fullscreen=1" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" style="width:425px;height:355px;" pluginspage="http://get.adobe.com/es/flashplayer/"></embed>';
    var veintemin=   '<embed src="http://www.20minutos.tv/videoplayer/#{hash}/" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" style="width:425px;height:355px;" pluginspage="http://get.adobe.com/es/flashplayer/"></embed>';
    /* The variables */
    var hash2Use= '';
    var template2Use= '';
    var cleanedUrl= '';
    /* Video matches */
    if(url.match(/(www|de|au|br|ca|fr|es|hk|ie|it|mx|nz|pl|ru|tw\.)?youtube\.com/)) {
        template2Use= youtube;
		if(url.include('watch?v='))
			hash2Use= url.substring(url.indexOf('watch?v=')+'watch?v='.length);
		else
			hash2Use= url.gsub(/&amp;/,'&').substring(url.gsub(/&amp;/,'&').indexOf('&v=')+'&v='.length);			
        if(hash2Use.include('&'))
            hash2Use= hash2Use.split('&')[0];
        cleanedUrl= 'http://www.youtube.com/watch?v='+hash2Use;
    }else if(url.match(/(www\.)?dailymotion\.com/)) {
        template2Use= dailymotion;
		url= url.replace('/swf/','/video/');
        hash2Use= url.substring(url.indexOf('video/')+'video/'.length);
        if(hash2Use.include('_'))
            hash2Use= hash2Use.split('_')[0];
        cleanedUrl= 'http://www.dailymotion.com/video/'+hash2Use;
    }else if(url.match(/(www\.)?video\.google\.(com|es)/)) {
        template2Use= google;
        hash2Use= url.substring(url.indexOf('videoplay?docid=')+'videoplay?docid='.length);
        if(hash2Use.include('&'))
            hash2Use= hash2Use.split('&')[0];
        cleanedUrl= 'http://video.google.com/videoplay?docid='+hash2Use;
    }else if(url.match(/www\.metacafe\.com/)) {
        template2Use= metacafe;
        hash2Use= url.substring(url.indexOf('watch/')+'watch/'.length);
        if(hash2Use.include('/'))
            hash2Use= hash2Use.split('/')[0]+'/'+hash2Use.split('/')[1];
        cleanedUrl= 'http://www.metacafe.com/watch/'+hash2Use+'/';
    }else if(url.match(/www\.stage6\.com/)) {
        template2Use= stage6;
        hash2Use= url.substring(url.indexOf('video/')+'video/'.length);
        if(hash2Use.include('/'))
            hash2Use= hash2Use.split('/')[0];
        cleanedUrl= 'http://www.stage6.com/video/'+hash2Use;
    }else if(url.match(/(www\.)?vimeo\.com/)) {
        template2Use= vimeo;
        hash2Use= url.substring(url.indexOf('.com/')+'.com/'.length);
        if(hash2Use.include('/'))
            hash2Use= hash2Use.split('/')[0];
        if(hash2Use.include('&'))
            hash2Use= hash2Use.split('&')[0];
        cleanedUrl= 'http://www.vimeo.com/'+hash2Use;
    }else if(url.match(/20minutos\.tv/)) {
        template2Use= veintemin;
        hash2Use= url.substring(url.indexOf('.tv/video/')+'.tv/video/'.length);
        if(hash2Use.include('-'))
            hash2Use= hash2Use.split('-')[0];
        cleanedUrl= 'http://www.20minutos.tv/video/'+hash2Use;
    }
    /* Preparamos la tpl */
    var template= new Template(template2Use);
    var json4Tpl= {hash: hash2Use};
    /* Escribimos el Html */
    document.write(template.evaluate(json4Tpl));
    /* Preparamos la gallery */
    var thePost= $(magicId).up('div.postbody');
    var userId= thePost.select('p.author a')[1].readAttribute('href');
    userId= userId.substring(userId.indexOf('u=')+'u='.length);
    if(userId.include('&'))
        userId= userId.split('&')[0];
    var postTitle= thePost.select('h3 a').first().innerHTML;
    if(postTitle.strip()=='')
        postTitle= $$('h3.first a').first().innerHTML;
    var postContent= thePost.select('div.content').first().innerHTML.stripScripts().stripTags();
    var postDate= thePost.select('p.author').first().innerHTML;
    postDate= postDate.substring(postDate.lastIndexOf('</strong>')+'</strong>'.length).gsub(/^\sel\s/,'');
        
    new Ajax.Request(domain+'trigger.aspx', {
      method: 'post',
      parameters: {
        mode: 'postVideo',
        videoUrl: cleanedUrl,
        postUserId: userId,
        videoTitle: postTitle,
        videoDesc: postContent,
        videoDate: postDate,
        sourceUrl: document.location.href
      }
    });
}

saveComment= function(json) {
    new Ajax.Request(domain+'view.aspx', {
      method: 'post',
      parameters: {
        mode: 'write_comment',
        texto: json.textarea.value,
        id_entidad: json.id_entidad,
        tipo: json.tipo
      },
      onLoading: function(transport) {
        alert(transport.responseText);
      
      },
      onFailure: function(transport) {
        alert(transport.responseText);
        
      },
      onSuccess: function(transport) {
        alert(transport.responseText);
      }
    });
}

/*
 * ACCIONES DE LOGIN
 */
loginActions= function() {
    try {
        var winforo=win.frames[1].document;
        winforo.getElementById('username').value=$F('username');
        winforo.getElementById('password').value=$F('password');
        winforo.getElementById('redirect').value=$F('redir');
        winforo.getElementById('login').click();
    }catch(ex){ /*alert(ex.message);*/ }
}

changeForumLoginSrc= function() {
    try {
        if(document.location.href.indexOf('login_box.aspx')!=-1) {
            var lboxpath=$$('script').first().src;
            lboxpath=lboxpath.substring(0,lboxpath.indexOf('/theme/')+1);
            lboxpath+='template/login_box.html';
            var winforo=win.frames[1].document;
            if(winforo.location.href!=lboxpath&&$('tblLogin')!=null) {
                winforo.location.href=lboxpath;
            }
        }
    }catch(ex){ /*alert(ex.message);*/ }
}
/*
 * FIN ACCIONES DE LOGIN
 */

escribirAvatar= function(username, from, jplus) {
    var tplNoLogged=new Template('<em>&iexcl;Bien-<br />venido!</em>'+
                    '<img src="../themes/2008/imageset/usuario.jpg" alt="Usuario" />'+
                    '<ul>'+
                        '<li><a href="ucp.php?mode=login" class="greybox">Login</a></li>'+
                        '<li><a href="#{url_reg}">Reg&iacute;strate</a></li>'+
                    '</ul>');
					//../login.aspx?redir=foro/index.php
    var tplLogged=new Template('<em>&iexcl;Hola<br /><strong style="color:Red;">#{usuario}</strong>!</em>'+
                  '<img src="#{img_url}" alt="#{usuario}" style="#{img_propcss}:48px;" />'+
                  '<ul>'+
                      '<li><a href="http://spreadsheets.google.com/pub?key=pHbhG9CqXmlb9BsUd5s8RDQ" target="_blank" style="color:red;">Novedades</a></li>'+
                      '<li><a href="#{url_logout}">Salir</a></li>'+
                  '</ul>');
    var logged=(!jplus)?null:(jplus.logged=='1')?true:false;
    var regurl=(!jplus)?'':jplus.regurl;
	var logouturl=(!jplus)?'':jplus.logout;
    if(logged!=false) {
        new Ajax.Request(domain+'trigger.aspx', {
            method: 'post',
            parameters: {
                json:'{mode:get_user_avatar,username:'+username+',from:'+from+'}'
            },
            onFailure: function(transport) {
                if(from=='foro') {
                    $('banner-login').update(tplNoLogged.evaluate({url_reg:regurl}));
                }else {
                    $('loggedAvatar').update('<img src="themes/2008/imageset/usuario.jpg" alt="Usuario" />');
                }
            },
            onSuccess: function(transport) {
                if(transport.responseText=='') {
                    if(from=='foro') {
                        $('banner-login').update(tplNoLogged.evaluate({url_reg:regurl}));
                    }else {
                        $('loggedAvatar').update('<img src="themes/2008/imageset/usuario.jpg" alt="Usuario" />');
                    }
                }else {
                    var img=new Image();
                    img.src=transport.responseText;
                    var propcss;
                    (img.height>img.width)?propcss='height':propcss='width';
                    if(from=='foro') {
                        $('banner-login').update(tplLogged.evaluate({usuario:username,img_url:transport.responseText,img_propcss:propcss,url_logout:logouturl}));
                    }else {
                        var imgMarkup='<img src="'+transport.responseText+'" alt="'+username+'" style="'+propcss+':48px;" />';
                        $('loggedAvatar').update(imgMarkup);
                    }
                }
            }
        });
    }else {
        $('banner-login').update(tplNoLogged.evaluate({url_reg:regurl}));
    }
}

setPostProps= function() {
    var _IN='';
    $$('input[title="forjs"]').each(function(i) {
        !_IN?_IN+=i.value:_IN+=';'+i.value;
    });
    new Ajax.Request(domain+'trigger.aspx', {
        method: 'post',
        parameters: {
            json:'{mode:get_entry_data,sqlin:"'+_IN+'"}'
        },
        onSuccess: function(transport) {
            var a=new Array();
            a=transport.responseText.evalJSON().arr;
            a.each(function(item) {
                $('post'+item.id+'CommentsNum').update(item.numComments);
                $('post'+item.id+'ListCat').update(item.strCategorias);
                $('post'+item.id+'ListTag').update(item.strTags);
                if(item.notaMedia!='0') {
                    $('post'+item.id+'Votes').update('<strong>'+item.notaMedia+'</strong><br />votos')
                    $('post'+item.id+'Votes').setStyle({
                        display: 'block'
                    });
                }
            });
        }
    });
}

doAccordionToggle= function(me) {
    $$('.accordion_toggle').each(function(el) {
        el.removeClassName('accordion_toggle_active');
    });
    if(!me.hasClassName('accordion_toggle_active')) {
        me.toggleClassName('accordion_toggle_active');
    }
}

/* GLIDDERS */
doMoveGlider= function(ev,gl,sname) {
    var el= Event.element(ev);
    if(!(el.hasClassName('left_disabled')||el.hasClassName('right_disabled'))) {
        var webTitlesArr= ['Lo M&aacute;s Votado','Lo M&aacute;s Comentado','Usuarios M&aacute;s Activos'];
        var forumTitlesArr= ['Lo M&aacute;s Le&iacute;do','Lo M&aacute;s Comentado','Usuarios M&aacute;s Activos'];
        var arrTitles= new Array();
        var currIx= 0;
        if(sname=='web') {
            arrTitles= webTitlesArr;
            currIx= top10WebCounter;
        }else if(sname=='foro') {
            arrTitles= forumTitlesArr;
            currIx= top10ForoCounter;
        }
        if(el.hasClassName('left')) {
            if(currIx==1)
                el.addClassName('left_disabled');
            if(currIx<=arrTitles.length)
                el.next('a').removeClassName('right_disabled');
                
            gl.previous();
            (sname=='web')?(top10WebCounter--):(top10ForoCounter--);
        }else if(el.hasClassName('right')) {
            if(currIx==1)
                el.addClassName('right_disabled');
            if(currIx>=0)
                el.previous('a').removeClassName('left_disabled');
            
            gl.next();
            (sname=='web')?(top10WebCounter++):(top10ForoCounter++);
        }
        (sname=='web')?(currIx= top10WebCounter):(currIx= top10ForoCounter);
        $('top10'+sname.capitalize()+'Title').update(arrTitles[currIx]);
        return false;
    }else {
        return false;
    }
}

/* POST CRASH */
postCrash= function() {
    new Ajax.Request(domain+'trigger.aspx', {
      method: 'post',
      parameters: {
        mode: 'postCrash',
        url: document.location.href
      }
    });
}

/* POST MOROSO */
doAddMoroso= function(did,uid) {
    if(confirm('\u00BFEst\u00E1s seguro de querer formar parte de nuestra lista de morosos?')) {
        new Ajax.Request(domain+'trigger.aspx', {
            method: 'post',
            parameters: {
                mode:'postMoroso',
                id_descarga: did,
                id_usuario: uid
            },
            onSuccess: function(transport) {
                $('casiMoroso').update(transport.responseText);
            },
            onFailure: function(transport) {
                $('casiMoroso').update(transport.responseText);
                new Ajax.Request(domain+'trigger.aspx', {
                  method: 'post',
                  parameters: {
                    mode: 'postCrash',
                    url: document.location.href+' / '+transport.responseText
                  }
                });
            }
        });
    }
}


/* REDIMENSION DE FIRMAS */
resizeSignatures= function() {
    $$('.signature').each(function(item) {
        if(item.getHeight()>230) {
            var link= new Element('a', {
                href: 'javascript:;',
                onclick: 'javascript:xpandSignature(event,'+item.getHeight()+');',
                'class': 'signatureXpander'
            });
            link.insert('<span>Ver firma completa</span>');
            item.insert({bottom: link});
            item.setStyle({
                height: '215px',
                overflow: 'hidden'
            });
            var off= item.cumulativeOffset();
            link.setStyle({
               top: ((off.top+item.getHeight())-link.getHeight()+5)+'px',
               left: off.left+'px'
            });
        }
    });
}

xpandSignature= function(ev, originalHeight) {
    var el= Event.element(ev);
    var signature= el.up('div');
    el.up('a').remove();
    new Effect.Morph(signature, {
        style: 'height:'+originalHeight+'px;overflow:auto;',
        duration: 1
    });
    new PeriodicalExecuter(function(pe) {
        $$('.signatureXpander').each(function(item) {
            var signature= item.up('div');
            var off= signature.cumulativeOffset().top;
            item.setStyle({
               top: ((off+signature.getHeight())-item.getHeight()+5)+'px'
            });
        });
    
        pe.stop();
    }, 1.1);
}