$(function() {
	    
		//cache selector
		var images = $(".post-body img"),
		  title = $(".post h3").text() || document.title;
		
	    //make images draggable
	    images.draggable({
		  //create draggable helper
		  helper: function() {
		    return $("<div>").attr("id", "helper").html("<span>" + title + "</span><img id='thumb' src='" + $(this).attr("src") + "'>").appendTo("body");
		  },
		  cursor: "pointer",
		  cursorAt: { left: -10, top: 20 },
		  zIndex: 99999,
		  //show overlay and targets
		  start: function() {
		    $("<div>").attr("id", "overlay").css("opacity", 0.7).appendTo("body");
			$("#tip").remove();
			$(this).unbind("mouseenter");
			$("#targets").css("left", ($("body").width() / 2) - $("#targets").width() / 2).slideDown();
		  },
		  //remove targets and overlay
		  stop: function() {
		    $("#targets").slideUp();
			$(".share", "#targets").remove();
		    $("#overlay").remove();
			$(this).bind("mouseenter", createTip);
		  }
		});
		
		//make targets droppable
		$("#targets li").droppable({
		  tolerance: "pointer",
		  //show info when over target
		  over: function() {
		    $(".share", "#targets").remove();
		    $("<span>").addClass("share").text("Share on " + $(this).attr("id")).addClass("active").appendTo($(this)).fadeIn();
		  },
		  drop: function() {
		    var id = $(this).attr("id"),
			  currentUrl = window.location.href,
			  baseUrl = $(this).find("a").attr("href");

			if (id.indexOf("twitter") != -1) {
			  window.location.href = baseUrl + "/home?status=" + title + ": " + currentUrl;
			} else if (id.indexOf("delicious") != -1) {
			  window.location.href = baseUrl + "/save?url=" + currentUrl + "&title=" + title;
			} else if (id.indexOf("facebook") != -1) {
			  window.location.href = baseUrl + "/sharer.php?u=" + currentUrl + "&t=" + title;
			} else if (id.indexOf("wikio") != -1) {
			  window.location.href = baseUrl + "/sharethis/?url=" + currentUrl + "&t=" + title;
			} else if (id.indexOf("meneame") != -1) {
			  window.location.href = baseUrl + "/submit.php?url=" + currentUrl + "&t=" + title;
			} else if (id.indexOf("bitacoras") != -1) {
			  window.location.href = baseUrl + "/anotaciones/" + currentUrl ;
			}
		  }		  
		});
	  
	    var createTip = function(e) {
		  //create tool tip if it doesn't exist
		  ($("#tip").length === 0) ? $("<div>").html("<span>Drag To Share<\/span><span class='arrow'><\/span>").attr("id", "tip").css({ left:e.pageX + 30, top:e.pageY - 16 }).appendTo("body").fadeIn(2000) : null;
		};
		
		images.bind("mouseenter", createTip);
		
		images.mousemove(function(e) {
		
		  //move tooltip
          $("#tip").css({ left:e.pageX + 30, top:e.pageY - 16 });
        });
	  
	    images.mouseleave(function() {
		
		  //remove tooltip
		  $("#tip").remove();
	    });
	  });


