var v3_url="http://www.aunder.org";

function isNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}

var modalWindow = {  

    parent:"body",  

    windowId:null,  

    content:null,  

    width:null,  

    height:null,  

    close:function()  

    {  

        $(".modal-window").remove();  

        $(".modal-overlay").remove();  

    },  

    open:function()  

    {  

        var modal = "";  

    modal += "<div class=\"modal-overlay\"></div>";

        modal += "<div id=\"" + this.windowId + "\" class=\"modal-window\" style=\"width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";  

        modal += this.content;  

        modal += "</div>";      





        $("#contenido").append(modal);  

  

        $(".modal-window").append("<a class=\"close-window\"></a>");  

        $(".close-window").click(function(){modalWindow.close();});  

        $(".modal-overlay").click(function(){modalWindow.close();});  

    }  

};



var previewWeb = function(id) 

{

    var modal = "";

    modal+= "<div id=\"webshot\"><img src=\"http://imagenes.aunder.org/webcache/cache.php?dir="+id+"\"/></div>";  

    $("#webshot").remove();

        $("#webSnap").append(modal);

};



var cargaContactanos = function()  

{  

    source=v3_url+"/contact_form.html";

    modalWindow.windowId = "Cont&atilde;ctanos";  

    modalWindow.width = 480;  

    modalWindow.height = 405;  

    modalWindow.content = "<iframe width='480' height='405' frameborder='0' scrolling='no' allowtransparency='true' src='" + source + "'></iframe>";  

    modalWindow.open();  

};



var cargaEnlace = function()  

{  

    source=v3_url+"/enlaces_form.html";

    modalWindow.windowId = "Unete";  

    modalWindow.width = 480;  

    modalWindow.height = 405;  

    modalWindow.content = "<iframe width='480' height='405' frameborder='0' scrolling='no' allowtransparency='true' src='" + source + "'></iframe>";  

    modalWindow.open();  

};



var cargaPersonalizar = function()  

{  

    source=v3_url+"/personalizaRSS.php";

    modalWindow.windowId = "Personalizar";  

    modalWindow.width = 480;  

    modalWindow.height = 405;  

    modalWindow.content = "<iframe width='480' height='405' frameborder='0' scrolling='no' allowtransparency='true' src='" + source + "'></iframe>";  

    modalWindow.open();  

};



