var gl = {
    offset : 18,
    offsetTumblr: 10,
    masFotoloh : 9,
    commentsToShow: 30
}
var js = {
    loading : function(texto){
        if(!texto) texto = "Cargando";
        $("body").append('<div class="loading" />');
        var altura = $("body").height();
        var style = 'display:block; z-index: 2800; width:100%; position:absolute; top:0;left:0; height:' + altura +'px; background:url(/wp-content/themes/tc12m/css/ui/bg-info.png);';
        $(".loading").attr("style", style);
        $(".loading").append('<div class="loadingText">'+ texto +'<div>');
        var styleText = 'color: #fff;position:fixed; top: 39%;left: 48%';
        $(".loadingText").attr("style", styleText);
		$(".loading").bind("click", function(){$(".loading").remove();});	

    },
    newSabiaUd : function(e,i){
        $.ajax({
            url:'/ajax/',
            dataType:'json',
            data: "sabiausted=true",
            error :function(){ },
            success:function(data){
                $(i).next().next().remove();
                $(i).next().remove();
                $(i).after($.base64_decode(data));
            }
        })
    },
    masArchivo : function(e,i){
        js.loading();
        offset = gl.offset;
        gl.offset = gl.offset + 18;
        var itemesPrev = $(i).parent().find(".item").length;
        $.ajax({
            url:'/ajax/',
            dataType:'json',
            data: "archivo=true&categoria="+i.rel+"&offset=" + offset,
            error :function(){
                $(i).remove()
                },
            success:function(data){
                if($.base64_decode(data)=="Llegamos al final"){
                    $(i).after('<span class="moreContentLoader">'+$.base64_decode(data)+'</span>');
                    $(i).remove();
                }else{
                    $(i).prev().append($.base64_decode(data));
                    js.hcol("#mas-archivo li.item");
                    var itemesNext = $(i).parent().find(".item").length
                    if (itemesNext - itemesPrev <  18 ){
                        $(i).after('<span class="moreContentLoader">Llegamos al fin</span>');
                        $(i).remove();
                    }
                    setTimeout(function(){$("#mainContent .articleList li a img").display({target: js,func:"articleList"});}, 800)
                }
            },
            complete : function(){
                 setTimeout(function(){$(".loading").fadeOut().remove();},1000);
			}
        })

    },
    masTumblr : function(e,i){
        js.loading();
        var itemesPrev = $(i).parent().find(".article").length;
        offset = gl.offsetTumblr;
        gl.offsetTumblr = gl.offsetTumblr + 10;
        $.ajax({
            url:'/ajax/',
            dataType:'json',
            data: "tumblr=true&categoria="+i.rel+"&offset=" + offset,
            error :function(){
                $(i).remove()
                },
            success:function(data){
                var structuraHTML = $.base64_decode(data);
                if($.base64_decode(data)=="Llegamos al final"){
                    $(i).after('<span class="moreContentLoader">'+ structuraHTML +'</span>');
                    $(i).remove();
                }else{
                    $("#masTumblr").before(structuraHTML);
                    var itemesNext = $(i).parent().find(".article").length
                    if (itemesNext - itemesPrev <  10 ){
                        $(i).after('<span class="moreContentLoader">Llegamos al fin</span>');
                        $(i).remove();
                    }
                }
            },
            complete : function(){
                 setTimeout(function(){$(".loading").fadeOut().remove();},1000);
            }
        })
    },
    casadecitas : function(e,i){
        js.loading();
        var itemesPrev = $(i).parent().find("article").length;
        offset = gl.offsetTumblr;
        gl.offsetTumblr = gl.offsetTumblr + 10;
        $.ajax({
            url:'/ajax/',
            dataType:'json',
            data: "casadecitas=true&categoria=casa-de-citas&offset=" + offset,
            error :function(){
                $(i).remove()
                },
            success:function(data){
                var structuraHTML = $.base64_decode(data);
                if($.base64_decode(data)=="Llegamos al final"){
                    $(i).after('<span class="moreContentLoader">'+$.base64_decode(data)+'</span>');
                    $(i).remove();
                }else{
                    $(i).before($.base64_decode(data));
                    var itemesNext = $(i).parent().find("article").length
                    if (itemesNext - itemesPrev <  10 ){
                        $(i).after('<span class="moreContentLoader">Llegamos al fin</span>');
                        $(i).remove();
                    }
                }
            },
            complete : function(){
                    setTimeout(function(){$(".loading").fadeOut().remove();},1000);
            }
        })
    },
    masFotoloh : function(e,i){
        js.loading("Cargando");
        var itemesPrev = $(i).parent().find(".item").length;
        offset = gl.masFotoloh;
        gl.masFotoloh = gl.masFotoloh + 9;
        $.ajax({
            url:'/ajax/',
            dataType:'json',
            data: "fotoloh=true&offset=" + offset,
            error :function(){
                $(i).remove()
                },
            success:function(data){
                if($.base64_decode(data)=="Llegamos al final"){
                    $(i).after('<span class="moreContentLoader">'+$.base64_decode(data)+'</span>');
                    $(i).remove();
                }else{
                    var alto = $(i).prev().height() * 2;
                    $(i).prev().height(alto);
                    $(i).prev().append($.base64_decode(data));
                    var itemesNext = $(i).parent().find(".item").length
                    if (itemesNext - itemesPrev <  9 ){
                        $(i).after('<span class="moreContentLoader">Llegamos al fin</span>');
                        $(i).remove();
                    }
                }
            },
            complete : function(){
                 Shadowbox.setup();
                 setTimeout(function(){
                        $(".loading").fadeOut("slow").remove();
                      $('#fotoloh .reordenar').masonry({itemSelector : '.item'}).masonry( 'reloadItems' ).masonry( 'reload' );
                 },1000);
            }
        })
    },
    masAtw : function(e,i){
        js.loading("Cargando");
        var itemesPrev = $(i).parent().find(".item").length;
        offset = gl.masFotoloh;
        gl.masFotoloh = gl.masFotoloh + 9;
        $.ajax({
            url:'/ajax/',
            dataType:'json',
            data: "masAtw=true&offset=" + offset,
            error :function(){
                $(i).remove()
                },
            success:function(data){
                if($.base64_decode(data)=="Llegamos al final"){
                    $(i).after('<span class="moreContentLoader">'+$.base64_decode(data)+'</span>');
                    $(i).remove();
                }else{
                    var alto = $(i).prev().height() * 2;
                    $(i).prev().height(alto);
                    $(i).prev().append($.base64_decode(data));
                    var itemesNext = $(i).parent().find(".item").length
                    if (itemesNext - itemesPrev <  9 ){
                        $(i).after('<span class="moreContentLoader">Llegamos al fin</span>');
                        $(i).remove();
                    }
                }
            },
            complete : function(){
                Shadowbox.setup();
                 setTimeout(function(){
                        $(".loading").fadeOut().remove();
                      $('#fotoloh .reordenar').masonry({itemSelector : '.item'}).masonry( 'reloadItems' ).masonry( 'reload' );
                 },1000);


            }
        })
    },
    buscarPage : function(e,i){
        js.loading("Cargando");
        var zona = i.href.split('/');
        var page = parseInt(zona[4]) + 1
        var newpage = "/" +zona[3] + "/" + page + "/" + zona[5];
        i.href=newpage;
        $('#newPage').load(newpage + ' ul.articleList.list .item', function(){
            
            
                $('ul.articleList.list').append($('#newPage').html());
            
            
        }).ajaxComplete(function(){
                   setTimeout(function(){$(".loading").fadeOut().remove();},1000);
            return false;
        });
        return false;
    },
    tagPage : function(e,i){
        js.loading("Cargando");
        var zona = i.href.split('/');
        var page = parseInt(zona[4]) + 1
        var newpage =  zona[3] + "/" + page + "/";
        i.href="/" + newpage;
        $('#newPage').load(newpage +' ul.articleList.list .item', function(response, status, xhr){
            if (status == "error") {
                $(i).after('<p class="moreContentLoader" id="buscarPage">No se econtraron más resultados.</p>');
                $(i).remove();
            }
            else{
                $('ul.articleList.list').append($('#newPage').html());
            }
            $('#newPage').html(" ");
        }).ajaxComplete(function(){
                 setTimeout(function(){$(".loading").fadeOut().remove();},1000);

        });
    },
    menuactive : function(e,i){
        $("#scopeNavigation ul li").removeClass("selected");
        $(i).parent().addClass("selected");
        $('#siteContent-container').load(i.href + '#siteContent-container section', function(){
            $(".evtr").evt({
                target: js,
                event:'click',
                "listen":"item.rel"
            });
        });
    },
    hcol :function(item){
        var lista = 0;
        $.each($(item), function(i,e){
            lista = Math.max(lista, $(e).height());
        })
        $(item).height(lista);
    },
    articleList : function(item){
        $(item).parent().wrap('<div class="wrapTrama" style="position:relative;" />')
        $(item).parent().after('<div class="trama"></div>');
        $(item).parent().next().css("background-image","url(/wp-content/themes/tc12m/css/ui/trama.png)");
        $(item).parent().next().css("width",item.width);
        $(item).parent().next().css("height",item.height);
        $(item).parent().next().css("position","absolute");
        $(item).parent().next().css("top","2px");
        $(item).parent().next().css("left","2px");
        $("div.wrapTrama").bind("mouseenter",function(){$(this).find(".trama").hide();}).bind("mouseleave",function(){$(this).find(".trama").show();})
    },
    showComments : function(e, item){
        js.loading("cargando");
        $("#comments").fadeIn('slow').slideDown('slow');
        $("#commentsList li:gt(20)").hide();
        $("#commentsList li:lt(21)").addClass("showit");
        var $target = $($(item).attr("href"));
        $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
        var targetOffset = $target.offset().top;
        $('html,body').animate({
            scrollTop:targetOffset
        }, 800);
         setTimeout(function(){$(".loading").fadeOut().remove();},1000);


    },
    gotoCommentsReply : function(e, item){

        $("#comments").show();
        $("#commentsList li").addClass("showit");
        setTimeout(function(){
            var $target = $("#comment_form");
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
            var targetOffset = $target.offset().top;
            $('html,body').animate({scrollTop:targetOffset}, 800);return false;
        }, 1000);


    },
    showMoreComments : function(e, item){
        js.loading("cargando");
        var items = gl.commentsToShow;
        var targeItem = items - 10 == 20 ? 21 : items - 10;
        var $target = $("#" + $("#commentsList li:eq("+ targeItem +")").attr("id") )
        gl.commentsToShow += 20;
        $("#commentsList li:lt("+items+")").fadeIn().addClass("showit");
        if ($("#commentsList li").not(".showit").length==0) $("#showMoreComments").remove();
        $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
        var targetOffset = $target.offset().top;
        $('html,body').animate({
            scrollTop:targetOffset
        }, 800);
		setTimeout(function(){$(".loading").fadeOut().remove();},1000);
    },
    goComment : function(){
         $('#showComments').trigger("click");
    },
    postComment:function(){
        js.loading();
        var datos=$("#comment_form").serialize();
        $.ajax({
            url:"/wp-comments-post.php",
            type:"POST",
            data:datos,
            success:function(result){
                lastComments = $(result).find("#commentsList li:last-child");
                if(!$.ide("#commentsList")) {
                    $("#comments").prepend('<ul class="commentsList" id="commentsList" />');
                }
                $("#commentsList").append(lastComments);
            },
            complete : function (){
                 setTimeout(function(){$(".loading").fadeOut().remove();},1000);
            }
                
        })
        var timeline = "comment="+$("#comment_form #comment").val() +"&comment_post_ID="+$("#comment_form #comment_post_ID").val() +"&social_connect_comment_via_provider="+$('#comment_form input[name$="social_connect_comment_via_provider"]').val()
        $.ajax({
            url:"/ajax/",
            type:"GET",
            data:timeline,
            success:function(result){
			
            }
                
        })
    },
    closeBwUpdate : function(){
         $.post("/wp-admin/admin-ajax.php",{
          action : "ajax_zone" ,
          estado : "closeupdate"
        });
       $("#browserUpdate").fadeOut();
    },
    cerrarConti: function(e,i){
//       $.post("/wp-admin/admin-ajax.php",{
//	      action : "ajax_zone" ,
//	      estado : "cerrado"
//       });
       $("#daBomb").fadeOut();
    },
    min2min : function(){
	    $.ajax({
            url:"/ajax/",
            type:"GET",
            data:"min2min=true",
            success:function(result){
            $("#min2min").html($.base64_decode(result));
            }                
        })
	}
}
$(function(){
  setTimeout(function(){
//var $container = $('#fotoloh .reordenar');
//$container.imagesLoaded( function(){$container.masonry({itemSelector : '.item'});});
 $('#fotoloh .reordenar').masonry({itemSelector : '.item'}).masonry( 'reloadItems' ).masonry( 'reload' );
},3000);

var $container = $('#fotoloh .reordenar');
$container.imagesLoaded( function(){$container.masonry({itemSelector : '.item'});});

$(".evtc").evt({
        target: js,
        event:'click',
        "listen":"item.id"
    });
    $(".evtr").evt({
        target: js,
        event:'click',
        "listen":"item.rel"
    });
    if (location.hash == "#comments"){
        setTimeout(function(){
            $('#showComments').trigger("click")
        }, 500);
    }
    if (location.hash == "#respond"){js.gotoCommentsReply();}
    if ($.browser.msie && ($.browser.version =="8.0" || $.browser.version =="7.0" || $.browser.version =="6.0")){
        $(".bottomLogo").hide();
        $("#browserUpdate").show();

    }
    if ($.browser.msie){
        $(".moreContentLoader").attr("style", "background-position:50% 0 !important;");
    }
    $("#mainContent .articleList li a img, #secondaryContent .articleList li a img, #thePlanet .articleList li a img").display({
        target: js,
        func:"articleList"
    });

   // var sabiaUstedQue = setInterval(function(){ $("#newSabiaUd").trigger("click");}, 60000 );
    if($.ide("#daBomb")) var min2min = setInterval(function(){js.min2min()}, 60000 ); 

    setTimeout(function(){js.hcol("#mainContent .colHeight");}, 500 );
    setTimeout(function(){js.hcol("#secondaryContent .colHeight");}, 500 );
    setTimeout(function(){js.hcol("#thePlanet .altura ul.list .item");}, 500 );
    setTimeout(function(){js.hcol(".launcher .mediumCol .articleList");}, 500 );
    setTimeout(function(){js.hcol("#mainContent #mas-archivo li.item");}, 500 );
    setTimeout(function(){js.hcol("#secondaryContent #mas-archivo li.item");}, 500 );
    setTimeout(function(){js.hcol("#thePlanet #quotation .hgcol");}, 500 );

 	var shadow = false;
	$('a[rel="shadowbox"], a[rel="shadowbox[fotoloh]"], a[rel="shadowbox;width=760;height=530"]').each(function(index) {
		shadow = true;
  	});
	if(shadow){
	    Shadowbox.init({overlayOpacity: 0.8})
    }

});
(function($) {
    $.fn.evt = function(params){
        if(params.event=="click" || params.event=="change"){
            $.each(this,function(i,item) {
                eval("params.target." + eval(params.listen));
                if ( $.isFunction(eval("params.target." + eval(params.listen)))){
                    $(item).bind(params.event, function(event){
                        eval("params.target."+  eval(params.listen) +"(event, item)");
                        return false;
                    })
                }
            });
        }
        else{
            $.each(this,function(i,item) {
                if ( $.isFunction(eval("params.target."+eval(params.listen)))){
                    $(item).bind("mouseenter",function(event){
                        eval("params.target."+eval(params.listen)+"(event, item, true)");
                        return false;
                    }).bind("mouseleave",function(event){
                        eval("params.target."+eval(params.listen)+"(event, item, false)");
                        return false;
                    })
                }
            });
        }
    }
    $.fn.display = function(params){
        $.each(this,function(i,item) {
            eval("params.target."+ params.func + "(this)");
        })
    }
    $.fn.doit = function(params){
        if (document.getElementById($(this).attr("id"))) eval("params.target."+ params.func + "(this)");
    }
    $.fn.jsdo = function(params){
        if (document.getElementById($(this).attr("id"))) js.getAjaxSite(params.func, params.siteurl, params.query,params.type);
    }
})(jQuery);
$.extend({
    ide : function(id) {
        var id = id.split("#");
        return document.getElementById(id[1])?true:false;
    },
    utf8_decode : function( str_data ) {
        var tmp_arr = [], i = ac = c = c1 = c2 = 0;

        while ( i < str_data.length ) {
            c = str_data.charCodeAt(i);
            if (c < 128) {
                tmp_arr[ac++] = String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = str_data.charCodeAt(i+1);
                tmp_arr[ac++] = String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = str_data.charCodeAt(i+1);
                c3 = str_data.charCodeAt(i+2);
                tmp_arr[ac++] = String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return tmp_arr.join('');
    },
    base64_decode: function( data ) {
        var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, dec = "", tmp_arr = [];

        do {  // unpack four hexets into three octets using index points in b64
            h1 = b64.indexOf(data.charAt(i++));
            h2 = b64.indexOf(data.charAt(i++));
            h3 = b64.indexOf(data.charAt(i++));
            h4 = b64.indexOf(data.charAt(i++));

            bits = h1<<18 | h2<<12 | h3<<6 | h4;

            o1 = bits>>16 & 0xff;
            o2 = bits>>8 & 0xff;
            o3 = bits & 0xff;

            if (h3 == 64) {
                tmp_arr[ac++] = String.fromCharCode(o1);
            } else if (h4 == 64) {
                tmp_arr[ac++] = String.fromCharCode(o1, o2);
            } else {
                tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
            }
        } while (i < data.length);

        dec = tmp_arr.join('');
        dec = $.utf8_decode(dec);

        return dec;
    }
})