(function(){

window.RetweetJS = {
	// Your Bit.ly Username
	bitly_user: "pizcos",

	// Your Bit.ly API Key
	// Found here: http://bit.ly/account
	bitly_key: "R_d7dcca8a010182d656286ffc333baa4d",

	// The text to replace the links with
	link_text: (/windows/i.test( navigator.userAgent) ? "&#9658;" : "&#9851;") +
		"&nbsp;Retweet",

	// What # to show (Use "clicks" for # of clicks or "none" for nothing)
	count_type: "clicks",

	// Tweet Prefix text
	// "RT @jeresig " would result in: "RT @jeresig Link Title http://bit.ly/asdf"
	prefix: "Comparto:  ",

	// Style information
	styling: "a.retweet { font: 12px ; color: #000; float: right; margin: 0 30px 0 0; border: 2px solid #ccc; padding: 3px; background: #eaeaea; }" +
		"a.retweet span { color: #000;  margin-left: 2px; padding: 5px; }" +
		"a.vert { display: block; text-align: center; font-size: 16px; float: right; margin: 2px 50px 0 0; }" +
		"a.retweet strong.vert { display: block; margin-bottom: 4px; background: #F5F5F5; border: 1px solid #EEE; -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; padding: 3px; }" +
		"a.retweet span.vert { display: block; font-size: 12px; margin-left: 0px; border: 1px solid #ccc; }"
};

//////////////// No Need to Configure Below Here ////////////////

var loadCount = 1;

// Asynchronously load the Bit.ly JavaScript API
// If it hasn't been loaded already
if ( typeof BitlyClient === "undefined" ) {
	var head = document.getElementsByTagName("head")[0] ||
		document.documentElement;
	var script = document.createElement("script");
	script.src = "http://bit.ly/javascript-api.js?version=latest&login=" +
		RetweetJS.bitly_user + "&apiKey=" + RetweetJS.bitly_key;
	script.charSet = "utf-8";
	head.appendChild( script );

	var check = setInterval(function(){
		if ( typeof BitlyCB !== "undefined" ) {
			clearInterval( check );
			head.removeChild( script );
			loaded();
		}
	}, 10);

	loadCount = 0;
}

if ( document.addEventListener ) {
	document.addEventListener("DOMContentLoaded", loaded, false);

} else if ( window.attachEvent ) {
	window.attachEvent("onload", loaded);
}

function loaded(){
	// Need to wait for doc ready and js ready
	if ( ++loadCount < 2 ) {
		return;
	}

	var elems = [], urlElem = {}, hashURL = {};

	BitlyCB.shortenResponse = function(data) {
		for ( var url in data.results ) {
			var hash = data.results[url].userHash;
			hashURL[hash] = url;

			var elems = urlElem[ url ];

			for ( var i = 0; i < elems.length; i++ ) {
				elems[i].href += hash;
			}

			if ( RetweetJS.count_type === "clicks" ) {
				BitlyClient.stats(hash, 'BitlyCB.statsResponse');
			}
		}
	};

	BitlyCB.statsResponse = function(data) {
		var clicks = data.results.clicks, hash = data.results.userHash;
		var url = hashURL[ hash ], elems = urlElem[ url ];

		if ( clicks > 0 ) {
			for ( var i = 0; i < elems.length; i++ ) {
				var strong = document.createElement("strong");
				strong.appendChild( document.createTextNode( clicks + " " ) );
				elems[i].insertBefore(strong, elems[i].firstChild);

				if ( /(^|\s)vert(\s|$)/.test( elems[i].className ) ) {
					elems[i].firstChild.className = elems[i].lastChild.className = "vert";
				}
			}
		}

		hashURL[ hash ] = urlElem[ url ] = null;
	};

	if ( document.getElementsByClassName ) {
		elems = document.getElementsByClassName("retweet");
	} else {
		var tmp = document.getElementsByTagName("a");
		for ( var i = 0; i < tmp.length; i++ ) {
			if ( /(^|\s)retweet(\s|$)/.test( tmp[i].className ) ) {
				elems.push( tmp[i] );
			}
		}
	}

	if ( elems.length && RetweetJS.styling ) {
		var style = document.createElement("style");
		style.type = "text/css";

		try {
			style.appendChild( document.createTextNode( RetweetJS.styling ) );
		} catch (e) {
			if ( style.styleSheet ) {
				style.styleSheet.cssText = RetweetJS.styling;
			}
		}

		document.body.appendChild( style );
	}

	for ( var i = 0; i < elems.length; i++ ) {
		var elem = elems[i];

		if ( /(^|\s)self(\s|$)/.test( elem.className ) ) {
			elem.href = window.location;
			elem.title = document.title;
		}

		var origText = elem.title || elem.textContent || elem.innerText,
			href = elem.href;

		elem.innerHTML = "<span>" + RetweetJS.link_text + "</span>";
		elem.title = "";
		elem.href = "http://twitter.com/home?status=" +
			encodeURIComponent(RetweetJS.prefix +  origText + " http://bit.ly/");

		if ( urlElem[ href ] ) {
			urlElem[ href ].push( elem );
		} else {
			urlElem[ href ] = [ elem ];
			BitlyClient.shorten(href, 'BitlyCB.shortenResponse');
		}
	}

}

})();




