var currentKey,qs,hint,twitter_user,config,go,msg,errorInterval,errorTime=10000,tags,photos,user,disallowedWords=["use","the","to","and","of","is","was","my","an","in","but","on","for","as","that","they","it","from","your","like","with","it's","can","can't","their","they're","any","yet","do","don't","are","this","these","those","that","that's","you","me","by","than","may","about","behind","from","on","toward","above","below","in","on top of","under","across","beneath","onto","underneath","after","beside","inside","out","until","against","between","up","along","by","into","over","upon","among","down","like","past","with","around","during","near","since","within","at","except","of","through","without","before","for","off","to","of","and","but","or","so","both","not","either","neither","whether","also","after","before","when","while","since","until","although","even","if","because","all","another","any","anybody","anyone","anything","both","each","each other","either","everybody","everyone","everything","few","he","her","hers","herself","him","himself","his","I","it","its","itself","little","many","me","mine","more","most","much","myself","neither","no one","nobody","none","nothing","one","one another","other","others","ours","ourselves","several","she","some","somebody","someone","something","that","theirs","them","themselves","these","they","this","those","us","we","what","whatever","which","whichever","who","whoever","whom","whomever","whose","you","yours","yourself","yourselves","just","good","have","would","get","going","great","there","make","how","had","day","too","back","yes","no","were","could","should","got","will","way","new","give","i'm","i'll","via","(via","rt","i've","your","you're","our","only","today","reading:"];function toggleOptions(){$('#options').toggleClass('collapsed');}
function collapseOptions(){$('#options').addClass('collapsed');}
function setMsg(text,after,classname){after=after||'&#8230;';msg=msg||$('#msg');if(!msg.length){msg=$('<p />').attr('id','msg').prependTo('#bd');}else{msg.removeAttr('class');}
if(classname){msg.attr('class',classname);}
msg.html(text+'<span class="after">'+after+'</span>').show();}
function hideMsg(){msg.hide();}
function startError(){errorInterval=setInterval(error,errorTime);}
function clearError(){if(errorInterval){clearInterval(errorInterval);}}
function error(msg){msg=msg||'An <acronym title="Application Programming Interface">API</acronym> is fail whalin&#8217;. Is the Twitter account private?';clearError();setMsg(msg,'&nbsp;','error');}
function twitterGet(username){setMsg('Tapping into your state-of-mind');startError();var service=qs.get("service")||"http://twitter.com/statuses/user_timeline/";$.getJSON(service+username+".json?callback=?",function(data){twitterCallback(data);});}
function wordPop(string,disallowed,min,limit){disallowed=disallowed||new Array();min=min||3;if(!limit||limit>20)limit=20;string=$.trim(string.toLowerCase());var arr=string.split(' ');for(var i in arr){if(arr[i].length&&arr[i].indexOf('http://')==-1){var first=arr[i].charAt(0).replace(/[^a-zA-Z 0-9]+/g,'');if(!first.length){arr[i]=arr[i].substr(1);}
if(arr[i].length){var last=arr[i].charAt(arr[i].length-1).replace(/[^a-zA-Z 0-9]+/g,'');if(!last.length){arr[i]=arr[i].substr(0,arr[i].length-1);}}}else{arr.splice(i,1);}}
var words=new Object();for(var i in arr){var word=arr[i];if(!in_array(word,disallowed)&&word.length>=min&&word.lastIndexOf('http')==-1){if(words[word]){words[word]++;}else{words[word]=1;}}}
var freq=new Array();for(var word in words){var num=words[word];if(!isNaN(num)){if(!freq[num])freq[num]=new Array();freq[num].push(word);}}
var list=new Array();var highest=0;for(var num in freq){if(num>highest){highest=num;}}
for(var i=highest;i>0;i--){if(freq[i]){for(var n=0;n<freq[i].length;n++){list.push(freq[i][n]);}}}
list=list.slice(0,limit);var eggs=getHolidayKeywords();if(eggs){list=eggs.concat(list);}
return list;}
function getHolidayKeywords(){var today=new Date();var dates=[{m:11,d:25,words:['santa','snowman']},{m:9,d:31,words:['pumpkin','scary']}];for(var i in dates){var date=dates[i];if(date.m==today.getMonth()&&date.d==today.getDate()){return date.words;}}
return false;}
function getImgPath(photo,size){if(size){size='_'+size;}else{size='';}
return'http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+size+'.jpg';}
function base_encode(num,alphabet){alphabet=alphabet||'123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';var base_count=alphabet.length;var encoded='';while(num>=base_count){var div=num/base_count;var mod=(num-(base_count*intval(div)));encoded=alphabet.charAt(mod)+encoded;num=intval(div);}
if(num)encoded=alphabet.charAt(num)+encoded;return encoded;}
function getImgLink(photo,tiny){tiny=tiny||false;return tiny?'http://flic.kr/p/'+base_encode(photo.id):'http://www.flickr.com/photos/'+photo.owner+'/'+photo.id;}
function getDate(shorten){var today=new Date(),ref=['January','February','March','April','May','June','July','August','September','October','November','December'];var month=ref[today.getMonth()];if(shorten){month=month.substring(0,3);}
return month+' '+today.getDate()+', '+today.getFullYear();}
function getTime(){var today=new Date();var h=today.getHours();var m=today.getMinutes();var period='am';if(h>12){h=h-12;period='pm';}
if(h==0){h=12;}
if(m<10){m='0'+m;}
return h+':'+m+' '+period;}
function twitterCallback(status){clearError();setMsg('Digging your mojo');var string=new String();for(var i in status){var update=status[i];if(i==0)user=update.user;string+=update.text+' ';}
tags=wordPop(string,disallowedWords,3,qs.get("num-tags",10));flickr_user=qs.get('flickr-user');if(flickr_user){flickrUserGet(flickr_user);}else{flickrGet(tags);}}
function flickrUserGet(username){setMsg('Identifying witnesses');startError();$.getJSON('http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=bf33532b09e209abdc1a0b1ee18d8c58&username='+username+'&format=json&jsoncallback=?',function(data){clearError();if(data.stat=='fail'){error("The Flickr user you provided doesn't exist.");}else{flickrGet(tags,data.user.nsid);}});}
function flickrGet(tags,nsid){setMsg('Picking up good vibrations');startError();$.getJSON(getFlickrFeed(null,nsid),function(data){flickrCallback(data);});}
function getFlickrFeed(format,nsid){format=format||'json&jsoncallback=?';nsid=nsid?'&user_id='+nsid:'';return'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf33532b09e209abdc1a0b1ee18d8c58&tags='+tags.join(',').replace(/\#/,'')+'&content_type=1&media=photos&per_page=50&sort='+qs.get('sort','relevance')+'&extras=date_upload,date_taken,owner_name,tags&safe_search=1'+nsid+'&format='+format;}
function flickrCallback(data){clearError();if(data.stat!='fail'&&data.photos.photo){hideMsg();photos=data.photos.photo;if(photos.length<1){var msg="Sorry, no photos found!.";if(qs.contains('flickr-user')){msg+=' Try searching all Flickr users.';}
error(msg);}else{buildPortwit();}}else{error("Flickr borked! Or your tweets are <em>really</em> esoteric.");}}
function getFeedUrl(){var query=location.search.substring(1,location.search.length);if(query.length){query='?'+query;}
return window.location.pathname+'feed/'+query;}
function buildPortwit(){$('<link />').attr('rel','alternate').attr('type','application/rss+xml').attr('title',user.screen_name+"&#8217;s Portwit (RSS Feed)").attr('href',getFeedUrl()).appendTo('head');var nav='<li id="nav-grid"><a href="#">Grid</a></li>';if($.hasFlashPlayer){nav+='<li id="nav-slideshow"><a href="#">Slideshow</a></li>';}
var portwit=$('<div id="portwit">'+'<ul id="nav">'+nav+'</ul>'+'<div id="frame"></div>'+'<div id="user">'+'<div>'+'<img src="/images/polaroid.png" width="54" height="60" alt="" style="background-image: url('+user.profile_image_url+');" />'+'<p>'+'<a href="http://twitter.com/'+user.screen_name+'" id="user-name" onclick="window.open(this.href);return false" title="View Profile">'+user.name+'</a><span>'+(user.location.length?' of '+user.location:'')+' has been using these words frequently:</span> '+tags.join(', ')+'<br />'+'<a href="'+getFeedUrl()+'" class="rss-link">RSS</a>, '+'<a href="http://twitter.com/home?status='+urlencode("Looking at @"+user.screen_name+"'s Twitter status in photos on @portwiture: http://portwiture.com/"+user.screen_name)+'&source=Portwiture" class="tweet-link" onclick="window.open(this.href);return false">Tweet This!</a>'+'</p>'+'</div>'+'</div>'+'</div>').appendTo('#bd');$('#nav a').click(function(){if(!$(this).hasClass('current')){var id=$(this).parent().attr('id');switch(id){case'nav-grid':buildGrid();break;case'nav-slideshow':buildSlideshow();break;}}
return false;});buildGrid();}
function buildGrid(){$('#nav-grid a').addClass('current');$('#nav-slideshow a').removeClass('current');var frame=$('#frame').html('');var ul=$('<ul />').appendTo(frame);if(!photos.length){return false;}
for(var i in photos){var photo=photos[i];var imgPath=getImgPath(photo,'s');var linkPath=getImgLink(photo);var li=$('<li />').appendTo(ul);var a=$('<a />').attr('id','thumb-'+i).attr('href',linkPath).attr('title',htmlentities(photo.title)).click(function(){var id_int=parseInt($(this).attr('id').replace('thumb-',''));flickrBox(id_int);return false;}).appendTo(li);var img=$('<img />').attr('src',imgPath).appendTo(a);}}
function buildSlideshow(){if($.hasFlashPlayer){$('#nav-slideshow a').addClass('current');$('#nav-grid a').removeClass('current');$('#frame').html('').flash({swf:'/swf/slideshow.swf',params:{allowFullScreen:true,wmode:'transparent',flashvars:'xmlfile='+urlencode(getFeedUrl())+'&xmlfiletype=Media+RSS'},width:750,height:375});}}
function flickrBox(key){var photo=photos[key];if(!photo){alert("You've requested a photo that doesn't exist.");return false;}
currentKey=key;var overlay=$('#overlay');if(!overlay.length){overlay=$('<div />').attr('id','overlay').click(function(){removeFlickrbox();}).appendTo('body');}
sizeOverlay();if(photo.tags.constructor!=Array){photo.tags=photo.tags.split(' ');}
var matches=new Array();for(var i in tags){var tag=tags[i];if(in_array(tag,photo.tags)||in_array(tag.replace(/[^a-zA-Z 0-9]+/g,''),photo.tags)){matches.push(tag);}}
if(matches.length>1){matches='Because you\'ve been using the words <strong>'+matches.join('</strong>, <strong>')+'</strong>.';var last_comma=matches.lastIndexOf(', ');matches=matches.substr(0,last_comma)+' and '+matches.substr(last_comma+1);}else{matches='Because you\'ve been using the word <strong>'+matches.join('')+'</strong>.';}
var title=$.trim(photo.title);if(!title.length){title='Untitled';}
var box=$('#flickrbox');var resetTop=true;if(box.length){resetTop=false;$('#flickrbox-img a:has(img)').remove();}else{box=$('<div />').attr('id','flickrbox').appendTo('body');$('<div id="flickrbox-pos">'+'<div id="flickrbox-img">'+'<a href="#" title="Close" id="flickrbox-close">Close</a>'+'</div>'+'<p id="flickrbox-info" />'+'<ul id="flickrbox-nav">'+'<li id="flickrbox-prev"><a href="#" title="Previous Image">Previous Image</a></li>'+'<li id="flickrbox-next"><a href="#" title="Next Image">Next Image</a></li>'+'</ul>'+'<p id="flickrbox-count" />'+'</div>').appendTo(box);$('#flickrbox-close').click(function(){removeFlickrbox();return false;});$('#flickrbox-prev a').click(function(){prevImage();var pappy=$(this).parent().parent();pappy.css('bottom',pappy.css('bottom'));return false;});$('#flickrbox-next a').click(function(){nextImage();var pappy=$(this).parent().parent();pappy.css('bottom',pappy.css('bottom'));return false;});posFlickrbox(resetTop);}
$('#flickrbox-info').html('<a href="'+getImgLink(photo)+'" onclick="window.open(this.href);return false;"><strong>'+htmlentities(title)+'</strong></a> (<a href="http://twitter.com/home?status='+urlencode(htmlentities(truncate(title,140-(getImgLink(photo,true).length+user.screen_name.length+35)))+" "+getImgLink(photo,true)+" - via http://portwiture.com/"+user.screen_name)+'&source=Portwiture" onclick="window.open(this.href);return false;">Tweet it!</a>)<br />'+'By '+htmlentities(photo.ownername)+'<br />'+matches);$('#flickrbox-count').text((key+1)+' of '+photos.length);if(key<1){$('#flickrbox-prev').hide();}else{$('#flickrbox-prev').show();}
if(key+1<photos.length){$('#flickrbox-next').show();}else{$('#flickrbox-next').hide();}
var flickrImg=new Image();$(flickrImg).load(function(){$('#flickrbox-img a:has(img)').remove();var a=$('<a />').attr('href','#').attr('title','Next Image').click(function(){nextImage();return false;}).prependTo('#flickrbox-img').append(this);$('#flickrbox').css('width',flickrImg.width+'px');$('#flickrbox-img').css({height:flickrImg.height+'px',width:flickrImg.width+'px'});posFlickrbox();});flickrImg.src=getImgPath(photo);}
function truncate(text,len){len=len||60;if(text.length>len){text=text.substring(0,len);text=text.replace(/\w+$/,'');text+='...';}
return text;}
function sizeOverlay(){$('#overlay').css({height:$(document).height()+'px',width:$(document).width()+'px'});}
function posFlickrbox(resetTop){var flickrbox=$('#flickrbox');if(flickrbox.length){var h=$(window).height();var w=$(window).width();var padding=parseInt(flickrbox.css('padding-left').replace('px',''));var t=$(window).scrollTop()+h/50;var l=w/2-(flickrbox.width()+padding*2)/2;var options=resetTop?{top:t+'px',left:l+'px'}:{left:l+'px'};flickrbox.css(options);}}
function removeFlickrbox(){$('#overlay, #flickrbox').remove();currentKey=0;}
function nextImage(change){change=change||1;var next=currentKey+change;if(next>=photos.length){next=0;}else if(next<0){next=photos.length-1;}
if(next<photos.length&&next>-1){flickrBox(next);}}
function prevImage(){nextImage(-1);}
function checkGo(val){val=$.trim(val);if(val.length&&val!=hint){go.removeClass('disabled');}else{go.addClass('disabled');}}
$(document).ready(function(){if(window.location.hash.length){var username=$.trim(window.location.hash.substr(1));if(username.length){window.location='/'+username;}}
$('noscript').remove();qs=new Querystring();twitter_user=$('#twitter-user'),config=$('#config'),go=$('#go');hint=$('label[for=twitter-user]').text();checkGo(twitter_user.val());var currentVal=$.trim(twitter_user.val());if(currentVal.length&&currentVal!=hint){twitterGet(currentVal);}else{twitter_user.val(hint);}
$('input[type=text]').click(function(){$(this).select();}).keyup(function(e){if(e.keyCode==13){config.submit();}else{checkGo($(this).val());}});twitter_user.click(function(){if($(this).val()==hint){$(this).val('');}}).select(function(){if($(this).val()==hint){$(this).val('');}}).blur(function(){if(!$.trim($(this).val()).length){$(this).val(hint);}});config.submit(function(){var val=$.trim(twitter_user.val());if(!val.length||val==hint){return false;}
$('#portwit').remove();collapseOptions();$('#options input[type=text]').each(function(){if(!$.trim($(this).val()).length){$(this).remove();}});$('#options select').each(function(){var selected=$(this).val();var def=null;var options=$('option',this);options.each(function(){if($(this).attr('class')=='default'){def=$(this).val();}});if(selected==def){$(this).remove();}});twitter_user.replaceWith('<div id="'+twitter_user.attr('id')+'">'+val+'</div>');$('#config').attr('action','/'+val+'/');setMsg('Getting the ball rolling');});go.click(function(){$('#config').submit();return false;});$('#options-btn').click(function(){toggleOptions();return false;});$(this).keyup(function(e){switch(e.keyCode){case 192:toggleOptions();break;case 39:if($('#flickrbox').length)nextImage();break;case 37:if($('#flickrbox').length)prevImage();break;case 88:if($('#flickrbox').length)removeFlickrbox();break;}});$.getJSON('http://search.twitter.com/search.json?q=%23whyportwit&rpp=3&callback=?',function(data){if(data.results.length>0){var col=$('#col-2');var colHtml=$(col).html();col.html(colHtml.replace('Take inspiration from the results, and use your imagination!','<a href="http://search.twitter.com/search?q=%23whyportwit">Just ask Twitter</a>:'));var ul=$('<ul />').appendTo(col);for(var i in data.results){var result=data.results[i];var li=$('<li />').appendTo(ul);$('<a />').attr('href','http://twitter.com/'+result.from_user+'/status/'+result.id).html(result.text.replace('#whyportwit','')).appendTo(li);}}});$('.col a').click(function(){window.open($(this).attr('href'));return false;});});$(window).resize(function(){sizeOverlay();posFlickrbox();});