
var Browser=function(){var that=this;this.run=function(){exhibitUsername=USERNAME;shouldAutoFacet=true;isExhibitPanelShown=false;deliciousLoginManager=new DeliciousLoginManager();deliciousLoginManager.subscribe('onLogin',function(username){loggedInUser=username;resetBrowser();});deliciousLoginManager.subscribe('onLogout',function(){var previouslyLoggedInUser=loggedInUser;loggedInUser=null;if(isExhibitPanelShown==false||previouslyLoggedInUser==exhibitUsername){resetBrowser();}});}
var deliciousLoginManager;var exhibitUsername;var shouldAutoFacet;var loggedInUser;var isExhibitPanelShown;var deliciousTimestampCache={timestamp:null,date:null}
var MAX_NUMBER_OF_BOOKMARKS=1000;var resetBrowser=function(){if(deliciousLoginManager.getIsLoggedIn()&&deliciousLoginManager.getCurrentUser()==exhibitUsername){onLoggedIn(exhibitUsername);}
else{onLoggedOut();}}
var resetUI=function(optionalMessage){$('#main_body').empty().hide();$('#optional_message').remove();if(optionalMessage){setLoadingMessage(optionalMessage);}
isExhibitPanelShown=false;}
var setLoadingMessage=function(message){var optionalMessageDiv=$('#optional_message')[0];if(optionalMessageDiv){$(optionalMessageDiv).html(message);}
else{$('<div id="optional_message">'+message+'</div>').insertAfter('#main_body');}}
var showExhibitPanel=function(){$('#optional_message').remove();$('#main_body').show();$('#main_body .exhibitPanel').show();isExhibitPanelShown=true;}
var onLoggedIn=function(username){$('#login_message').html('Logged in as '+username+' &#8226 ');$('#logout_button').html('Logout').show().unbind('click').click(function(){deliciousLoginManager.logout(function(){});clearCache(function(){});});resetUI("Loading...");loadExhibit("api");}
var onLoggedOut=function(){$('#logout_button').hide();$('#login_message').html('<a href="javascript:{}">Login</a> to see more items');$('#login_message a').click(function(){deliciousLoginManager.logout();deliciousLoginManager.tryLogin(function(){});setTimeout(function(){$('#prompt_username').attr('value',exhibitUsername);$('#prompt_username').attr('readonly','readonly');$('#prompt_username').css('color','#666666');$('#prompt_userpass').focus();},25);});resetUI("Loading...");loadExhibit("json");}
var loadExhibit=function(dataSourceType){var parameters={dataSourceType:dataSourceType,shouldAutoFacet:shouldAutoFacet};var handleGetDataError=function(error){var resetMessage=null;if(error.type=="Null Timestamp"){resetMessage="Oops! Delicious had a hiccup. Please try refreshing this page.";}
else if(error.type=="Empty Delicious Cache"){clearCache(function(){});resetMessage="No bookmarks to display.";}
else if(error.type=="Invalid Cache"){clearCache(function(){});resetMessage="Invalid cache. Please try refreshing this page.";}
else{clearCache(function(){});resetMessage="Error loading data.";}
resetUI(resetMessage);}
getExhibitData(parameters,function(data,error){if(error){ErrorLogger.logError(error.toString());Utilities.consoleError('loadExhibit: ',error);if(error.type=="Invalid Password"){alert(error.message);deliciousLoginManager.logout();}
else{handleGetDataError(error);}}
else{renderExhibitFromData(data,function(error){if(error){Utilities.consoleError('loadExhibit: ',error);handleGetDataError(error);}
else{$('#autofacet-option-checkbox')[0].checked=shouldAutoFacet?"checked":"";$('#autofacet-option-checkbox').click(function(){shouldAutoFacet=!shouldAutoFacet;resetBrowser();});}});}});}
var getExhibitData=function(parameters,callback){var dataSourceType=parameters.dataSourceType;var shouldAutoFacet=parameters.shouldAutoFacet;if(dataSourceType=="api"){checkPassword(function(isCorrectPassword,errorInfo){if(isCorrectPassword==false){var error=new Error('Error requesting bookmarks from "'+exhibitUsername+'" - Incorrect username/password combination');error.type="Invalid Password";callback(null,error);}
else if(!isCorrectPassword){error=new Error('Error requesting bookmarks from "'+exhibitUsername+'" - Error: '+JSON.stringify(errorInfo));callback(null,error);}
else{getDeliciousData_api(shouldAutoFacet,function(data,error){callback(data,error);});}});}
else if(dataSourceType=="json"){getDeliciousData_json(shouldAutoFacet,function(data,error){callback(data,error);});}
else{callback(null,new Error("dataSourceType is not recognized: "+dataSourceType));}}
var renderExhibitFromData=function(data,callback){try{$('.exhibitPanel').clone().appendTo("#main_body");var templateElements=$('#main_body div[template_exrole]');for(var i=0;i<templateElements.length;i++){var template=templateElements[i];var role=$(template).attr('template_exrole');$(template).removeAttr('template_exrole');$(template).attr('ex:role',role);}
setupExhibit(data);showExhibitPanel();callback();}
catch(error){callback(error);}}
function checkPassword(callback){deliciousLoginManager.xxAjax({url:"https://api.del.icio.us/v1/posts/update",shouldUseCredentials:true},function(data,errorInfo){if(errorInfo.noErrors()){var newTimestamp=$($(data)[1]).attr('time');if(newTimestamp){cacheDeliciousTimestamp(newTimestamp);}
callback(true);}
else{if(errorInfo.status==401){callback(false,new ErrorInfo());}
else{callback(null,errorInfo);}}});}
var getDeliciousData_json=function(shouldAutoFacet,callback){$.getJSON('http://feeds.delicious.com/feeds/json/'+exhibitUsername+'?raw&count=100&callback=?',null,function(jsonData){try{var exhibitData=getExhibitDataFromDeliciousJsonObject(jsonData);callback(exhibitData);}
catch(error){callback(null,error);}});}
var getDeliciousData_api=function(shouldAutoFacet,callback){getIsCacheAvailable(function(isCacheAvailable,error){if(error){callback(null,error);}
else if(isCacheAvailable){getIsCacheStale(function(isCacheStale,error){if(error){callback(null,error);}
else if(!isCacheStale){getExhibitDataFromCache(function(exhibitData,error){callback(exhibitData,error);});}
else{refreshCacheUsingDeliciousAPI(function(error){if(error){callback(null,error);}
else{getExhibitDataFromCache(function(exhibitData,error){callback(exhibitData,error);});}});}});}
else{createCacheUsingDeliciousAPI(function(error){if(error){callback(null,error);}
else{getExhibitDataFromCache(function(exhibitData,error){callback(exhibitData,error);});}});}});}
var createCacheUsingDeliciousAPI=function(callback){setLoadingMessage("Downloading bookmarks from Delicious...");getDeliciousXML(function(deliciousXML,error){if(error){callback(error);}
else{getDeliciousUpdateTimestamp(function(updateTimestamp,error){if(error){callback(error);}
else{var deliciousJsonObject=getDeliciousJsonObjectFromDeliciousXML(deliciousXML);cacheDeliciousJsonObject(deliciousJsonObject,updateTimestamp,function(error){callback(error);});}});}});}
var refreshCacheUsingDeliciousAPI=function(callback){setLoadingMessage('Syncing bookmarks with Delicious...');getDeliciousJsonHashes(function(deliciousJsonHashes,error){if(error){callback(error);}
else{getDeliciousJsonObjectFromCache(function(deliciousJsonObject,error){if(error){callback(error);}
else{try{var storedHashes={};for(var i=0;i<deliciousJsonObject.length;i++){var post=deliciousJsonObject[i];storedHashes[post.hash]=post;}
var retrievedHashes={};var hashesThatNeedUpdating=[];var mapOfHashesToUpdate={};for(var i=0;i<deliciousJsonHashes.length;i++){var hashInfo=deliciousJsonHashes[i];retrievedHashes[hashInfo.hash]=hashInfo;mapOfHashesToUpdate[hashInfo.hash]=true;if(!storedHashes[hashInfo.hash]||storedHashes[hashInfo.hash].meta!=hashInfo.meta){hashesThatNeedUpdating.push(hashInfo.hash);}}
var hashesThatNeedDeleting=[];for(var i=0;i<deliciousJsonObject.length;i++){var post=deliciousJsonObject[i];if(!retrievedHashes[post.hash]){hashesThatNeedDeleting.push(post.hash);}}
for(var i=0;i<hashesThatNeedDeleting.length;i++){delete storedHashes[hashesThatNeedDeleting[i]];}
if(hashesThatNeedUpdating.length>100){createCacheUsingDeliciousAPI(callback);}
else{getDeliciousUpdateTimestamp(function(timestamp,error){if(error){callback(error);}
else{fetchUpdatedDeliciousData(hashesThatNeedUpdating,function(updatedDeliciousData,error){try{for(var i=0;i<updatedDeliciousData.length;i++){var updatedInfo=updatedDeliciousData[i];storedHashes[updatedInfo.hash]=updatedInfo;}
var deliciousJsonObject=[];for(var i=0;i<deliciousJsonHashes.length;i++){var hashInfo=deliciousJsonHashes[i];var post=storedHashes[hashInfo.hash];if(!post){callback(new Error("update cache error: could not find updated info for: "+hashInfo.hash));return;}
else{deliciousJsonObject.push(post);}}
cacheDeliciousJsonObject(deliciousJsonObject,timestamp,function(error){if(error){callback(error)}
else{callback();}});}
catch(error){callback(error);}});}});}}
catch(error){callback(error);}}});}});}
var cacheDeliciousJsonObject=function(deliciousJsonObject,updateTimestamp,callback){var serializedDeliciousJsonObject=JSON.stringify(deliciousJsonObject);GM_setValue("serializedDeliciousJsonObject",escape(serializedDeliciousJsonObject));GM_setValue("updateTimestamp",updateTimestamp);GM_setValue("usernameForDeliciousCache",loggedInUser);setTimeout(function(){callback();},1);}
var getDeliciousJsonObjectFromCache=function(callback){GM_getValue("serializedDeliciousJsonObject",function(data){try{var deliciousJsonObject=JSON.parse(unescape(data));if(typeof(deliciousJsonObject)=="string"||!deliciousJsonObject.length){var error=new Error("Invalid delicious cache: "+data.substr(0,25));error.type="Invalid Cache";callback(null,error)}
else if(deliciousJsonObject.length==0){var error=new Error("deliciousJsonObject length == 0");error.type="Empty Delicious Cache";callback(null,error);}
else{callback(deliciousJsonObject);}}
catch(error){clearCache(function(){callback(null,error);});}});}
var getExhibitDataFromCache=function(callback){getDeliciousJsonObjectFromCache(function(deliciousJsonObject,error){if(error){callback(null,error);}
else{try{var exhibitData=getExhibitDataFromDeliciousJsonObject(deliciousJsonObject);callback(exhibitData);}
catch(error){clearCache(function(){callback(null,error);});}}});}
var clearCache=function(callback){callback=callback?callback:function(){};if(typeof(GM_setValue)!="undefined"){GM_setValue("usernameForDeliciousCache",null);GM_setValue("updateTimestamp",null);GM_setValue("serializedDeliciousJsonObject",null);}
setTimeout(function(){callback();},1);}
window.clearCache=clearCache;var getCachedUpdateTimestamp=function(callback){try{GM_getValue("updateTimestamp",function(timestamp){callback(timestamp);});}
catch(error){callback(null,error);}}
var getDeliciousUpdateTimestamp=function(callback){var deliciousTimestamp=getCachedDeliciousTimestamp();if(deliciousTimestamp){callback(deliciousTimestamp);}
else{deliciousLoginManager.xxAjax({url:"https://api.del.icio.us/v1/posts/update",shouldUseCredentials:true},function(data,errorInfo){if(errorInfo.noErrors()){var newTimestamp=$($(data)[1]).attr('time');if(newTimestamp){cacheDeliciousTimestamp(newTimestamp);callback(newTimestamp);}
else{var error=new Error("delicious update timestamp is null.");error.type="Null Timestamp";callback(null,error);}}
else{callback(null,new Error("xxAjax error when getting delicious update timestamp."))}});}}
var getDeliciousJsonHashes=function(callback){deliciousLoginManager.xxAjax({url:"https://api.del.icio.us/v1/posts/all?hashes",shouldUseCredentials:true},function(data,errorInfo){if(errorInfo.noErrors()){try{var posts=$("post",data);var deliciousJsonHashes=[];for(var i=0;i<posts.length&&i<MAX_NUMBER_OF_BOOKMARKS;i++){var post=posts[i];var postObject={};postObject.meta=$(post).attr('meta');postObject.hash=$(post).attr('url');deliciousJsonHashes.push(postObject);}
callback(deliciousJsonHashes);}
catch(error){callback(null,error);}}
else{callback(null,new Error("xxAjax error when getting delicious hashes."))}});}
var cacheDeliciousTimestamp=function(timestamp){deliciousTimestampCache.timestamp=timestamp;deliciousTimestampCache.date=new Date();}
var getCachedDeliciousTimestamp=function(){if(((new Date())-deliciousTimestampCache.date)<6000){return deliciousTimestampCache.timestamp;}
else{return null;}}
var getIsCacheAvailable=function(callback){try{GM_getValue("usernameForDeliciousCache",function(username){if(username==loggedInUser){getCachedUpdateTimestamp(function(timestamp,error){callback((timestamp!=null&&timestamp!=''),error);});}
else{callback(false);}});}
catch(error){callback(false,error);}}
var getIsCacheStale=function(callback){getDeliciousUpdateTimestamp(function(newTimestamp,error){if(error){callback(false,error);}
else{getCachedUpdateTimestamp(function(timestamp,error){callback((timestamp==null||timestamp!=newTimestamp),error);});}});};var getDeliciousXML=function(callback){deliciousLoginManager.xxAjax({url:"https://api.del.icio.us/v1/posts/all?meta=yes&results="+MAX_NUMBER_OF_BOOKMARKS,shouldUseCredentials:true},function(data,errorInfo){if(errorInfo.noErrors()){callback(data);}
else{callback(null,new Error("xxAjax error when getting all user's delicious xml."))}});}
var fetchUpdatedDeliciousData=function(hashesToUpdate,callback){if(hashesToUpdate.length==0){callback([]);}
else{var data='meta=yes&hashes='+hashesToUpdate.join("+");deliciousLoginManager.xxAjax({url:'https://api.del.icio.us/v1/posts/get',data:data,shouldUseCredentials:true,method:"POST"},function(data,errorInfo){if(errorInfo.noErrors()){try{var updatedDeliciousData=getDeliciousJsonObjectFromDeliciousXML(data);callback(updatedDeliciousData);}
catch(error){callback(null,error);}}
else{callback(null,new Error("xxAjax error when getting all user's delicious xml."))}});}}
var getDeliciousJsonObjectFromDeliciousXML=function(DeliciousXML){var xmlDoc=(new DOMParser()).parseFromString(DeliciousXML,"text/xml");var posts=$("post",xmlDoc);var deliciousJsonObject=[];for(var i=0;i<posts.length;i++){var post=posts[i];var postObject={};postObject.u=$(post).attr('href');postObject.d=$(post).attr('description');var tagString=$(post).attr('tag');postObject.t=tagString?tagString.split(' '):[];postObject.dt=$(post).attr('time');postObject.meta=$(post).attr('meta');postObject.extended=$(post).attr('extended');postObject.hash=$(post).attr('hash');deliciousJsonObject.push(postObject);}
return deliciousJsonObject;}
var getExhibitDataFromDeliciousJsonObject=function(jsonData){var count=jsonData.length;var exhibitData=[];for(var index=0;index<jsonData.length;index++){var jsonObj=jsonData[index];var post={};post.label=jsonObj.u;post.type='bookmark';post.add_date=count-index;post.title=jsonObj.d;post.url=jsonObj.u;post.description=jsonObj.n;post.extended=(jsonObj.extended!=null&&jsonObj.extended!="")?jsonObj.extended:null;var delicious_tags=jsonObj.t;delicious_tags=(delicious_tags)?delicious_tags:[];post.delicious_tags=delicious_tags;var all_tags=$.map(delicious_tags,function(tag){return parseFacetedTag(tag).tag;});post.all_tags=all_tags;var unfaceted_tags=[];var facets=[];for(var i=0;i<delicious_tags.length;i++){var tag=delicious_tags[i];var facet=parseFacetedTag(tag).facet;if(shouldAutoFacet&&!facet){facet=validateFacetName(findRecommendedFacet(tag));}
if(!facet){unfaceted_tags.push(tag);}
else if($.inArray('_'+facet,facets)==-1){facets.push('_'+facet);}}
post.unfaceted_tags=unfaceted_tags;if(unfaceted_tags.length!=0){facets.push('unfaceted_tags');}
if(all_tags.length!=0){facets.push('all_tags');}
post.facets=facets;for(var i=0;i<facets.length;i++){var facet=facets[i];if(facet.substr(0,1)=='_'){post[facet]=[];}}
for(var i=0;i<delicious_tags.length;i++){var tag=delicious_tags[i];var tokens=parseFacetedTag(tag);if(shouldAutoFacet&&tokens.facet==null){tokens.facet=validateFacetName(findRecommendedFacet(tokens.tag));}
if(tokens.facet!=null){tag=validateTagName(tokens.tag,'display');if($.inArray(tokens.tag,post['_'+tokens.facet])==-1){post['_'+tokens.facet].push(tag);}}}
exhibitData.push(post);}
return exhibitData;}
var findRecommendedFacet=function(tag){var facetsForThisTag=tagmap_data_for_common_tags[tag.toLowerCase()];if(facetsForThisTag){return facetsForThisTag[0];}
else{return null;}}
var setupExhibit=function(exhibitData){var facets={};var expressions={};for(var i=0;i<exhibitData.length;i++){var post=exhibitData[i];for(var x=0;x<post.facets.length;x++){var facet=post.facets[x];expressions[facet]=0;if(facet.substr(0,1)=='_'){facet=facet.substr(1);if(facets[facet]!=null){facets[facet]=facets[facet]+1;}
else{facets[facet]=1;}}}}
ExhibitFactory.expressions=expressions;var exhibitItems=exhibitData;var exhibitTypes={"bookmark":{pluralLabel:"bookmarks"}};var exhibitProperties={};exhibitProperties.add_date={label:"add date",valueType:"number"};exhibitProperties.title={label:"title",valueType:"text"};exhibitProperties.url={label:"url",valueType:"text"};exhibitProperties.type_of_object={label:"type of object"};for(var facet in facets){exhibitProperties['_'+facet]={label:validateFacetName(facet,'display').toLowerCase()};}
exhibitProperties.delicious_tags={label:"delicious tags"};exhibitProperties.unfaceted_tags={label:"unfaceted tags"};exhibitProperties.all_tags={label:"all tags"};var exhibitArgs={};exhibitArgs.types=exhibitTypes;exhibitArgs.properties=exhibitProperties;exhibitArgs.items=exhibitItems;ExhibitFactory.resetFacetObjects();window.database=Exhibit.Database.create();window.database.loadData(exhibitArgs,'/');window.exhibit=Exhibit.create();window.exhibit.configureFromDOM();var sortedFacets=[];for(var facet in facets){sortedFacets.push({facet:facet,count:facets[facet]});}
sortedFacets=sortedFacets.sort(function(a,b){return b.count-a.count;});var facetProperties={};facetProperties.sortMode="count";facetProperties.expression=".facets";facetProperties.facetLabel="Facets";facetProperties.showMissing=false;var facetObject=ExhibitFactory.createOpenedFacet('facets',facetProperties,$('#facet-column','#main_body')[0],null);$('#'+facetObject.facetID).hide();var totalNumberOfBookmarks=exhibitData.length;var facetPane=$('#facet-pane','#main_body')[0];var prevElement=null;for(var i=0;i<sortedFacets.length;i++){var facetName=sortedFacets[i].facet;if(i<3){var facetProperties={};facetProperties.sortMode="count";facetProperties.expression="._"+facetName;facetProperties.facetLabel=validateFacetName(facetName,'display');facetProperties.showMissing=false;var facetObject=ExhibitFactory.createOpenedFacet('_'+facetName,facetProperties,facetPane,prevElement);prevElement=$('#'+facetObject.facetID)[0];}
else if(i<8){var facetProperties={};facetProperties.sortMode="count";facetProperties.expression="._"+facetName;facetProperties.facetLabel=validateFacetName(facetName,'display');facetProperties.showMissing=false;var facetObject=ExhibitFactory.createCollapsedFacet('_'+facetName,facetProperties,facetPane,prevElement);prevElement=$('#'+facetObject.facetID)[0];}}
var facetProperties={};facetProperties.sortMode="count";facetProperties.expression=".all_tags";facetProperties.facetLabel="Tags";facetProperties.height="635px";facetProperties.showMissing=false;facetProperties.scroll=false;var facetObject=ExhibitFactory.createOpenedFacet('tags',facetProperties,$('#tag-facet-div','#main_body')[0],null,'tagsFacet');prevElement=$('#'+facetObject.facetID)[0];var moreFacetsButton=$('#more-facets-button','#main_body')[0];$(moreFacetsButton).click(function(){var moreFacetsDropDownMenu=$('<div id="more_facets_dropdown_menu"></div>')[0];var sortedExpressions=[];for(var expression in ExhibitFactory.expressions){sortedExpressions.push({expression:expression,count:ExhibitFactory.expressions[expression]});}
sortedExpressions=sortedExpressions.sort(function(a,b){return a.count-b.count;});function openFacet(facetID){$(document.body).trigger('mousedown');var lastOpenedFacet=$('#facet-column .exhibit-facet','#main_body');lastOpenedFacet=lastOpenedFacet[lastOpenedFacet.length-1];var facetProperties={sortMode:"count",expression:"."+facetID,facetLabel:validateFacetName(facetID.substr(1),'display'),showMissing:false}
ExhibitFactory.createOpenedFacet(facetID,facetProperties,$('#facet-column','#main_body')[0],lastOpenedFacet);}
for(var i=0;i<sortedExpressions.length;i++){var expression=sortedExpressions[i].expression;if(expression.substr(0,1)=='_'){var facetID=expression;var percent=ExhibitFactory.expressions[expression];if(percent>0&&$('#'+facetID)[0]==null){var facetName=validateFacetName(expression.substr(1),'display');var facetOption=$('<div class="facet_option">'+facetName+'</div>')[0];var precentRelevance=$('<span class="percent_relevance">'+percent+'</span>')[0];$(precentRelevance).prependTo(facetOption);$(facetOption).appendTo(moreFacetsDropDownMenu);$(facetOption).click((function(facetID){return function(){openFacet(facetID);}})(facetID));}}}
$(moreFacetsDropDownMenu).css('visibility','hidden');$(moreFacetsDropDownMenu).prependTo(moreFacetsButton);$(moreFacetsDropDownMenu).css('left',''+(moreFacetsButton.offsetWidth-2)+'px');$(moreFacetsDropDownMenu).css('top','-'+(moreFacetsDropDownMenu.offsetHeight-32)+'px');$(moreFacetsDropDownMenu).dropShadow({left:0,top:0,blur:1,opacity:0.5});$('.dropShadow',moreFacetsButton).css('visibility','hidden');setTimeout(function(){$(moreFacetsDropDownMenu).css('visibility','visible');$('.dropShadow',moreFacetsButton).css('visibility','visible');},1);$(moreFacetsDropDownMenu).bind('mousedown',function(e){return false;});$(document.body).one('mousedown',function(e){$(moreFacetsDropDownMenu).removeShadow();if(moreFacetsDropDownMenu.parentNode){moreFacetsDropDownMenu.parentNode.removeChild(moreFacetsDropDownMenu);}});});}}
function launch_tagger(label){var url=database.getObject(label,"url");var title=database.getObject(label,"title");open('/tagger.html?title='+encodeURIComponent(title)+'&url='+encodeURIComponent(url),'facettetagger','location=yes,links=no,scrollbars=no,toolbar=no,width=685,height=541,resizable=yes');}
var ExhibitFactory={facetObjects:{},expressions:{},events:{"onFacetOpened":[],"onFacetSorted":[]}};ExhibitFactory.addListener=function(event,listener){ExhibitFactory.events[event].push(listener);}
ExhibitFactory.fireEvent=function(event,arg1,arg2){var listeners=ExhibitFactory.events[event];for(var i=0;i<listeners.length;i++){listeners[i](arg1,arg2);}}
ExhibitFactory.createOpenedFacet=function(facetID,facetProperties,container,prevElement,tagFacet){ExhibitFactory.facetObjects[facetID]={facetID:facetID,status:'opened',facetProperties:facetProperties};var facetDiv=$('<div id="'+facetID+'"/>')[0];(prevElement==null)?$(facetDiv).prependTo(container):$(facetDiv).insertAfter(prevElement);var facet=Exhibit.UI.createFacet(facetProperties,facetDiv,window.exhibit.getUIContext());window.exhibit.setComponent(facetID,facet);var facetHeader=$('#'+facetID+' .exhibit-facet-header')[0];facetHeader=(facetHeader)?facetHeader:$('#'+facetID+' .exhibit-flowingFacet-header')[0];try{ExhibitFactory._modifyFacetHeader(facetHeader,facetID);}
catch(e){if(typeof(console)!="undefined"){console.log(e);}}
ExhibitFactory.updatePercentRelevance(facetID);ExhibitFactory.fireEvent("onFacetOpened",facetDiv);return ExhibitFactory.facetObjects[facetID];}
ExhibitFactory.createCollapsedFacet=function(facetID,facetProperties,container,prevElement){ExhibitFactory.facetObjects[facetID]={facetID:facetID,status:'collapsed',facetProperties:facetProperties};var facetDiv=$('<div id="'+facetID+'" class="exhibit-facet-header collapsed-facet">'
+facetProperties.facetLabel+'</div>')[0];(prevElement==null)?$(facetDiv).prependTo(container):$(facetDiv).insertAfter(prevElement);var facetHeader=facetDiv;ExhibitFactory._modifyFacetHeader(facetHeader,facetID);ExhibitFactory.updatePercentRelevance(facetID);return ExhibitFactory.facetObjects[facetID];}
ExhibitFactory.removeOpenedFacet=function(facetID){window.exhibit.disposeComponent(facetID);$('#'+facetID).remove();ExhibitFactory.facetObjects[facetID]=null;}
ExhibitFactory.removeCollapsedFacet=function(facetID){$('#'+facetID).remove();ExhibitFactory.facetObjects[facetID]=null;}
ExhibitFactory.changeToOpenedFacet=function(facetID){var parentNode=$('#'+facetID)[0].parentNode;var prevElement=$('#'+facetID).prev()[0];var facetProperties=ExhibitFactory.getFacetObject(facetID).facetProperties;ExhibitFactory.removeCollapsedFacet(facetID);ExhibitFactory.createOpenedFacet(facetID,facetProperties,parentNode,prevElement);}
ExhibitFactory.changeToCollapsedFacet=function(facetID){var parentNode=$('#'+facetID)[0].parentNode;var prevElement=$('#'+facetID).prev()[0];var facetProperties=ExhibitFactory.getFacetObject(facetID).facetProperties;ExhibitFactory.removeOpenedFacet(facetID);ExhibitFactory.createCollapsedFacet(facetID,facetProperties,parentNode,prevElement);}
ExhibitFactory.updatePercentRelevance=function(facetID,percentage){var percentRelevanceElement=$('#'+facetID+' .percent_relevance')[0];var facetObject=ExhibitFactory.getFacetObject(facetID);if(percentRelevanceElement){if(percentage!=null){$(percentRelevanceElement).html(''+percentage);}
else{if(facetID=='tags'){var expression=facetObject.facetProperties.expression.substr(1);var percentage=ExhibitFactory.expressions[expression];}
else{var percentage=ExhibitFactory.expressions[facetID];}
$(percentRelevanceElement).html(''+percentage);}}}
ExhibitFactory.setFacetSortMode=function(facetID){}
ExhibitFactory.getFacetObject=function(facetID){return ExhibitFactory.facetObjects[facetID];}
ExhibitFactory.resetFacetObjects=function(){ExhibitFactory.facetObjects={};}
ExhibitFactory._modifyFacetHeader=function(oldFacetHeader,facetID){var newHeader=$('<table><tbody><tr><td class="column1"><span class="percent_relevance">100</span>'+
$(oldFacetHeader).html()+'</td><td class="column2"><a class="menu_anchor"></a>'+'<img src="'+MEDIA_URL+'exhibit/images/down_arrow_gray.png"/></td></tr></tbody></table>')[0];$(newHeader).attr('class',$(oldFacetHeader).attr('class'));$(newHeader).attr('id',$(oldFacetHeader).attr('id'));$(oldFacetHeader).replaceWith(newHeader);if(ExhibitFactory.getFacetObject(facetID).status=="opened"){$('.column1',newHeader).click(function(){ExhibitFactory.changeToCollapsedFacet(facetID)});}
else{$('.column1',newHeader).click(function(){ExhibitFactory.changeToOpenedFacet(facetID)});}
$('.column2',newHeader).click(function(){ExhibitFactory._showFacetMenu(facetID)});}
ExhibitFactory._showFacetMenu=function(facetID){var menu_anchor=$('#'+facetID+' .menu_anchor')[0];var menuDiv=$('<div class="facet_dropdown_menu"></div>')[0];$(menuDiv).click(function(e){if(!e)var e=window.event;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();});var sortButton=$('<div class="sort_button">Sort by: </div>')[0];var alphaButton=$('<a class="alpha_button" href="javascript:{}">alpha</a>')[0];$(alphaButton).appendTo(sortButton);var countButton=$('<a class="count_button" href="javascript:{}">count</a>')[0];$(countButton).appendTo(sortButton);$(sortButton).appendTo(menuDiv);var sortFunction=function(sortMode){ExhibitFactory.getFacetObject(facetID).facetProperties.sortMode=sortMode;if(ExhibitFactory.getFacetObject(facetID).status=="collapsed"){ExhibitFactory.changeToOpenedFacet(facetID);}
else{var facet=window.exhibit.getComponent(facetID);facet._settings.sortMode=sortMode;facet.update(facet._uiContext.getCollection().getRestrictedItems());ExhibitFactory.fireEvent("onFacetSorted",$('#'+facetID)[0]);}
$(document.body).trigger('mousedown');}
if(ExhibitFactory.getFacetObject(facetID).facetProperties.sortMode=="alpha"){$(alphaButton).addClass('disabled');$(countButton).click(function(){sortFunction('count');});}
else{$(countButton).addClass('disabled');$(alphaButton).click(function(){sortFunction('alpha');});}
if(ExhibitFactory.getFacetObject(facetID).status=="opened"){var collapseFacetButton=$('<div class="collapse_button">Collapse facet</div>')[0];$(collapseFacetButton).appendTo(menuDiv);$(collapseFacetButton).click(function(){ExhibitFactory.changeToCollapsedFacet(facetID);$(document.body).trigger('mousedown');});}
else{var openFacetButton=$('<div class="open_button">Open facet</div>')[0];$(openFacetButton).appendTo(menuDiv);$(openFacetButton).click(function(){ExhibitFactory.changeToOpenedFacet(facetID);$(document.body).trigger('mousedown');});}
var closeFacetButton=$('<div class="close_button">Remove facet</div>')[0];$(closeFacetButton).appendTo(menuDiv);$(closeFacetButton).click(function(){if(ExhibitFactory.getFacetObject(facetID).status=="opened"){ExhibitFactory.removeOpenedFacet(facetID);}
else{ExhibitFactory.removeCollapsedFacet(facetID);}
$(document.body).trigger('mousedown');});$(menuDiv).appendTo(menu_anchor);$(menuDiv).dropShadow({left:0,top:0,blur:1,opacity:0.5});$(menuDiv).css('visibility','hidden');$('.dropShadow',menu_anchor).css('visibility','hidden');setTimeout(function(){$(menuDiv).css('visibility','visible');$('.dropShadow',menu_anchor).css('visibility','visible');},1);$(menuDiv).bind('mousedown',function(e){return false;});$(document.body).one('mousedown',function(e){$(menuDiv).removeShadow();menuDiv.parentNode?menuDiv.parentNode.removeChild(menuDiv):{};});}
Exhibit.ListFacet.prototype.original_update=Exhibit.ListFacet.prototype.update;Exhibit.ListFacet.prototype.update=function(items){this.original_update(items);var numberOfRestrictedItems=exhibit.getDefaultCollection().countRestrictedItems();var property=this._expression.getPath()._segments[0].property;if(property=='facets'){for(var expression in ExhibitFactory.expressions){ExhibitFactory.expressions[expression]=0;}
var computedFacet=this._computeFacet(items);for(var i=0;i<computedFacet.length;i++){var item=computedFacet[i];var value=item.value;var count=item.count;var percentage=count;var expression=value;ExhibitFactory.expressions[expression]=percentage;}
for(var expression in ExhibitFactory.expressions){var percentage=ExhibitFactory.expressions[expression];if(expression[0]=='_'){ExhibitFactory.updatePercentRelevance(expression,percentage);}
else{ExhibitFactory.updatePercentRelevance('tags');}}}}
function validateTagName(name_string,display)
{var tagName=name_string.replace(/(^\s+|\s+$)/g,'');if(!display){tagName=tagName.replace(/</g,'');tagName=tagName.replace(/>/g,'');tagName=tagName.replace(/\s/g,'_');}
else{tagName=tagName.replace(/\[.+\]$/,'');tagName=tagName.replace(/_/g,' ');}
return tagName;}
function validateFacetName(name_string,display)
{if(name_string==null){return null;}
var facetName=name_string.replace(/(^\s+|\s+$)/g,'');facetName=facetName.replace(/(\(|\))/g,'');if(!display)
{facetName=facetName.replace(/\s/g,'_');facetName=facetName.toLowerCase();}
else
{facetName=facetName.replace(/_/g,' ');var WordTokens=facetName.split(' ');for(var i=0;i<WordTokens.length;i++){WordTokens[i]=WordTokens[i].charAt(0).toUpperCase()+WordTokens[i].substr(1);}
for(var i=1;i<WordTokens.length-1;i++){var lowercase_word=WordTokens[i].toLowerCase();var found=false;if(map_of_words_to_be_lowercase[lowercase_word]){found=true;}
if(found){WordTokens[i]=lowercase_word;}}
facetName=WordTokens.join(' ');}
return facetName;}
var map_of_words_to_be_lowercase=(function(){var array_of_words_to_be_lowercase=['the','a','at','but','by','down','for','from','in','into','near','of','on','onto','over','till','to','up','upon','with','about','above','across','after','against','along','among','around','before','behind','below','beneath','beside','between','beyond','despite','down','during','except','inside','outside','over','past','since','through','throughout','toward','under','underneath','until','within','without','and','but','or','nor','for','so','yet','but','for'];var map_obj={};for(var i=0;i<array_of_words_to_be_lowercase.length;i++){if(array_of_words_to_be_lowercase[i]){var word=array_of_words_to_be_lowercase[i].toLowerCase();map_obj[word]=true;}};return map_obj;})();function listTagDetails(name){var detailsString=name.match(/\[.+\]$/);if(detailsString){detailsString=detailsString[0].substring(1,detailsString[0].length-1);}
if(detailsString!=null&&detailsString.length>0){var tokens=detailsString.split(/;/);return tokens;}
else{return null;}}
function parseFacetedTag(name){var facet=name.match(/\([^\[\]]+\)$/);var tag='';if(facet){facet=facet[0].substring(1,facet[0].length-1);tag=name.substring(0,name.length-facet.length-2);}
else{facet=null;tag=name;}
return{facet:validateFacetName(facet),tag:validateTagName(tag)};}
jQuery.queryParams=(function(){var s=location.search;var r={};if(s&&s.length>1){var q=s.substring(s.indexOf('?')+1);q=q.replace(/\&$/,'');jQuery.each(q.split('&'),function(){var splitted=this.split('=');var key=splitted[0];var val=(typeof(splitted[1])!=undefined)?splitted[1]:null;if(val){if(/^[0-9.]+$/.test(val))val=parseFloat(val);if(typeof val=='number'||val.length>0)r[key]=val;}
else{r[key]=null;}});return r;}})();