$(document).ready(function() {
	/*
		inFrame - Keep Demos Inside the Page with jQuery
		- affects all the links with a class of 'inframe'
		- set a rel attribute like rel="height:400px" on the link for a 400px high iframe
		- if you don't set a height, default is 550px
	*/
	$('a.inframe').click(function() {
		var e=$(this);
		var iframe=e.next('iframe');
 
		if (!e.data('state')) {	//if state is undefined
 
			e.data('state','open'); //set the state to 'open'
 
			// Extract the frame height from the rel attribute
			var frameHeight=e.attr('rel');
			var pat1 = new RegExp('height:');
			pat1.test(frameHeight);
			frameHeight=RegExp.rightContext;
			var pat2 = new RegExp('px');
			pat2.test(frameHeight);
			frameHeight = RegExp.leftContext;
			if ( !frameHeight || (Math.ceil(frameHeight)!=Math.floor(frameHeight)) ) {
				//if it's null or not an integer
				frameHeight = '550'; //default frame height, in case none is specified
			};
			frameHeight += 'px';
 
			frameWidth = '100%';
 
			// Insert the iframe just after the link
			e.after('<iframe style="width:'+frameWidth+'; height:'+frameHeight+'; border:solid 1px #ccc; margin-bottom:1em; background:#fff;" src=' + e.attr('href') + ' frameborder="0" ></iframe>');
 
			iframe.css('display', 'none');
			// Insert the "loading..." text
			iframe.before(' <small class="quiet"> Loading...</small>')
			iframe.load(function(){	//once content was loaded
				iframe.slideDown(500);	//slide it down
				iframe.prev('small').remove();	//remove the 'loading...'
			});
			e.attr('title','Hide');	//set the link title to 'Hide'
		}
		else if(e.data('state')=='closed') { //if state is 'closed'
			e.data('state', 'open');
			e.next('iframe').slideDown(500);
			e.attr('title','Hide');
		}
		else if(e.data('state')=='open') { //if state is 'open'
			e.data('state', 'closed');
			e.next('iframe').slideUp(500);
			e.attr('title','Show');
		}
		return false;
	});
});