$(document).ready(function() {





 $("#tabs").stop().animate({opacity: "0.6"},0);  

 

 $("#header").hover(function () {

    $("#tabs").stop().animate({opacity: "0.9"},200);},

            function () { $("#tabs").stop().animate({opacity: "0.6"},200); });



 $("#au_recomienda_data").stop().animate({height: "20px"},0);

 $("#au_recomienda_data2").stop().animate({height: "0px"},0);  

 

 $("#indice_au_recomienda").hover(function () {

    $("#au_recomienda_data").stop().animate({height: "40px"},200);

        $("#au_recomienda_data2").stop().animate({height: "0px"},200);

    },

            function () { $("#au_recomienda_data").stop().animate({height: "20px"},200); 

                        $("#au_recomienda_data2").stop().animate({height: "0px"},200);          

});





 $(".img_serie").hide();  

 

 $(".serie").dblclick(function () {

    $(this).children(".img_serie").slideToggle("fast"); });



$("#avatar").show();

$("#datos_user_posts").show();

$("#datos_user_pms").show();



$("#avatar").animate({left: "60px", top: "60px"},0);

$("#datos_user_posts").animate({left: "-180px", top: "60px"},0);

$("#datos_user_pms").animate({left: "300px", top: "60px"},0);







var X,r;

$("#avatar_contenido").mouseenter(function(e) {

X=e.pageX;

r=1;

});



$("#avatar_contenido").mouseover(function(e) {

var mov=e.pageX-X;

if (mov<-60 && r>0){

    var avl=$("#avatar").position().left;

    var pol=$("#datos_user_posts").position().left;

    var pml=$("#datos_user_pms").position().left;

    

    if (avl<=-180){

    avl=-180; 

    pml=20;

    pol=-420;

    }

    else if (avl>=200){

    avl=60;

    pol=-180;

    pml=300;

    }

    else {

    avl=-180;

    pml=20;

    pol=-420;

    }

    $("#avatar").animate({left: avl-10+"px"},200);

    $("#datos_user_posts").animate({left: pol-10+"px"},200);

    $("#datos_user_pms").animate({left: pml-10+"px"},200);



    $("#avatar").animate({left: avl+5+"px"},100);

    $("#datos_user_posts").animate({left: pol+5+"px"},100);

    $("#datos_user_pms").animate({left: pml+5+"px"},100);



    $("#avatar").animate({left: avl+"px"},100);

    $("#datos_user_posts").animate({left: pol+"px"},100);

    $("#datos_user_pms").animate({left: pml+"px"},100);



    X=e.pageX;

    mov=0;

    r=0;

}

else if (mov>60 && r>0){

    var avl=$("#avatar").position().left;

    var pol=$("#datos_user_posts").position().left;

    var pml=$("#datos_user_pms").position().left;

    

    if (avl>=300){

    avl=300;

    pml=440;

    pol=60;

    }

    else if (avl<=0){

    avl=60;

    pol=-180;

    pml=300;

    }

    else {

    avl=300;

    pol=60;

    pml=440;

    }

    $("#avatar").animate({left: avl+10+"px"},200);

    $("#datos_user_posts").animate({left: pol+10+"px"},200);

    $("#datos_user_pms").animate({left: pml+10+"px"},200);



    $("#avatar").animate({left: avl+5+"px"},100);

    $("#datos_user_posts").animate({left: pol+5+"px"},100);

    $("#datos_user_pms").animate({left: pml+5+"px"},100);



    $("#avatar").animate({left: avl+"px"},100);

    $("#datos_user_posts").animate({left: pol+"px"},100);

    $("#datos_user_pms").animate({left: pml+"px"},100);

    X=e.pageX;

    mov=0;

    r=0;

}



});







$("#fo_busqueda_serie").keyup(function(e) {

if(e.keyCode == 13) {

    $("#fo_busqueda_serie").submit();

}

});

if ($('.enlaces_noti').length!=0)

{
    var imgOn='http://www.aunder.org/templates/v3Theme/img/imgOnP.png';
    var imgOff='http://www.aunder.org/templates/v3Theme/img/imgOffP.png';
    var data=readCookie('AUCheckin');
    if (data!=null) {
		var i=0;
		var encontrado=false;
		$('.capis').each(function (i) {
			var ids=parseInt($(this).attr('name'));
			var capi=parseInt($(this).attr('value'));
			var data_a=data.split('k');
			var i=0;
			var encontrado=false;
			while (i<data_a.length && !encontrado)
			{
				var f=data_a[i].split('d');
				var n_ids=parseInt(f[0]);
				if (n_ids==ids)
				{
					capis=f[1].split('i');
					var j=0;
					while (j<capis.length && !encontrado)
					{
						if (capis[j].indexOf('-')>0) {
							var paso= capis[j].split('-');
							var ini=parseInt(paso[0]);
							var fin=parseInt(paso[1]);
							encontrado=capi>=ini && capi<=fin;
						}
						else {
							encontrado=(parseInt(capis[j])==capi);
						}
						j++;
					}
				}
				i++;
			}
			if (encontrado) {
				$(this).attr('checked', true);
			}
		});	
	}
    $(function(){
        $("input:checkbox").each(function(){            
			$(this).css("display","none");
			if($(this).is(":checked")){ 
				$(this).after($(document.createElement("img"))
				.attr({src:imgOn,title:'Este ya lo he visto',id:$(this).attr("id")+"kk",width: 60})
					.addClass("chkBoxImg").css({cursor: "pointer", position: "relative", left:"4px", top:"3px", float:"right"}));
			}else{
				$(this).after($(document.createElement("img"))
				.attr({src:imgOff, title:'Este no lo he visto, de momento',id:$(this).attr("id")+"kk",width: 60})
				.addClass("chkBoxImg").css({cursor: "pointer", position: "relative", left:"4px", top:"3px", float:"right"}));
			}
		});
		$("img.chkBoxImg").click(function(){
			i=$(this).parent().find("input:checkbox");
			s=$(this).attr("src");
			pick=$(i)[0].value;
			if(s==imgOn){
				$(this).attr("src",imgOff);
				i.attr("checked",false);
				capis=i.attr("value");
				ids=i.attr("name");
				uid=i.attr("id").replace("marca","");
				//alert(" uid="+uid+" ids="+ids+" capi="+capis);
				$.ajax({
					type: "POST",
					url: "http://www.aunder.org/checkin.php",
					data: "uid="+uid+"&ids="+ids+"&capi="+capis+"&accion=del_capi",
					success: function(msg){

					},
					timeout:5000,
					error: function(request,ajaxOptions,error){
						if (request.status!=0)
							alert(request.status+" - "+ajaxOptions+" - "+request.statusText);
					}
				});
			}else{
				$(this).attr("src",imgOn);
				$(i).attr("checked",true);
				capis=$(i).attr("value");
				ids=$(i).attr("name");
				uid=$(i).attr("id").replace("marca","");
				//alert(i+" uid="+uid+" ids="+ids+" capi="+capis);
				$.ajax({
					type: "POST",
					url: "http://www.aunder.org/checkin.php",
					data: "uid="+uid+"&ids="+ids+"&capi="+capis+"&accion=add",
					success: function(msg){

					},
					timeout:5000,
					error: function(request,ajaxOptions,error){
						alert(request.status+" - "+error+" uid="+uid+" ids="+ids+" capi="+capis);
					}
				});
			}
		});
	});
}


if ($('#Todos').length!=0)

{

    var imgOn='http://www.aunder.org/templates/v3Theme/img/imgOn.png';
    var imgOff='http://www.aunder.org/templates/v3Theme/img/imgOff.png';

    var data=readCookie('AUCheckin');

    var ids=$('#capis_en_serie').html()

    var k=ids.indexOf('checkin_serie_capis(');

    var k1=ids.indexOf(',',k)+1;

    ids=ids.substr(k1,ids.indexOf(')',k)-k1)

    if (data!=null) {

		var data_a=data.split('k');

		var i=0;

		var encontrado=false;

		while (i<data_a.length && !encontrado)

		{

			data_a[i] = data_a[i].replace("1-1","1i1");
			var f=data_a[i].split('d');

			if (f[0]==ids)

			{

				encontrado=true;

				var k2=f[1].indexOf('-');

				while (k2>0)

				{

					var k3=k2;

					while (f[1].charAt(k3)!='i' && k3>0)

						k3--;

					var k4=k2;

					while (f[1].charAt(k4)!='i' && k4<f[1].length)

						k4++;

					var ini=parseInt(f[1].substr(k3+1,k2-1-k3));

					var fin=parseInt(f[1].substr(k2+1,k4-(k2)));

					sucesion=""+ini;

					for (k5=ini+1;k5<=fin;k5++)

					{

						sucesion+="i"+k5;

					}

					f[1]=f[1].replace(ini+"-"+fin,sucesion);

					k2=f[1].indexOf('-');

				}

				var f2=f[1].split('i');

				

				var j=0;

				while (j<f2.length)

				{

					$("INPUT[type='checkbox'][value='"+f2[j]+"']").attr('checked', true);

					j++;

				}

			}

			i++;

		}
	}
    $(function(){
        $("input:checkbox").each(function(){            
    $(this).css("display","none");
    if($(this).is(":checked")){ 
        $(this).after($(document.createElement("img"))
        .attr({src:imgOn,title:'Checkbox',id:$(this).attr("id")})
            .addClass("chkBoxImg"));
    }else{
        $(this).after($(document.createElement("img"))
        .attr({src:imgOff, title:'Checkbox',id:$(this).attr("id")})
        .addClass("chkBoxImg"));
    }});
    $("img.chkBoxImg").click(function(){
        i= "input#"+$(this).attr("id")+":checkbox";
        s=$(this).attr("src");
		pick=$(i)[0].value;
        if(s==imgOn){
            
			if (pick=='Todos')
				{
					$("img.chkBoxImg").attr("src",imgOff);
					$("INPUT[type='checkbox']").attr("checked",false);
				}
			else
				{
					$(this).attr("src",imgOff);
					$(i).attr("checked",false);
				}
        
        }else{
        if (pick=='Todos')
				{
					$("img.chkBoxImg").attr("src",imgOn);
					$("INPUT[type='checkbox']").attr("checked",true);
				}
			else
				{
					$(this).attr("src",imgOn);
					$(i).attr("checked",true);
				}
        }});
});
}



$("#f_busqueda_serie").autocomplete("http://www.aunder.org/series.php", {

        width: 350,

        max: 12,

        highlight: false,

        scroll: true,

        scrollHeight: 500,

        formatItem: function(data, i, n, value) {

            var nombre =value.split(";")[1].replace(/\s/g,"_");

            return "<a href='http://www.aunder.org/Serie/"+nombre+"'><img src='http://www.aunder.org/au/Imagenes/" + value.split(";")[0] + "' /> " + value.split(";")[2]+"</a>";

        },

        formatResult: function(data, value) {

            return value.split(";")[1];

        }

    });



function findValueCallback(event, data, formatted) {

        $("<li>").html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result");

    }

    

function formatItem(row) {

        return row[0] + " (<strong>id: " + row[1] + "</strong>)";

    }

function formatResult(row) {

        return row[0].replace(/(<.+?>)/gi, '');

    }





$('#Todos').click(

   function()

   {
   
      $("INPUT[type='checkbox']").attr('checked', $('#Todos').is(':checked'));   

   }

)





});



