
var Utilities=function(){this.consoleLog=function(){if(typeof(console)!="undefined"){switch(arguments.length)
{case 1:console.log(arguments[0]);break;case 2:console.log(arguments[0],arguments[1]);break;case 3:console.log(arguments[0],arguments[1],arguments[2]);break;default:console.log(arguments);}}}
this.consoleError=function(){if(typeof(console)!="undefined"){switch(arguments.length)
{case 1:console.error(arguments[0]);break;case 2:console.error(arguments[0],arguments[1]);break;case 3:console.error(arguments[0],arguments[1],arguments[2]);break;default:console.error(arguments);}}}}
Utilities=new Utilities();var CookieUtils=function(){var that=this;this.getCookie=function(name){var arg=name+'=';var alen=arg.length;var clen=document.cookie.length;var i=0;while(i<clen){var j=i+alen;if(document.cookie.substring(i,j)==arg){return getCookieVal(j);}
i=document.cookie.indexOf(' ',i)+1;if(i===0){break;}}
return null;}
this.setCookie=function(name,value){var argv=arguments;var argc=arguments.length;var expires=(argc>2)?argv[2]:null;var path=(argc>3)?argv[3]:null;var domain=(argc>4)?argv[4]:null;var secure=(argc>5)?argv[5]:false;var cookie_string=name+'='+escape(value)+
((expires===null)?'':('; expires='+expires.toGMTString()))+
((path===null)?'':('; path='+path))+
((domain===null)?'':('; domain='+domain))+
((secure===true)?'; secure':'');document.cookie=cookie_string;}
this.deleteCookie=function(name,path){var exp=new Date();var cval=that.getCookie(name);if(!path){path='';}
document.cookie=name+'='+cval+((path===null)?'':('; path='+path))+'; expires='+exp.toGMTString();}
function getCookieVal(offset){var endstr=document.cookie.indexOf(";",offset);if(endstr==-1){endstr=document.cookie.length;}
return unescape(document.cookie.substring(offset,endstr));}}
CookieUtils=new CookieUtils();var ErrorInfo=function(obj,extra_message){var initialize=function(){error=obj;extraMessage=extra_message;if(error){Utilities.consoleError("ErrorInfo: ",error,extraMessage);ErrorLogger.logError(error+((extraMessage)?" - "+extraMessage:""));}}
this.getError=function(){return error;}
this.getExtraMessage=function(){return extraMessage;}
this.noErrors=function(){return(error)?false:true;}
var error=null;var extraMessage=null;initialize();}
var ErrorLogger=function(){this.NumberOfErrors=0;this.LoggedErrors=[];this.logError=function(str){if(parent==window){var ignoredErrors=[];for(var i=0;i<ignoredErrors.length;i++){var errorToIgnore=ignoredErrors[i];if(str.match(errorToIgnore)){return;}}
if(this.NumberOfErrors<5){if($.inArray(str,this.LoggedErrors)==-1){this.NumberOfErrors++;this.LoggedErrors.push(str);var toolbarVersion=typeof(facetteToolbarVersion)!="undefined"?facetteToolbarVersion:"undefined";$.post("/errorlogger/logerror",{message:toolbarVersion+": "+str});}}}}}
ErrorLogger=new ErrorLogger();var ObservableBase=function(class_events,class_name){var that=this;this.fire=function(){fire.apply(this,arguments);}
this.subscribe=function(event,listeners){subscribe(event,listeners);}
var events=class_events;var className=class_name;var fire=function(){if(arguments.length==0){throw('ObservableBase.fire called with no arguments: '+className);}
else{var event=arguments[0];var eventListeners=events[event];var args=[];for(var i=1;i<arguments.length;i++){args.push(arguments[i]);}
Utilities.consoleLog(className+": "+event,args,"("+eventListeners.length+" listeners)");if(!eventListeners){throw('ObservableBase.fire called with invalid event: '+event);}
else{for(var i=0;i<eventListeners.length;i++){eventListeners[i].apply(this,args);}}}}
var subscribe=function(event,listener){if(!events[event]){throw('ObservableBase.subscribe called with invalid event: '+event);}
else{if(typeof(listener)=="function"){events[event].push(listener);}
else{throw('ObservableBase.subscribe called with invalid listener: '+listener);}}}}
function Querystring(){this.params={};var qs=location.search.substring(1,location.search.length);qs=qs.replace(/\+/g,' ');var args=qs.split('&');for(var i=0;i<args.length;i++){var pair=args[i].split('=');var name=unescape(pair[0]);var value=(pair.length==2)?unescape(pair[1]):name;this.params[name]=value;}}
Querystring.prototype.get=function(key,default_){var value=this.params[key];return(value!=null)?value:default_;}
Querystring.prototype.contains=function(key){var value=this.params[key];return(value!=null);}
Querystring=new Querystring();var InstallToolbarUpdate=function(){var installUrl=MEDIA_URL+"greasemonkey/FacettePlugin.xpi?v="+TOOLBAR_VERSION;var params={"Facette Delicious Connector":{URL:installUrl,IconURL:MEDIA_URL+"images/facette-32.png",toString:function(){return installUrl;}}};InstallTrigger.install(params);var toolbarVersion=typeof(facetteToolbarVersion)!="undefined"?facetteToolbarVersion:"undefined";var url="/update-clicked/"+TOOLBAR_VERSION+"/"+toolbarVersion;pageTracker._trackPageview(url);$.get(url);}
$(document).ready(function(){var updateToolbar=function(){if(window==window.parent){$.modal($('#toolbarUpdatePanel'),{close:false});var toolbarVersion=typeof(facetteToolbarVersion)!="undefined"?facetteToolbarVersion:"undefined";var url="/update-needed/"+TOOLBAR_VERSION+"/"+toolbarVersion;pageTracker._trackPageview(url);$.get(url);}}
var parseVersionString=function(str){if(typeof(str)!='string'){return false;}
var x=str.split('.');var maj=parseInt(x[0])||0;var min=parseInt(x[1])||0;var pat=parseInt(x[2])||0;return{major:maj,minor:min,patch:pat}}
setTimeout(function(){var toolbarUpdateIntervalId=setInterval(function(){if(typeof(GM_getValue)!="undefined"){clearInterval(toolbarUpdateIntervalId);if(typeof(facetteToolbarVersion)!="undefined"){var running_version=parseVersionString(facetteToolbarVersion);var latest_version=parseVersionString(TOOLBAR_VERSION);if(running_version.major<latest_version.major){updateToolbar();}else if(running_version.minor<latest_version.minor||running_version.patch<latest_version.patch){updateToolbar();}else{}}
else{updateToolbar();}}},200);},0);});var DeliciousLoginManager=function(){var that=this;var observableBase=new ObservableBase({'onLogin':[],'onLogout':[]},"DeliciousLoginManager");var fire=observableBase.fire;this.subscribe=observableBase.subscribe;this.getIsInitialized=function(){return isInitialized;}
this.getIsLoggedIn=function(){return isLoggedIn;}
this.getCurrentUser=function(){return getCurrentUser();}
this.logout=function(callback){logout(callback);}
this.tryLogin=function(callback){tryLogin(callback);}
this.xxAjax=function(parameters,callback){xxAjax(parameters,callback);}
var initialize=function(){$(document).ready(function(){setTimeout(function(){var name=CookieUtils.getCookie('username');if(name!=null&&name!=""){login(null,null,null,true,function(errorInfo){if(!errorInfo.noErrors()){logout();}});}
else{logout();}
isInitialized=true;},0);});}
var isLoggedIn=false;var username=null;var password=null;var credentials=null;var loginMode=null;var isInitialized=false;var getCurrentUser=function(){return(isLoggedIn)?username:null;}
var logout=function(callback){callback=callback?callback:function(){};username=null;password=null;credentials=null;loginMode=null;isLoggedIn=false;CookieUtils.deleteCookie('username','/');(typeof(GM_setValue)!="undefined")?GM_setValue('credentials',''):null;fire('onLogout');callback();}
var login=function(name,pass,mode,shouldUseStoredCredentials,callback){try{if(isLoggedIn){callback(new ErrorInfo("DeliciousLoginManager.login: User is already logged in."));return;}
var completeLogin=function(){if(shouldUseStoredCredentials){username=CookieUtils.getCookie('username');password=null;loginMode='saved';isLoggedIn=true;GM_getValue('credentials',function(creds){credentials=creds;fire('onLogin',username);callback(new ErrorInfo());});return;}
else{username=name;password=(mode=='saved')?null:pass;credentials=make_basic_auth(username,pass);loginMode=mode;isLoggedIn=true;checkPassword(function(isValid,error){if(isValid){if(mode=='saved'){var date=new Date();date.setDate(date.getDate()+30);CookieUtils.setCookie('username',username,date,'/');GM_setValue("credentials",credentials);}
fire('onLogin',username);callback(new ErrorInfo());}
else if(isValid==false){callback(new ErrorInfo(new Error("Invalid password for "+username)));$.modal($('#invalidPasswordPanel'));}
else{callback(new ErrorInfo(error));}});}}
var areGMFunctionsPresent=function(){return!(typeof(GM_setValue)=="undefined"||typeof(GM_getValue)=="undefined"||typeof(GM_xmlhttpRequest)=="undefined");}
var checkCount=0;var continueLogin=function(){if(!areGMFunctionsPresent()){Utilities.consoleLog("Facette plugin functions are not available. Retrying login after a delay.");if(checkCount<5){checkCount++;setTimeout(continueLogin,250);}
else{requestPluginInstallation();callback(new ErrorInfo("DeliciousLoginManager.login: Facette plugin functions are not available."));}}
else{completeLogin();}}
continueLogin();}
catch(ex){callback(new ErrorInfo(ex,"Error caught when logging in."));}}
var tryLogin=function(callback){var submitLoginForm=function(){var username=$('#prompt_username').attr('value');var password=$('#prompt_userpass').attr('value');var shouldRemember=$('#prompt_rememberMe').attr('checked')==true?true:false;if(username==""||password==""){callback(false,null);}
else{var mode=(shouldRemember)?"saved":"temporary";login(username,password,mode,false,function(errorInfo){if(errorInfo.noErrors()){callback(true,username);}
else{username=null;password=null;credentials=null;loginMode=null;isLoggedIn=false;callback(false,null);}});}
$.modal.close();}
$('#prompt_rememberMe').attr('checked',true);$('#prompt_username').attr('value','');$('#prompt_userpass').attr('value','');$.modal($('#login_prompt'),{containerCss:{width:"270px"},onClose:function(){callback(false,null);$.modal.close();},onShow:function(){$('#prompt_username').focus();$('#prompt_login_button').unbind('click').one('click',submitLoginForm);$("#prompt_userpass").keypress(function(e){if(e.which==13){submitLoginForm();}});}});}
var xxAjax=function(parameters,callback){try{if(!isLoggedIn){callback(null,new ErrorInfo("xxAjax may not be used when the user is not logged in."));}
var url=parameters.url;var method=parameters.method=="POST"?"POST":"GET";var data=parameters.data;var shouldUseCredentials=parameters.shouldUseCredentials?true:false;var header={};if(method=="POST"){header['Content-type']='application/x-www-form-urlencoded';}
if(shouldUseCredentials){if(url.match(/^https:/)==null){callback(null,new ErrorInfo("Credentials may not be sent without using https."));}
else{header['Authorization']=credentials;}}
var details={url:url,method:method,headers:header,data:data,onload:function(details){if(details.status!=200){Utilities.consoleLog("xxAjax error code: ",details.status);var errorInfo=new ErrorInfo("Request error code: "+details.status);errorInfo.status=details.status;callback(null,errorInfo);}
else{callback(details.responseText,new ErrorInfo());}},onerror:function(details){Utilities.consoleLog("onerror: ",details);var errorInfo=new ErrorInfo("Request error code: "+details.status);errorInfo.status=details.status;callback(null,errorInfo);}};GM_xmlhttpRequest(details);}
catch(ex){callback(null,new ErrorInfo(ex,"Error caught within xxAjax function"));}}
var checkPassword=function(callback){xxAjax({url:"https://api.del.icio.us/v1/posts/update",shouldUseCredentials:true},function(data,errorInfo){if(errorInfo.noErrors()){callback(true);}
else{if(errorInfo.status==401){callback(false);}
else{callback(null,new Error("Error checking password. Status: "+errorInfo.status));}}});}
var requestPluginInstallation=function(){$.modal($('#installRequestPanel'));var toolbarVersion=typeof(facetteToolbarVersion)!="undefined"?facetteToolbarVersion:"undefined";var serverToolbarVersion=typeof(TOOLBAR_VERSION)!="undefined"?TOOLBAR_VERSION:"undefined";var url="/installation-needed/"+serverToolbarVersion+"/"+toolbarVersion;$.get(url);try{pageTracker._trackPageview(url);}
catch(e){}}
var make_basic_auth=function(user,password){var tok=user+':'+password;var hash=Base64.encode(tok);return"Basic "+hash;}
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=Base64._utf8_encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}
output=output+
this._keyStr.charAt(enc1)+this._keyStr.charAt(enc2)+
this._keyStr.charAt(enc3)+this._keyStr.charAt(enc4);}
return output;},decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2);}
if(enc4!=64){output=output+String.fromCharCode(chr3);}}
output=Base64._utf8_decode(output);return output;},_utf8_encode:function(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}
else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}
else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}
return utftext;},_utf8_decode:function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++;}
else if((c>191)&&(c<224)){c2=utftext.charCodeAt(i+1);string+=String.fromCharCode(((c&31)<<6)|(c2&63));i+=2;}
else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string+=String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63));i+=3;}}
return string;}}
initialize();}