/* 	Twitter Trackbacks Widget v1.0
	Blog : http://www.moretechtips.net
	Project: http://code.google.com/p/twitter-trackbacks-widget/
	Copyright 2009 [Mike @ moretechtips.net] 
	Licensed under the Apache License, Version 2.0 
	(the "License"); you may not use this file except in compliance with the License. 
	You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
*/
(function($){$.fn.twitterTrackbacks=function(allOptions){var defaults={debug:0,url:'',url_querystring:0,n:10,show_n:1,inf_only:0,inf_tip:0,stay_time:5000,enter_time:200,exit_time:200,animate:'opacity',show_avatar:1,show_author:0,show_date:1,image_width:48,reply:'reply',retweet:'retweet',topsy_author_url:0,info:''};allOptions=$.extend({},defaults,allOptions);return this.each(function(){var div=$(this);var count=0,ul=null,vp=-1,startI=-1,endI=-1;var op=allOptions;var effectParams=new Object;var topsyURL='';var requested=function(json){if(!json.response.list){if(op.debug)div.html('<b style="color:red">Error:unkown</b>');return;}var rs=json.response.list;count=rs.length;if(count==0)return;topsyURL=json.response.topsy_trackback_url;ul=$('<ul class="ttw-inner"></ul>').appendTo(div.html(''));for(var i=0;i<count;i++)addLI(rs[i]);if(op.show_n>0)fadeIn();};var addLI=function(x){var uname=x.author.url.replace('http://twitter.com/','');var id='';if(x.permalink_url)id=x.permalink_url.replace('http://twitter.com/'+uname+'/status/','');else x.author.photo_url='http://cdn2.topsy.com/asset/master.16412.82c193e596/img/twitter_user.png';if(!x.author.influence_level)x.author.influence_level=0;var li=$('<li'+(op.show_n>0?' style="display:none"':'')+' class="ttw-inf-'+x.author.influence_level+'">'+(op.show_avatar?'<span class="ttw-author-img">'+'<a href="'+(op.topsy_author_url?x.author.topsy_author_url:x.author.url)+'"'+' title="'+x.author.name+(op.inf_tip?' [influence level: '+x.author.influence_level+'/10]':'')+'">'+'<img src="'+x.author.photo_url+'" height="'+op.image_width+'" width="'+op.image_width+'" border="0"/>'+'</a>'+'</span>':'')+'<span class="ttw-body">'+(op.show_author?'<strong>'+'<a href="'+(op.topsy_author_url?x.author.topsy_author_url:x.author.url)+'">'+x.author.name+'</a>'+'</strong>':'')+'<span class="ttw-content">'+x.content+'</span>'+'<span class="ttw-meta">'+(op.show_date?'<a class="ttw-date" href="'+(x.permalink_url?x.permalink_url:topsyURL)+'">'+x.date_alpha+'</a>':'')+(op.reply&&id?' - <a class="ttw-reply" href="http://twitter.com/home?status=@'+uname+'%20&in_reply_to_status_id='+id+'&in_reply_to='+uname+'">'+op.reply+'</a>':'')+(op.retweet?' - <a class="ttw-retweet" href="http://twitter.com/home?status='+encodeURIComponent('RT @'+uname+' '+x.content)+'">'+op.retweet+'</a>':'')+(op.info?' - '+op.info:'')+'</span>'+'</span>'+'</li>').appendTo(ul);var cont=$('span.ttw-content',li);cont.html(linkify(cont.html()));};var fadeOut=function(){$('li',ul).eq(startI).fadeOut(op.exit_time,fadeIn);if(op.show_n>1)$('li',ul).slice(startI+1,endI).fadeOut(op.exit_time);};var fadeIn=function(){vp++;if(vp*op.show_n>=count)vp=0;startI=vp*op.show_n;endI=(vp+1)*op.show_n;$('li',ul).eq(startI).animate(effectParams,op.enter_time,"linear",fadeStill);if(op.show_n>1)$('li',ul).slice(startI+1,endI).animate(effectParams,op.enter_time,"linear");};var fadeStill=function(){ul.animate({opacity:1},op.stay_time,"linear",fadeOut);};var linkify=function(d){return d.replace(/\bhttps?\:\/\/\S+/gi,function(b){var c='';b=b.replace(/(\.*|\?*|\!*)$/,function(m,a){c=a;return''});return'<a class="ttw-link" href="'+b+'">'+((b.length>25)?b.substr(0,24)+'...':b)+'</a>'+c;}).replace(/\B\@([A-Z0-9_]{1,15})/gi,'@<a class="ttw-at" href="http://twitter.com/$1">$1</a>').replace(/\B\#([A-Z0-9_]+)/gi,'<a class="ttw-hashtag" href="http://search.twitter.com/search?q=%23$1">#$1</a>')};var request=function(){var data={url:op.url,infonly:op.inf_only,perpage:op.n};$.ajax({url:'http://otter.topsy.com/trackbacks.js',data:data,success:requested,dataType:'jsonp'});};var init=function(){if(div.attr('options')){try{op=eval('('+div.attr('options')+')');}catch(e){div.html('<b style="color:red">'+e+'</b>');return;}op=$.extend({},defaults,op);};effectParams[op.animate]='show';if(!op.url)op.url=location.protocol+'//'+location.host+location.pathname+(op.url_querystring?location.search:'');request();};init();});}})(jQuery);jQuery(document).ready(function(){jQuery('div.twitter-trackbacks').twitterTrackbacks();});



//<![CDATA[
function relatedPostsWidget(userOp){
    var self = this;
    var op = {
        'blogURL':''
        ,'maxPosts':5
        ,'maxTags':5
        ,'maxPostsPerTag':5
        ,'containerSelector':''
        ,'tags':null
        ,'loadingText':'Cargando entradas relacionadas'
        ,'loadingClass':''
        ,'relevantTip':''
        ,'relatedTitle':'Te puede interesar'
        ,'recentTitle':'Entradas recientes'
        ,'postScoreClass':''
        ,'onLoad':false
    };
    op = $.extend({}, op, userOp);
    var tagsLoaded = 0,div= null,ul=null;
    // If no contianer selected , will create div in place of script call
    if (!op.containerSelector) {
        document.write('<div id="related-posts" />');
        op.containerSelector = '#related-posts';
    }
    // Tag json posts are loaded
    var tagLoaded = function(json,status){
        tagsLoaded++;
        if(json.feed.entry) {
            for (var i=0; i<json.feed.entry.length; i++) {
                var entry = json.feed.entry[i];
                var url='';
                for (var k=0; k<entry.link.length; k++) {
                    if(entry.link[k].rel=='alternate') {
                        url = entry.link[k].href;
                        break;
                    }
                }
                var title = entry.title.$t;
                //Ignore current url
                if(location.href.toLowerCase()!= url.toLowerCase()) addPost(url,title);
            }
        } 
        // Loading posts of all tags is done
        if(tagsLoaded>=op.tags.length) {
             ul.attr('class','');
             $('#related-posts-loadingtext',div).remove();
             // Hide extra posts if maxPosts >0
             if(op.maxPosts>0) $('li:gt('+ (op.maxPosts-1) +')',ul).remove();
        }    
    }
    // Add post and re-order
    var addPost = function(url,title) {
        //current LI items inside of UL
        var list = $('li',ul);
        for(var i=0; i<list.length; i++) {
            //get score
            var a= $('a', list.eq(i) );
            var sc = getScore(a);
            //Post exists ?
            if(a.attr('href')==url) {
                //Yes : Then increment score
                setScore(a,++sc);
                //Re-order : compare with prevoius li items
                for(var j=i-1; j>=0; j--){
                    // find the item with higher score than current
                    var jA= $('a', list.eq(j) );
                    if (getScore(jA)>sc) {
                        // re-order if only there are items in the middle to appear before
                        if(i-j>1) list.eq(j).after(list.eq(i));
                        return;
                    }
                };
                // If no higher item then this one should go first
                if(i>0) list.eq(0).before(list.eq(i));
                return;
            }
        }
        //Add new post
        ul.append('<li><a href="'+url+'" title="'+(op.relevantTip? op.relevantTip.replace('\d',1):'')+'">'+title+'</a></li>');
    }
    // parse score from attribute
    var getScore = function(a){
        var score = parseInt(a.attr('score'));
        return score>0? score : 1;
    }
    // set score from attribute
    var setScore = function(a,sc) {
        a.attr('score',sc);
        if(op.relevantTip) a.attr('title',op.relevantTip.replace('\d',sc)); 
        if(op.postScoreClass) a.attr('class',op.postScoreClass+sc); 
    }
    // init 
    var initRelatedPosts = function() {
        // append my div to user selected container 
        if(op.containerSelector != '#related-posts'){
            var container = $(op.containerSelector);
            // check contianer is there and only one for pages like home
            if (container.length!=1) return;
            div = $('<div id="related-posts"/>').appendTo(container);
        }
        else div = $(op.containerSelector); // div which I wrote on document
        
        // get tags if wasn't preset
        if (!op.tags) {
            op.tags = [];
            $('a[rel="tag"]:lt('+op.maxTags+')').each(function () {
                var tag= $.trim($(this).text().replace(/\n/g,''));
                if($.inArray(tag,op.tags)==-1) op.tags[op.tags.length]=tag;
            });
        }
        // should make recent posts but no recent title :exit
        if(op.tags.length==0 && !op.recentTitle) return;
        
        //add recent posts title
        if(op.tags.length==0) $('<h2>'+op.recentTitle+'</h2>').appendTo(div);
        //add related posts title if any
        else if(op.relatedTitle) $('<h2>'+op.relatedTitle+'</h2>').appendTo(div);
        
        //Add loading text if any
        if(op.loadingText) $('<div id="related-posts-loadingtext">'+op.loadingText+'</div>').appendTo(div);
        // Appending UL with loading class if selected
        ul= $('<ul '+(op.loadingClass? 'class="'+ op.loadingClass+'"':'')+'/>').appendTo(div);
        
        //recent posts
        if(op.tags.length==0){
            $.ajax({url:op.blogURL+'/feeds/posts/summary/'
                    ,data:{'max-results':op.maxPostsPerTag,'alt':'json-in-script'}
                    ,success:tagLoaded
                    ,dataType:'jsonp'
                    ,cache:true });
        // Tags found , do related posts widget
        }else{
            // Requesting json feeds for each tag    
            for(var t=0; t<op.tags.length;t++) 
                $.ajax({url:op.blogURL+'/feeds/posts/summary/'
                        ,data:{'category':op.tags[t],'max-results':op.maxPostsPerTag,'alt':'json-in-script'}
                        ,success:tagLoaded
                        ,dataType:'jsonp'
                        ,cache:true });
        }    
    }
    // Call init on document ready
    if(op.onLoad) $(window).load(initRelatedPosts);
    else $(document).ready(initRelatedPosts);
}
//]]>


//<![CDATA[
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(6($){$.I.t({k:6(p){u p+J K().L()},M:6(v){5 w={x:\'N\',e:\'l\',f:\'O\',7:\'.7\',y:\'z\',A:\'P\',m:\'\',n:\'B\',g:\'l-Q\'};5 1=$.t(w,v);5 o=4;u 4.q(6(){5 2=$(4);5 r=\'\';5 b=o.k(\'R\');5 C=o.k(\'S\');$(2).T(\'<D h="\'+1.x+\'"></D>\');$(2).3(1.f).q(6(i){5 c=\'\';U(i===0){c=\' c="\'+C+\'"\'}r+=\'<8><a\'+c+\' V="#\'+b+\'">\'+$(4).j()+\'</a></8>\';$(4).E()});$(2).B(\'<9>\'+r+\'</9>\');$(2).3(1.7).F();$(2).3(1.7+\':s\').z().W(\'<\'+1.f+\'><a X="0" h="Y" Z="\'+b+\'" c="\'+b+\'">\'+$(2).3("9>8:s").j()+\'</a></\'+1.f+\'>\');$(2).3("9>8:s").G(1.e).3(\'a\')[1.n](\'<d h="\'+1.g+\'">\'+1.m+\'</d>\');$(2).3(\'9>8>a\').q(6(i){$(4).10(6(H){H.11();$(2).3(\'9>8.l\').12(1.e).3("d."+1.g).E();$(4).13();$(2).3(1.7+\':14\').F();$(2).3(1.7).15(i)[1.y](1.A);$(\'#\'+b).j($(4).j()).16();$(4)[1.n](\'<d h="\'+1.g+\'">\'+1.m+\'</d>\').17().G(1.e)})})})}})})(18);',62,71,'|options|el|find|this|var|function|tabbody|li|ul||contentAnchor|id|span|currentClass|tabhead|currentInfoClass|class||text|getUniqueId|current|currentInfoText|currentInfoPosition|||each|list|first|extend|return|config|defaults|wrapperClass|fx|show|fxspeed|prepend|tabsAnchor|div|remove|hide|addClass|event|fn|new|Date|getTime|accessibleTabs|content|h4|normal|info|accessibletabscontent|accessibletabs|wrapInner|if|href|before|tabindex|accessibletabsanchor|name|click|preventDefault|removeClass|blur|visible|eq|focus|parent|jQuery'.split('|'),0,{}))
//]]>