function checkin_serie_capis(uid,ids)

{

var capis="";

var valores=$(".capis");
valores=valores[0].form;
for (i=0;i<valores.length;i++)
{
	if (valores[i].checked==true && isNumeric(valores[i].value))
		capis+=valores[i].value+",";
}

if (capis!=""){
	capis=capis.slice(0,-1);
	op="add";
}
else {
	op="del";
}
//alert(capis+" "+uid+" "+ids);

$('.capis').css('opacity','0.5');
k=$('.submit');
$('.submit').replaceWith($('<div id="procesando">&nbsp;<img src="http://www.aunder.org/img/proceso.gif" width="30" height="30"></div>'));

$.ajax({

   type: "POST",

   url: "http://www.aunder.org/checkin.php",

   data: "uid="+uid+"&ids="+ids+"&capi="+capis+"&accion="+op,

   success: function(msg){

        $('#procesando').replaceWith(k);//alert("Gracias por participar");

    },

    timeout:5000,

   error: function(request,error){

    alert(request+" - "+error);

    }

 });

}



function get_rss_feed(url) {

    //clear the content in the div for the next feed.

    $("#feedContent").empty();

    

    //use the JQuery get to grab the URL from the selected item, put the results in to an argument for parsing in the inline function called when the feed retrieval is complete

    $.get(url, function(d) {

 

        //find each 'item' in the file and parse it

        

 

        //name the current found item this for this particular loop run

        var $item = $(d).find('item');

        // grab the post title

        var title = $item.find('title').text();

        // grab the post's URL

        var link = $item.find('link').text();

        // next, the description

        var description = $item.find('description').text();

        //don't forget the pubdate

        var pubDate = $item.find('pubDate').text();

        // now create a var 'html' to store the markup we're using to output the feed to the browser window

        var html = "<div class=\"entry\"><h2 class=\"postTitle\">" + title + "<\/h2>";

        html += "<em class=\"date\">" + pubDate + "</em>";

        html += "<p class=\"description\">" + description + "</p>";

        html += "<a href=\"" + link + "\" target=\"_blank\">Read More >><\/a><\/div>";



        //put that feed content on the screen!

        $('#feedContent').append($(html));  



     $('.blog').each(function () {

            var distance = 10;

            var time = 250;

            var hideDelay = 500;



            var hideDelayTimer = null;



            var beingShown = false;

            var shown = false;

            var trigger = $('.trigger', this);

            var info = $('#feedContent', this).css('opacity', 0);





            $([trigger.get(0), info.get(0)]).mouseover(function () {

                if (hideDelayTimer) clearTimeout(hideDelayTimer);

                if (beingShown || shown) {

                    // don't trigger the animation again

                    return;

                } else {

                    // reset position of info box

                    beingShown = true;



                    info.css({

                        top: -90,

                        left: -33,

                        display: 'block'

                    }).animate({

                        top: '-=' + distance + 'px',

                        opacity: 1

                    }, time, 'swing', function() {

                        beingShown = false;

                        shown = true;

                    });

                }



                return false;

            }).mouseout(function () {

                if (hideDelayTimer) clearTimeout(hideDelayTimer);

                hideDelayTimer = setTimeout(function () {

                    hideDelayTimer = null;

                    info.animate({

                        top: '-=' + distance + 'px',

                        opacity: 0

                    }, time, 'swing', function () {

                        shown = false;

                        info.css('display', 'none');

                    });



                }, hideDelay);



                return false;

            });

        });

    });

 

};



function buscarNoti(){

document.getElementById("f_busqueda_noticia").submit();

}



function buscarSerie(){

document.getElementById("f_busqueda_serie").submit();

}



function readCookie(name) {

    var nameEQ = name + "=";

    var ca = document.cookie.split(';');

    for(var i=0;i < ca.length;i++) {

        var c = ca[i];

        c = c.trim();

        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);

    }

    return null;

}

