decembre

GM - Flickr Functional Suite - NEW (by C. Tilford)

Jan 11th, 2024
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name          Flickr Functional Suite - NEW
  3. // @namespace     http://www.tilford.net/
  4. // @description   Adds some additional functionality to page
  5. // @include       http://*.flickr.com/*
  6. // @include       http://flickr.com/*
  7. // @include       https://*.flickr.com/*
  8. // @include       https://flickr.com/*
  9. // @grant       GM_getValue
  10. // @grant       GM_setValue
  11. // @grant       GM_log
  12. // @grant       GM_xmlhttpRequest
  13. //
  14. // ==/UserScript==
  15.  
  16. /*
  17.  
  18. This is a Grease Monkey script. It *requires* FireFox and the Grease
  19. Monkey extension to work:
  20.  
  21. http://www.mozilla.com/firefox/
  22. http://greasemonkey.mozdev.org/
  23.  
  24. Following the instructions on the above web pages
  25. 1. Install FireFox
  26. 2. Install GreaseMonkey
  27. 3. Install this script
  28.  
  29. Author: Charles Tilford  http://www.flickr.com/photos/charlestilford/
  30.   (I am not hosting tilford.net yet)
  31.  
  32. This code is released under the CreativeCommons 'By' license. That is,
  33. you can do anything you want with it, just leave my name as one of the
  34. authors. http://creativecommons.org/licenses/by/2.5/
  35.  
  36. h2. Summary
  37.  
  38. Provides an interface to let you assign colors to users you meet - that way, if you find a user's link on a page in the future, it will automatically be highlighted with thes color you previously gave them.
  39.  
  40. In group pool pages, you can highlight user photos where more than one image is visible from the same user. You can also overlay all comments from a user under the corresponding photos on that page.
  41.  
  42. h2. Features:
  43.  
  44. # Configuration
  45. ** All features can be toggled on / off
  46. ** Access to configuration either through [?] links or main "Organize" menu
  47. ** Colors can be customized.
  48. # User coloration
  49. ** All '/photos/USERNAME/' links will be altered:
  50. *** Clicking on them brings up a mini-menu
  51. *** You can assign a color to any user, which will highlight the user links
  52. *** Colors will be remembered (only on your computer)
  53. *** It is now possible to assign multiple colors to a user
  54. *** Links to their photos, profile and pool images (if in pool page) shown in menu
  55. # Group pool analysis
  56. ** When viewing pool pages, all images on the page are tallied
  57. *** Users posting more than one photo will be noted
  58. *** Images from those users will get a colored background
  59. *** Background colors are unique to each user (but otherwise essentially random)
  60. *** Summary of users posting multiple images shown at top of page
  61. ** Comments for all photos on a pool page are pre-fetched
  62. *** For any poster on a pool page, all their comments can be shown for other photos on the same page
  63. ** NOTE: these functions are off by default, turn them on in the options page ('Organize' Flickr menu)
  64.  
  65. !http://static.flickr.com/69/206732191_399d74d02a.jpg!:http://www.flickr.com/photos/charlestilford/206732191/
  66.  
  67. !http://static.flickr.com/73/219349265_b6b41a139b.jpg!:http://www.flickr.com/photos/charlestilford/219349265/
  68.  
  69. !http://static.flickr.com/90/219349268_a4dd3fa439.jpg!:http://www.flickr.com/photos/charlestilford/219349268/
  70.  
  71.  
  72. Handy Color name reference:
  73. http://www.w3.org/TR/2002/WD-css3-color-20020219/#x11-color
  74.  
  75. !! Caution !!
  76.  
  77. Persistent data, such as colors assigned to users, are stored within
  78. the Grease Monkey / FireFox system itself. If you invest a lot of time in
  79. color-coding users, you run the risk of losing all your assignments if
  80. FireFox's prefs.js is over-written. If you would like to back up your
  81. assignments, you should back up that file - on Windows it will be
  82. somewhere like:
  83.  
  84. C:\Documents and Settings\YourUserName\Application Data\
  85.    Mozilla\Firefox\Profiles\8aabdex06.default\prefs.js
  86.  
  87. and have entries like:
  88.  
  89. user_pref("greasemonkey.scriptvals.http://www.tilford.net//Flickr Functional Suite.UserColorcharlestilford", "Lime");
  90.  
  91. !! About User Identifications
  92.  
  93. Flickr uses a confusing mixture of identifiers for their customers.
  94.  
  95. Flickr     Used Here Example
  96. ---------- --------- -----------------
  97. NSID:      nsid      51159953@N00
  98. username:  uname     listentoreason
  99. photourl:  purl      charlestilford
  100. displayid: dispid    Truncated Username...
  101.  
  102. The NSID is the most useful for getting information, but the least
  103. human friendly. The displayid is not technically an official
  104. identifer, but is encountered when parsing Flickr web pages. It is
  105. used when a user name is too long - the username is truncated,
  106. apparently on a whitespace character, and shown with elipses ie "...".
  107.  
  108. # History
  109. * 25 Aug 2006
  110. ** John Carney suggests a Plays-Nice-With-Others alteration that lets pop-up functionality work fine with other GM scripts
  111. ** Added additional links in user menu, tried to tighten up real estate usage
  112. * 24 Aug 2006
  113. ** Bug fix by John Carney (http://schmickr.innercurmudgeon.com/)
  114. * 19 Aug 2006
  115. ** Implemented interface to Flickr API
  116. ** Use API to fetch comments for all photos on pool page
  117. *** For any pool contributor, show all of their comments on that page
  118. * 15 Aug 2006
  119. ** Allow multiple colors to be assigned to one user
  120. * 6 Aug 2006
  121. ** User settings added
  122. *** Can toggle basic behaviors on and off
  123. *** Can now customize color list, and assign description to each color
  124. ** Altered 'All Pool Photos' to only display when the low-level ID is used as the UID
  125. * 4 August 2006
  126. ** Nice interface to set user color
  127. ** User colors persistently stored with GM_setValue()
  128. ** Multiple posting working well
  129. ** The 'All Pool Photos' usually will not work - I need to implement a method to ajax get the low-level user ID
  130.  
  131.  !! Disclaimer !!
  132.  
  133. Feel free to mine the code for ideas, but be warned that because this
  134. is a Grease Monkey script, I have made no effort at all to make the code
  135. anywhere close to cross-browser compatible - parts of the code will be
  136. specific to FireFox and will not function in other browsers.
  137.  
  138. Boy it is *nice* to develop JS for *ONLY* FireFox!
  139.  
  140. */
  141.  
  142.  
  143. var CatFlickrSuite = {
  144.     // Internal data structures
  145.     privateData: new Object(), // Safe (?) storage of metadata for DOM elements
  146.     env:         new Object(), // Global environmental values
  147.     user:        new Object(), // user-defined values
  148.     doneTask:    new Object(), // Prevent re-fetching some data
  149.     gmMsg: "",                 // Debugging message buffer
  150.     apikey: "b1c88b6a99ffabbf76ace9eab025996f",
  151.     seckey: "79c1cc27f6c7cff9",
  152.     objects: {  }, // Pre-calculated/scanned
  153.     // Sigh. Flickr is changing their object IDs. Their perogative, of course
  154.     // Centralize the IDs here to make code updates easier
  155.     fids: {
  156.         main: 'main',
  157.         navYou: 'flickr_nav_menu_you',
  158.         //        navOrg: 'flickr_nav_menu_organize',
  159.         navOrg: 'explore-panel',
  160.         csfHelp: 'CfsHelpButton',
  161.         csfCols: 'currentColors',
  162.         csfAvl:  'availableColors',
  163.         csfPop:  'CatFlickrSuitePopUp',
  164.         csfTag:  'CFS_Tag_Assoc',
  165.         grpAvl:  'TagMatchAvail'
  166.     },
  167.     // User configurable parameters. Organized by class (the kind of
  168.     // <input> used to represent them) and parameter name, with a
  169.     // description and default value for each.
  170.     userSet: {
  171.         checkbox: {
  172.             colorUser: ["Colorize user IDs",1],
  173.             colorMult: ["Colorize multiple images from same user in group pools",0],
  174.             sumMult:   ["Summarize multi-posters in group pools",0],
  175.             getCom:    ["Pre-fetch all comments associated with photos on a pool page",0],
  176.         },
  177.         text: {
  178.             comWidth:  ["Maximum characters to show for in-line comments",100],
  179.             comSize:   ["Inline comment font size", '9px'],
  180.         },
  181.         textarea: {
  182.             UserColors: ["Colors and descriptions for tagging other users",
  183.                          "Lime Category 1\nAqua Category 2\nFuchsia Category 3\nSilver Category 4\nYellow Category 5\nRed Category 6\nBlack Category 7\nNone"],
  184.         },
  185.     },
  186.     translate: { },
  187.     // The 'minimum RGB spacing' - prevents grays when using string2color and color4string:
  188.     colBuf: 64,
  189.     /* colMin and colMax added for @decembre. Allows the RGB index
  190.        range in pools to be changed from 0-255 to user prefs.
  191.        colMin - increase to prevent 'dark' index values
  192.        colMax - decrease to prevent 'light' index values
  193.        ALWAYS have colMin < colMax, and both between 0 and 255 */
  194.     colMin: 0,
  195.     colMax: 255,
  196.     counter: 0,
  197.     ticket: 0,
  198.     ticketStatus: new Object(),
  199.     // Special links that we want to ignore:
  200.     specialLinks: ['1', '< Prev', 'You', 'Organize', 'Upload', 'upload',
  201.                    'Popular Tags','Organize & Create', "All your content",
  202.                    'Upload Photos and Videos', "Your Photostream",
  203.                    'Your Photos', 'Upload Photos', 'All your photos', ],
  204.     re: {
  205.         // Regular Expression Collection
  206.         frob:       /\?frob=(\S+)$/,             // Authentication frob
  207.         photoID:    /\/photos\/([^\/]+)\/(\d+)/, // PURL and Photo ID
  208.         userPhotos: /\/photos\/([^\/]+)\/$/,     // Link to user photots
  209.         myComs:     /\/photos_comments\.gne/,    // Comments you made
  210.         urlPool1:   /\/([^\/]+)\/pool\//,        // Group pool href
  211.         urlPool2:   /\/in\/pool-([^\/]+)\//,     // Image in pool stream
  212.         urlGroup:   /\/groups\/([^\/]+)\//,      // General group URL
  213.         urlAllGrp:  /\/groups\/?$/,               // Group list page
  214.         statRef:    /\/stats\/([^\/]+)\//,       // Statistics page
  215.         urlSet:     /\/photos\/([^\/]+)\/sets\/(\d+)\/?$/, // Photoset
  216.         elipsed:    /\.\.\.$/,                   // Trailing 3 periods (elipses)
  217.         nsid:       /^\d+\@.{3}$/, // Not sure what the real format is?
  218.         organize:   /\/photos\/organize\//,      // Organize DHTML interface
  219.     },
  220.     init: function() {
  221.         // The primary initialization function
  222.         // GM_log("Starting: " + new Date());
  223.         var now = new Date();
  224.         this.ms = now.getTime().toString();
  225.         this.setEnvironment();
  226.         if (this.env.pageType == 'Organize') return; // Do nothing on Organize
  227.         this.initTransmute();
  228.         this.setSettings();
  229.         this.insertSettings();
  230.         this.refresh();
  231.         this.annotateGroupList();
  232.         this.tagAssociation();
  233.         this.cleanComments();
  234.         this.colorStats();
  235.         this.finalize();
  236.         GM_log("Initialized Flickr Functional Suite");
  237.         window.addEventListener('click', function (e) {
  238.                 // alert('new data!');
  239.                 CatFlickrSuite.checkClickEvent(e);
  240.             }, false);
  241.  
  242.         //window.addEventListener('AutoPagerNewData', function (e) {
  243.         //        document.CatFlickrSuite.refresh();
  244.         //    }, false);
  245.     },
  246.     refresh: function() {
  247.         this.grabFrob();
  248.         this.armLinks();
  249.         this.findMultiPost();
  250.         this.colorUserPhotos();
  251.         this.getAllComments();
  252.     },
  253.     whoami: function() {
  254.         if (this.you == null) {
  255.             var data = this.parseFlickrData();
  256.             this.you = "";
  257.             if (data.flickr && data.flickr.user && data.flickr.user.pathalias) {
  258.                 this.you = data.flickr.user.pathalias;
  259.             } else {
  260.                 GM_log("Could not find path alias");
  261.             }
  262.         }
  263.         return this.you;
  264.     },
  265.     myNSID: function() {
  266.         if (this.nsid == null) {
  267.             var data = this.parseFlickrData();
  268.             this.nsid = 0;
  269.             if (data.flickr && data.flickr.user && data.flickr.user.nsid) {
  270.                 this.nsid = data.flickr.user.nsid;
  271.             } else {
  272.                 GM_log("Could not find NSID");
  273.             }
  274.         }
  275.         return this.nsid;
  276.     },
  277.     parseFlickrData: function () {
  278.         if (!this.yconf) {
  279.             var nodes = document.getElementsByTagName('script');
  280.             for (var n=0; n<nodes.length; n++) {
  281.                 var html = nodes[n].innerHTML;
  282.                 if (!html) continue;
  283.                 var hits = html.match(/\s*var\s+yconf\s+=\s*(\{.+?\})\;\s*/);
  284.                 if (hits) {
  285.                     this.yconf= JSON.parse( hits[1]);
  286.                     break;
  287.                 }
  288.             }
  289.             if (!this.yconf) {
  290.                 this.yconf = new Object();
  291.                 GM_log("Failed to find Flickr yconf hash object");
  292.             }
  293.         }
  294.         return this.yconf;
  295.     },
  296.     groupID: function() {
  297.         if (this.groupid == null) {
  298.             this.groupid = 0;
  299.             var nodes = document.getElementsByTagName('link');
  300.             for (var n=0; n<nodes.length; n++) {
  301.                 if (!nodes[n] || !nodes[n].href) continue;
  302.                 var hits = nodes[n].href.match(/groups_[a-z]+\.gne\?.*id=([^\&]+)/);
  303.                 if (hits) { this.groupid = hits[1]; break; }
  304.             }
  305.             if (!this.groupid) {
  306.                 // Try links
  307.                 nodes = document.getElementsByTagName('a');
  308.                 for (var n=0; n<nodes.length; n++) {
  309.                     if (!nodes[n] || !nodes[n].href) continue;
  310.                     var hits = nodes[n].href.match(/groups_[a-z]+\.gne\?.*id=([^\&]+)/);
  311.                     if (hits) { this.groupid = hits[1]; break; }
  312.                 }
  313.             }
  314.         }
  315.         return this.groupid;
  316.     },
  317.     setEnvironment: function() {
  318.         // Gather some global information
  319.         var href = this.env.href = document.location.href;
  320.         var mat;
  321.         this.env.pageType = this.env.pageView = '';
  322.         // Are we on the organize page?
  323.         mat  = href.match(this.re.organize);
  324.         if (mat) { this.env.pageType = 'Organize';
  325.         this.env.pageView = 'Organize'; return; }
  326.         // Are we on a 'Comments you've made' page?
  327.         mat  = href.match(this.re.myComs);
  328.         if (mat) { this.env.pageType = 'Comment';
  329.         this.env.pageView = 'YourComments'; return; }
  330.         // Are we on a Group's pool page?
  331.         // See if we are in a group pool-related page:
  332.         mat  = href.match(this.re.urlPool1);
  333.         if (mat) { this.env.group = mat[1];
  334.         this.env.pageType = 'Group'; this.env.pageView = 'Pool'; return; }
  335.  
  336.         // Group list page
  337.         mat  = href.match(this.re.urlAllGrp);
  338.         if (mat) { this.env.group = mat[1];
  339.             this.env.pageType = 'Group'; this.env.pageView = 'YourGroups'; return; }
  340.  
  341.         // Generic URL for groups:
  342.         mat  = href.match(this.re.urlGroup);
  343.         if (mat) { this.env.group = mat[1];
  344.         this.env.pageType = 'Group'; return; }
  345.         // A photoset page:
  346.         mat  = href.match(this.re.urlSet);
  347.         if (mat) { this.env.setOwn = mat[1]; this.env.set = mat[2];
  348.         this.env.pageType = this.env.pageView = 'Set'; return; }
  349.         // Statistics Page
  350.         mat  = href.match(this.re.statRef);
  351.         if (mat) {
  352.             this.env.statType = mat[1];
  353.             this.env.pageType = this.env.pageView = 'Stats'; return;
  354.         }
  355.        
  356.     },
  357.     initTransmute: function() {
  358.         // Turn one object type into another This just allows
  359.         // representation of some data structures in a format that is
  360.         // easy for humans to modify, but not the ultimate structure
  361.         // needed by the code.
  362.         this.specLinkHash = new Object();
  363.         for (var i=0; i<this.specialLinks.length;i++) {
  364.             this.specLinkHash[this.specialLinks[i].toLowerCase()] = 1;
  365.         }
  366.         // Flatten settings hash into 2D array
  367.         var uarr = new Array();
  368.         for (var type in this.userSet) {
  369.             // Cycle through each data type
  370.             var info = this.userSet[type];
  371.             for (var tag in info) {
  372.                 // Cycle through each parameter
  373.                 var subarray = [ type, tag ];
  374.                 // Add description, defaultValue:
  375.                 subarray = subarray.concat( info[tag] );
  376.                 uarr.push(subarray);
  377.             }
  378.         }
  379.         this.msg();
  380.         this.userSetArr = uarr;
  381.     },
  382.     setSettings: function() {
  383.         // Scan all configurable tagnames and retrieve value from
  384.         // GreaseMonkey internal store, or set to default value.
  385.         var uarr = this.userSetArr;
  386.         for (var u=0; u < uarr.length; u++) {
  387.             var tag        = uarr[u][1];
  388.             var def        = uarr[u][3];
  389.             this.user[tag] = GM_getValue(tag, def);
  390.         }
  391.         // Special processing of user colors
  392.         var colArr = this.user.UserColors.split(/[\r\n]+/);
  393.         this.user.colList = new Array();
  394.         this.user.colDesc = new Object();
  395.         for (var c=0;c<colArr.length;c++) {
  396.             var cbits = colArr[c].split(/\s+/);
  397.             var cname = cbits.shift();
  398.             if (!cname || cname == '') continue;
  399.             var cdesc = cbits.join(' ');
  400.             this.user.colList.push(cname);
  401.             this.user.colDesc[ cname.toLowerCase() ] = cdesc;
  402.         }
  403.     },
  404.     msg: function() {
  405.         // Record some debugging information. These messages will
  406.         // appear in the FireFox javascript Console, under 'Messages'
  407.         if (this.gmMsg != "") GM_log("Execution messages:\n"+this.gmMsg);
  408.         this.gmMsg = "";
  409.     },
  410.     err: function (msg, e) {
  411.         // Throw an error, also to the JS concole
  412.         if (e) {
  413.             if (e.description) msg += "\n  DESC: " + e.description;
  414.             msg += "\n  ERR: " + e;
  415.         }
  416.         GM_log(msg);
  417.     },
  418.     finalize: function() {
  419.         // Final code to execute after all parsing is done.
  420.         this.msg();
  421.     },
  422.     armLinks: function() {
  423.         // Search for <a> tags on the page that we want to modify
  424.         var links = this.liveUserPhotoList();
  425.         for (var i=0; i < links.length; i++) {
  426.             this.registerUserPhoto( links[i] );
  427.         }
  428.     },
  429.     colors4user: function(purl, asArray) {
  430.         // Get your color(s) for a particular PURL
  431.         // asArray = return array, otherwise return hash
  432.         var rv = asArray ? new Array() : new Object();
  433.         var cstr = GM_getValue("UserColor"+purl);
  434.         if (!cstr) return rv;
  435.         // Split string on spaces
  436.         var clist = cstr.split(/\s+/);
  437.         for (c=0; c < clist.length; c++) {
  438.             var cname = clist[c].toLowerCase();
  439.             if (!cname || cname == 'none') continue; // compatibility with old versions
  440.             if (asArray) {
  441.                 rv.push(cname);
  442.             } else {
  443.                 rv[cname] = clist[c];
  444.             }
  445.         }
  446.         return rv;
  447.     },
  448.     userPhotoClick: function(el, evt) {
  449.         if (evt) {
  450.             evt.preventDefault();
  451.             evt.stopPropagation();
  452.             GM_log(evt);
  453.             evt.returnValue = false;
  454.         }
  455.         // Establish the new pop-up menu that will be used for "/photos/UserName/" links:
  456.         // GM_log(el.id + ' from ' + this.ms);
  457.         var dispid    = this.registerUserPhoto(el);
  458.         var uname     = this.getTranslation(dispid, 'uname');
  459.         var purl      = this.getTranslation(dispid, 'purl');
  460.         var nsid      = this.getTranslation(dispid, 'nsid');
  461.         var colHash   = this.colors4user( purl );
  462.         // GM_log("User click on "+el.id+" ("+el+") = "+dispid);
  463.         // Close box and name:
  464.         var html = "<span class='CancelButt'>[x]</span>&nbsp;<b>"+
  465.         (uname ? uname : dispid)+
  466.         "</b>&nbsp;<span style='color:green;cursor:help' id='"+
  467.         this.fids.csfHelp+"'>[?]</span>\n<div id='currentColors'>";
  468.         for (var ucol in colHash) {
  469.             html += this.userColorBlock( colHash[ucol], 'SetColor' );
  470.         }
  471.         html += "</div>\n";
  472.  
  473.         // Each 'item' is a line in the popup - see makeMenu()
  474.         var items = new Array();
  475.         var links = new Array();
  476.         // This is what the link used to point to:
  477.         links.push( ['Photos', "/photos/"+purl+"/" ] );
  478.         // Add in the user's profile, favorites, sets and tags:
  479.         links.push( [ 'Profile', "/people/"+purl+"/" ] );
  480.         links.push( [ 'Favorites', "/photos/"+purl+"/favorites/"] );
  481.         // links.push( [ 'Archive', "/photos/"+purl+"/archives/"] );
  482.         links.push( [ 'Sets', "/photos/"+purl+"/sets/"] );
  483.         links.push( [ 'Tags', "/photos/"+purl+"/tags/"] );
  484.         if (nsid) {
  485.             links.push( ['Mail', "/messages_write.gne?to="+nsid]);
  486.         }
  487.         if (this.env.pageView == 'Pool') {
  488.             // We are on a pool-related page
  489.             if (nsid) links.push ( ['All Pool Photos', '/groups/'+this.env.group+'/pool/'+nsid]);            if (uname && this.objects.comments) {
  490.                 // Pre-computed comments are available
  491.                 if (this.objects.comments[uname]) {
  492.                     // We found at least one comment for this user
  493.                     var coms = this.objects.comments[uname];
  494.                     var cn   = coms.length;
  495.                     var cmag = {href: "javascript:void(0)", 'class': 'ShowComments', text: ctxt};
  496.                     var ctxt = (this.objects.shownComments[uname] ? 'Hide ' : 'Show ') + cn;
  497.                     ctxt    += " comment"+(cn == 1 ? '' : 's')+ " on this page";
  498.                     cmag.text = ctxt;
  499.                     items.push(cmag);
  500.                 } else {
  501.                     // No comments for this user
  502.                     items.push("<i>No comments found</i>");
  503.                 }
  504.                 // Are the AJAX requests succesfully completed?
  505.                 var stat = this.apiStatus('getComments');
  506.                 if (stat != "") {
  507.                     // Warn the user that some data was not available.
  508.                     items.push({ tag:'i', style:'color:orange; font-size:xxsmall', text:"&rArr;Data missing: "+stat})
  509.                 }
  510.             }
  511.         }
  512.          if (uname) {
  513.             // John Watson's Scout page - list of the user's interesting photos
  514.             links.push
  515.                 ( [ 'Scout', "http://flagrantdisregard.com/flickr/scout.php?username="+uname] );
  516.             // Nathan Siemer's HiveMind
  517.             links.push
  518.             ( [ 'HiveMind', "http://flickrhivemind.net/User/"+uname] );
  519.         }
  520.         if (links.length > 0) {
  521.             // The number of links to stuff into one line:
  522.             var linksPerLine = 3;
  523.             for (var l=0;l<links.length; l++) {
  524.                 html += "| <a class='simple_butt' href='"+links[l][1]+"'>"+links[l][0]+"</a> ";
  525.                 if (!((l+1) % linksPerLine)) html += "|</br>";
  526.             }
  527.             if (links.length % linksPerLine) html += "|</br>";
  528.         }
  529.         // Make a menu of colors to list:
  530.         items.push({ tag:'b', text: 'Available Flags:' });
  531.  
  532.         html += this.makeMenu( items ) +"\n<div style='font-size:smaller' id='"
  533.         + this.fids.csfAvl + "'>";
  534.         for (var c=0; c < this.user.colList.length; c++) {
  535.             var col   = this.user.colList[c];
  536.             if (colHash[col.toLowerCase()]) continue;
  537.             var linkHtml = this.userColorBlock( col, 'SetColor' );
  538.             if (linkHtml != "") html += linkHtml;
  539.         }
  540.         html += "</div>\n";
  541.  
  542.         // Pop up the window
  543.         var div = this.popUp(el, html, evt);
  544.         // Also associate the PURL with the popup, we'll need it for processing clicks later
  545.         var hb = document.getElementById(this.fids.csfHelp);
  546.         if (hb) hb.addEventListener('click', function (e) {
  547.             return CatFlickrSuite.settingsClick(this, e);}, false);
  548.         this.privateHash(div, 'purl', purl);
  549.         this.privateHash(div, 'dispid', dispid);
  550.         this.privateHash(div, 'onclose', function() {
  551.                 CatFlickrSuite.updateUser( el );
  552.             } );
  553.         GM_log("DEBUG="+el.href);
  554.         return false;
  555.     },
  556.     userColorBlock: function(col, cname) {
  557.         // Returns a single div for a category color
  558.         if (/^none$/i.test(col)) return ""; // compatibility with old versions
  559.         // Get the description for this color:
  560.         var text  = this.user.colDesc[col.toLowerCase()];
  561.         // Use the color name itself if no description available:
  562.         if (!text) text = col;
  563.         return this.makeMenu( [ {
  564.             tag: 'div', 'class':cname, text: "<em>"+text+"</em>", colName: col, style: "background-color:"+col
  565.         } ] );
  566.     },
  567.     escapeXML: function (txt) {
  568.         if (txt == null) return '';
  569.         txt = txt.replace(/&gt;/g,'>');
  570.         txt = txt.replace(/&lt;/g,'<');
  571.         txt = txt.replace(/&amp;/g,'&');
  572.         return txt;
  573.     },
  574.     unescapeXML: function (txt) {
  575.         if (txt == null) return '';
  576.         txt = txt.replace(/\>/g,'&gt;');
  577.         txt = txt.replace(/\</g,'&lt;');
  578.         txt = txt.replace(/\&/g,'&amp;');
  579.         return txt;
  580.     },
  581.     liveUserPhotoList: function () {
  582.         /* Designed to always return a list of user photos, even
  583.            if the page has been modified by another script */
  584.         var arr = new Array();
  585.         var links = document.getElementsByTagName("a");
  586.         for (var l=0; l < links.length; l++) {
  587.             var el = links[l];
  588.             if (this.isUserPhoto(el)) arr.push(el);
  589.         }
  590.         return arr;
  591.     },
  592.     isUserPhoto: function (el) {
  593.         if (!el) return false;
  594.         var dispid  = el.text;
  595.         // Skip special links:
  596.         if (dispid == null || dispid == '' || this.specLinkHash[dispid.toLowerCase()] ||
  597.             /photostream$/.test(dispid)) return false;
  598.         var hit  = el.href.match( this.re.userPhotos );
  599.         if (!hit) return false;
  600.         return hit[1];
  601.     },
  602.     colorUserPhotos: function (purlReq) {
  603.         if (this.user.colorUser != 1) return;
  604.         // This routine colors <a> tags pointing to
  605.         // "/photos/UserName/", so long as you have assigned a color
  606.         // to that particular user. If purlReq is null, then all links
  607.         // are processed, otherwise only the requested purl will be
  608.         // altered.
  609.         var arr = this.liveUserPhotoList();
  610.         this.gmMsg += "Coloring User photos for '"+purlReq+"' out of " +arr.length+" total images\n";
  611.         for (var i=0; i < arr.length; i++) {
  612.             var el     = arr[i];
  613.             // if (this.privateHash(el, 'cupDone')) continue;
  614.             this.privateHash(el, 'cupDone', true);
  615.             var purl   = this.privateHash(el, 'purl');
  616.             // Skip if there is a specific request and this is not it
  617.             if (purlReq && purl != purlReq) continue;
  618.             // this.gmMsg += "Coloring "+purl+"\n";
  619.             var colArr  = this.colors4user( purl, true );
  620.             var colNum  = colArr.length;
  621.             var text    = this.privateHash(el, 'innerText');
  622.             var htmlNow = el.innerHTML;
  623.             if (colNum < 1) {
  624.                // Decolorize the link if it was previously colored:
  625.                 if (text) el.innerHTML = htmlNow.replace(/\<span[^\>]+span\>/,'');
  626.                 continue;
  627.             }
  628.             if (!text) {
  629.                 text = this.unescapeXML(el.text);
  630.                 this.privateHash(el, 'innerText', text);
  631.             }
  632.             // The routine below will color the user's name into one or more colored blocks:
  633.             var tlen   = text.length;
  634.             var step   = tlen / colNum;
  635.             var html   = "";
  636.             for (var c=0; c < colNum; c++) {
  637.                 var start = Math.floor(0.5 + c * step);
  638.                 var end   = (c == colNum - 1) ? tlen : Math.floor(0.5 + (c+1) * step);
  639.                 if (start == end) continue;
  640.                 html += "<span style='background-color:"+colArr[c]+"'>"+
  641.                     this.escapeXML(text.substring(start, end)) + "</span>";
  642.             }
  643.             if (/\<span/.test(el.innerHTML)) {
  644.                 el.innerHTML = htmlNow.replace(/\<span.+span\>/, html);
  645.             } else {
  646.                 el.innerHTML = htmlNow.replace(text, html);
  647.             }
  648.         }
  649.         this.msg();
  650.     },
  651.     tagAssociation: function () {
  652.         var main  = document.getElementById(this.fids.main);
  653.         if (!main) return;
  654.         var type = this.env.pageType;
  655.         if (type == 'Set') {
  656.             // Only associate with sets you own
  657.             var you   = this.whoami();
  658.             var owner = this.env.setOwn;
  659.             if (!owner || !you || owner != you) return;
  660.         } else if (type != 'Group') {
  661.             return;
  662.         }
  663.         var div = document.getElementById(this.fids.csfTag);
  664.         if (!div) {
  665.             // Make the div if we have not already done so
  666.             div = document.createElement('div');
  667.             div.id = this.fids.csfTag;
  668.             main.insertBefore(div, main.firstChild);
  669.             div.style.border = 'solid navy 1px';
  670.         }
  671.         var tags = new Array();
  672.         var hash = this.getTagAssociations(  );
  673.         for (var tag in hash) {
  674.             if (tag && tag != '') tags.push( tag );
  675.         }
  676.         var html = "";
  677.         var form = document.createElement('form');
  678.         form.innerHTML = "<i>Associate tag rule with this "+type+":</i> "+
  679.         "<input name='tagassoc' width='20' value='' />";
  680.         div.innerHTML = html;
  681.         div.appendChild(form);
  682.         form.addEventListener('submit', function (e) {
  683.             e.preventDefault();
  684.             return CatFlickrSuite.addTagAssociation(this);}, false);
  685.         if (tags.length != 0) {
  686.             var tform = document.createElement('form');
  687.             var thtml = "<input type='submit' id='cfs_ta_search' value='Find new members with tag:'>";
  688.             tags = tags.sort();
  689.             for (var t=0; t < tags.length; t++) {
  690.                 var tag = tags[t];
  691.                 thtml += "<span style='border: grey solid 1px; margin: 3px; padding: 3px;'><input type='checkbox' name='cfs_ta' value='"+tag+
  692.                     "' checked='checked'/>"+hash[tags[t]] +" <span class='CancelButt'>[x]</span></span> ";
  693.             }
  694.             var lim = GM_getValue("TagAssocLimit", '');
  695.             thtml += "<br /><span style='color: #006'>";
  696.             thtml += "Report at most <input id='cfs_ta_limit' size='3' value='"+lim+
  697.                 "' /> matches";
  698.             thtml += ", uploaded between <input id='cfs_ta_minage' size='3' />";
  699.            thtml += " to <input id='cfs_ta_maxage' size='3' /> days ago";
  700.             thtml += "</span>\n";
  701.             tform.innerHTML = thtml;
  702.             div.appendChild(tform);
  703.             // Monitor tag interactions:
  704.             tform.addEventListener('click', function (e) {
  705.                 return CatFlickrSuite.tagAssocClickHandler(e);}, false);
  706.         }
  707.         this.taDiv = div;
  708.     },
  709.     intFromField: function( fieldId, desc, errors) {
  710.         var obj = document.getElementById( fieldId);
  711.         if (!obj) return null;
  712.         if (/^\d+$/.test(obj.value)) return obj.value;
  713.         if (desc && errors) errors.push(desc);
  714.         return null;
  715.     },
  716.     UTC: new Date(1970,0,1),
  717.     flickrDateFormat: function( offset ) {
  718.         if (!offset) offset = 0;
  719.         var dt = new Date();
  720.         dt.setDate(dt.getDate() - offset);
  721.         return (dt.getTime() - this.UTC.getTime()) / 1000 ;
  722.         return dt.toUTCString();
  723.  
  724.         var string = dt.getFullYear();
  725.         var bits   = [ dt.getMonth() + 1, dt.getDate(),
  726.                        dt.getHours(), dt.getMinutes(), dt.getSeconds() ];
  727.         for (var b=0; b < bits.length; b++) {
  728.             var val = bits[b];
  729.             if (val < 10) val = '0' + val;
  730.             string += val;
  731.         }
  732.         return string;
  733.     },
  734.     gmObjId: function () {
  735.         var type = this.env.pageType.toLowerCase();
  736.         if (!type || type == '' || !this.env[type] ) return '';
  737.         return type + '_' + this.env[type];
  738.     },
  739.     getTagAssociations: function() {
  740.         var hash = new Object();
  741.         var gid  = this.gmObjId();
  742.         if (gid == '') return hash;
  743.         var txt = GM_getValue("TagAssoc_"+gid, '');
  744.         var words = txt.split(',');
  745.         for (var w=0; w < words.length; w++) {
  746.             var raw = words[w];
  747.             hash[ this.cleanTag(raw) ] = raw;
  748.         }
  749.         return hash;
  750.     },
  751.     setTagAssociations: function(hash) {
  752.         var gid  = this.gmObjId();
  753.         if (!hash || gid == '') return 0;
  754.         var arr = new Array();
  755.         for (var tag in hash) {
  756.             if (tag && tag != '') arr.push(hash[tag]);
  757.         }
  758.         arr = arr.sort();
  759.         GM_setValue("TagAssoc_"+gid, arr.join(','));
  760.         return arr.length;
  761.     },
  762.     addTagAssociation: function (el) {
  763.         var val = this.valuesForNamedInput(el, 'tagassoc');
  764.         if (!val || val.length != 1 || ! val[0]) return;
  765.         var raw  = val[0];
  766.         var tag  = this.cleanTag(raw);
  767.         var hash = this.getTagAssociations();
  768.         hash[ tag ] = raw;
  769.         this.setTagAssociations(hash);
  770.         // Redraw the interface
  771.         this.tagAssociation();
  772.     },
  773.     tagAssocClickHandler: function(e) {
  774.         // Respond to a click event in a tag list
  775.         if (!e || !e.originalTarget) return;
  776.         var targ  = e.originalTarget;
  777.         var cn, id;
  778.         try {
  779.             // For some reason this throws a Permission Denied sometimes
  780.             cn = targ.className;
  781.             id = targ.id;
  782.         } catch (e) {
  783.             this.err("Failed to find node information for "+targ, e);
  784.         }
  785.         if (cn == 'CancelButt') {
  786.             var el    = targ.parentNode.firstChild;
  787.             if (!el || !el.value) return;
  788.             var raw  = el.value;
  789.             var hash = this.getTagAssociations();
  790.             delete hash[ this.cleanTag(raw) ];
  791.             this.setTagAssociations(hash);
  792.             this.tagAssociation(); // Redraw the interface
  793.         } else if ( id == 'cfs_ta_search' ) {
  794.             e.preventDefault();
  795.             this.searchTagAssociations();
  796.         }
  797.     },
  798.     cleanTag: function (raw) {
  799.         // "Hot Dog" !cat rat !"My Mouse"
  800.         // leading exclamation point
  801.         if (raw == null) return '';
  802.         var tag = raw.toLowerCase();
  803.         tag = tag.replace(/\s+/g, ' ');   // Space runs trimmed to single spaces
  804.         tag = tag.replace(/\! /g, '!');   // Remove trailing space after !
  805.         var tagList = new Array();
  806.         // Identify and extract contents of quoted strings
  807.         var quotes  = [ "'", '"' ];
  808.         for (var q = 0; q < quotes.length; q++) {
  809.             var qt = quotes[q];
  810.             // Make sure ! is inside quotes:
  811.             var swRE   = new RegExp('!' + qt, 'g');
  812.             tag        = tag.replace(swRE, qt + '!');
  813.             var nestRe = new RegExp(qt+ '([^' + qt + ']+)' + qt);
  814.             while (1) {
  815.                 var quoted = tag.match( nestRe );
  816.                 if (!quoted || quoted.length < 2) break;
  817.                 var inner = quoted[1];
  818.                 // Check for leading !
  819.                 var isNot = /^\!/.test(inner) ? '!' : '';
  820.                 inner     = inner.replace(/[^a-z0-9]/g, '');
  821.                 tagList.push( isNot + inner );
  822.                 tag = tag.replace(quoted[0],'');
  823.             }
  824.         }
  825.         tag = tag.replace(/^\s+/, '');   // Remove leading space
  826.         tag = tag.replace(/\s+$/, '');   // Remove trailing space
  827.         var words = tag.split(/\s+/);
  828.         for (var w = 0; w < words.length; w++) {
  829.             var word  = words[w];
  830.             var isNot = /^\!/.test(word) ? '!' : '';
  831.             word     = word.replace(/[^a-z0-9]/g, '');
  832.             tagList.push( isNot + word );
  833.         }
  834.         // GM_log("Raw: "+raw+" | Parsed: "+tagList.join(' '));
  835.         return tagList.join(' ');
  836.     },
  837.     searchTagAssociations: function () {
  838.         var cbs  = document.getElementsByName('cfs_ta');
  839.         if (!cbs || cbs.length < 1) return;
  840.         var type = this.env.pageType;
  841.         var ta   = this.tagAssocResults = { shown: {}, shownum: 0 };
  842.         var nsid = this.myNSID();
  843.         if (!nsid) {
  844.             alert("Failed to determine your Flickr NSID for searching");
  845.             return;
  846.         }
  847.         var commonFlickrArgs = {
  848.             method: 'flickr.photos.search', user_id: nsid, per_page: 500, extras: 'icon_server'
  849.         };
  850.  
  851.         var atErr = new Array();
  852.         var minA  = this.intFromField('cfs_ta_minage', "minimum age", atErr);
  853.         var maxA  = this.intFromField('cfs_ta_maxage', "maximum age", atErr);
  854.         if (minA && maxA && minA > maxA) {
  855.             var tmp = minA;
  856.             minA    = maxA;
  857.             maxA    = tmp;
  858.         }
  859.         if (minA) {
  860.             commonFlickrArgs.min_upload_date = this.flickrDateFormat( minA );
  861.         }
  862.         if (maxA) {
  863.             commonFlickrArgs.max_upload_date = this.flickrDateFormat( maxA );
  864.         }
  865.         // GM_log("Date range: "+commonFlickrArgs.min_upload_date + ' to ' + commonFlickrArgs.max_upload_date);
  866.  
  867.         if (type == 'Set') {
  868.         } else if (type == 'Group') {
  869.             commonFlickrArgs.privacy_filter = 1; // Assume we want only public photos for groups
  870.         } else {
  871.             alert("I do not know how to find photos for a '"+type+"' page");
  872.             return;
  873.         }
  874.         ta.what = type;
  875.  
  876.         // Determine which tag criteria the user wants to use to find photos
  877.         var tagCriteria = new Object();
  878.         for (var c=0; c < cbs.length; c++) {
  879.             // Scan through all the user's tag criteria defined for this set / pool
  880.             var cb = cbs[c];
  881.             if (!cb.checked) continue; // Not selected for this search
  882.             // Each criteria should have one or more tags in it
  883.             var tagSet  = cb.value.split(' ');
  884.            
  885.             var crit    = { tags: [], not: [] };
  886.             var goodTag = 0;
  887.             for (var ts = 0; ts < tagSet.length; ts++) {
  888.                 var tag = tagSet[ts];
  889.                 if (!tag) continue;
  890.                 if (/\!/.test(tag)) {
  891.                     // This is a 'not' tag
  892.                     crit.not.push( tag.replace(/\!/g, '') );
  893.                 } else {
  894.                     crit.tags.push( tag );
  895.                 }
  896.                 goodTag++;
  897.             }
  898.             if (goodTag == 0) continue;
  899.             // Use the not requests to aggregate each criteria
  900.             crit.not.sort();
  901.             var nkey = crit.not.join(' ') || '';
  902.             if (!tagCriteria[ nkey ]) {
  903.                 tagCriteria[ nkey ] = {
  904.                     'not': crit.not,
  905.                     'and': new Array(),
  906.                     'or':  new Array(),
  907.                 };
  908.             }
  909.             var posTags = crit.tags;
  910.             if (posTags.length == 1) {
  911.                 // Single positive tag request, put it in an OR stack
  912.                 tagCriteria[ nkey ].or.push( posTags[0] );
  913.             } else if (posTags.length > 1) {
  914.                 tagCriteria[ nkey ].and.push( posTags.join(',') );
  915.             }
  916.         }
  917.  
  918.         var searchArgs = new Array();
  919.         for (var nkey in tagCriteria) {
  920.             var crit      = tagCriteria[ nkey ];
  921.             var orLen     = crit.or.length;
  922.             var andLen    = crit.and.length;
  923.             var notLen    = crit.not.length;
  924.             if (orLen + andLen + notLen == 0) continue; // We need at least one criteria...
  925.             var notHash;
  926.             if (notLen) {
  927.                 // There is a least one tag we should exclude
  928.                 notHash = new Object();
  929.                 for (var n = 0; n < notLen; n++) {
  930.                     notHash[ crit.not[n] ] = 1;
  931.                 }
  932.             }
  933.  
  934.             var flickArgs = new Object();
  935.             for (var cfa in commonFlickrArgs) {
  936.                 // Make a copy of the common arguments hash:
  937.                 flickArgs[ cfa ] = commonFlickrArgs[cfa];
  938.             }
  939.  
  940.             var notQuery  = "";
  941.             if (notLen) {
  942.                 // We will need to know the tags for each photo in order to exclude them
  943.                 flickArgs.extras = flickArgs.extras + ',tags';
  944.                 if (orLen || andLen) {
  945.                     // The NOT query is going to be combined with other positive criteria
  946.                     notQuery = " <span style='font-weight:bold; color:red'>but NOT</span> " +
  947.                         "<u>" + crit.not.join('</u> <b>OR</b> <u>') + "</u>";
  948.                 } else {
  949.                     // This is simply an exclusionary criteria
  950.                     searchArgs.push( [ flickArgs, {
  951.                         ticktype: 'tagAssoc', search: 'tags', not: notHash,
  952.                                       query: "<span style='font-weight:bold; color:red'>NOT</span> " +
  953.                                       "<u>" + crit.not.join('</u> <b>OR</b> <u>') + "</u>"} ] );
  954.                 }
  955.             }
  956.             if (orLen) {
  957.                 // Request to do an OR tag search
  958.                 // We need to locally copy the hash again
  959.                 var flickArgsCopy = new Object();
  960.                 for (var fa in flickArgs) {
  961.                     flickArgsCopy[fa] = flickArgs[ fa ];
  962.                 }
  963.                 flickArgsCopy.tags     = crit.or.join(',');
  964.                 flickArgsCopy.tag_mode = 'any';
  965.                 searchArgs.push( [ flickArgsCopy, {
  966.                         ticktype: 'tagAssoc', search: 'tags', not: notHash,
  967.                                       query:  "<u>" + crit.or.join('</u> <b>OR</b> <u>') +"</u>"+ notQuery }] );
  968.             }
  969.             if (andLen) {
  970.                 // Request to do one or more AND tag searches
  971.                 for (var ca = 0; ca < andLen; ca ++) {
  972.                     // We need to locally copy the hash again
  973.                     var flickArgsCopy = new Object();
  974.                     for (var fa in flickArgs) {
  975.                         flickArgsCopy[fa] = flickArgs[ fa ];
  976.                     }
  977.                     flickArgsCopy.tags     = crit.and[ca];
  978.                     flickArgsCopy.tag_mode = 'all';
  979.                     searchArgs.push( [ flickArgsCopy, {
  980.                         ticktype: 'tagAssoc', search: 'tags', not: notHash,
  981.                                       query: "<u>" + crit.and[ca].split(',').join('</u> <b>AND</b> <u>') +"</u>"+ notQuery } ] );
  982.                 }
  983.             }
  984.         }
  985.         var numSearch = searchArgs.length;
  986.         if (numSearch == 0) {
  987.             alert("You need to select at least one tag to perform a search");
  988.             return;
  989.         }
  990.  
  991.         // At least one valid set of criteria
  992.         // Add the search to find pre-existing photos
  993.         if (type == 'Set') {
  994.             var sid = this.env.set;
  995.             if (!sid) { alert("Unable to determine the Set identifier"); return; }
  996.             searchArgs.push( [
  997.                 { method: 'flickr.photosets.getPhotos', photoset_id: sid },
  998.                 { ticktype: 'tagAssoc', search: 'photoset' } ] );
  999.         } else if (type == 'Group') {
  1000.             var gid = this.groupID();
  1001.             if (!gid) { alert("Failed to find Flickr Group ID"); return }
  1002.             searchArgs.push( [
  1003.                 { method: 'flickr.groups.pools.getPhotos', per_page: 500, user_id: nsid, group_id: gid },
  1004.                 { ticktype: 'tagAssoc', search: 'photos' } ] );
  1005.         }
  1006.  
  1007.         // Set up a DIV for output:
  1008.         var resID = 'cfs_tag_search_results';
  1009.         var targ  = document.getElementById( resID );
  1010.         if (targ) {
  1011.             targ.innerHTML = "";
  1012.         } else {
  1013.             targ = document.createElement('div');
  1014.             targ.id = resID;
  1015.             this.taDiv.appendChild(targ);
  1016.         }
  1017.         ta.resultsDiv = targ;
  1018.  
  1019.         // Parse the limit value
  1020.         ta.limit  = 0;
  1021.         ta.limit  = this.intFromField('cfs_ta_limit', "search limit", atErr);
  1022.         if (ta.limit) GM_setValue("TagAssocLimit", ta.limit);
  1023.  
  1024.        
  1025.         // launch all Flickr API searches:
  1026.         for (var sa = 0; sa < searchArgs.length; sa++) {
  1027.             var div = document.createElement('div');
  1028.             var qry = searchArgs[sa][1].query;
  1029.             if (qry) {
  1030.                 qry = "with tags " + qry;
  1031.             } else {
  1032.                 qry = "already present in the " + type;
  1033.             }
  1034.             div.innerHTML = "<i>Searching for your photos "+qry+"</i>";
  1035.             targ.appendChild(div);
  1036.             searchArgs[sa][1].div = div;
  1037.             this.flickrApi( searchArgs[sa][0], 'tagAssocCB', searchArgs[sa][1] );
  1038.         }
  1039.         // The callback (tagAssocCB, below) will perform the subtraction of [Present - Needed]
  1040.     },
  1041.     tagAssocCB: function(rsp, args, cfsArgs) {
  1042.         // This function captures and combines two Ajax calls
  1043.         var st   = cfsArgs.search;
  1044.         var ta   = this.tagAssocResults;
  1045.         if (ta.complete) return;
  1046.         var targ = ta.resultsDiv;
  1047.         var qDiv = cfsArgs.div;
  1048.         var type = ta.what;
  1049.         if (st == 'tags') {
  1050.             // This query is reporting photos matching the user's tag criteria
  1051.             var notHash = cfsArgs.not;
  1052.             var keeping = new Array();
  1053.            
  1054.             for each (photos in rsp.photos) {
  1055.                 for each (photo in photos.photo) {
  1056.                     if (notHash) {
  1057.                         // We need to verify that the photo does not have an excluded tag
  1058.                         var notCount = 0;
  1059.                         var tags = photo['@tags'].split(' ');
  1060.                         for (var t = 0; t < tags.length; t++) {
  1061.                             if (notHash[ tags[t] ]) { notCount++; break; }
  1062.                         }
  1063.                         // If any of the excluded tags match, then do not use the photo
  1064.                         if (notCount) continue;
  1065.                     }
  1066.                     var pid = photo['@id'];
  1067.                     keeping.push( { id: pid, title: photo['@title'], src: 'http://static.flickr.com/'+
  1068.                                             photo['@server']+'/'+pid+'_'+photo['@secret']+'_s.jpg'} );
  1069.                 }
  1070.             }
  1071.             if (!ta.results) ta.results = new Array();
  1072.             var rdat = { photos: keeping, args: cfsArgs };
  1073.             ta.results.push( rdat );
  1074.             var numMatched = keeping.length;
  1075.             var nstyle     = 'color: blue;';
  1076.             if (numMatched == 0) {
  1077.                 rdat.done = 1;
  1078.                 nstyle = 'color: red;';
  1079.             }
  1080.             qDiv.innerHTML = "<b style='"+nstyle+"'>" + numMatched + "</b> photo"+
  1081.                 (numMatched == 1 ? ' matches ' : 's match ') + cfsArgs.query;
  1082.         } else {
  1083.             // This query is reporting photos already in the set / pool
  1084.             var numExisting = 0;
  1085.             ta.exists = new Object();
  1086.             for each (refs in rsp[st]) {
  1087.                 for each (photo in refs.photo) {
  1088.                     ta.exists[ photo['@id'] ] = 1;
  1089.                     numExisting++;
  1090.                 }
  1091.             }
  1092.             var msg = "<a target='_blank' href='http://www.flickr.com/groups/"+this.groupID()+"/pool/"+this.myNSID()+"/'><b>" + numExisting + "</b> photo" +
  1093.             (numExisting == 1 ? '' : 's') + "</a> found already in " + type;
  1094.             if (numExisting == 500) {
  1095.                 msg += ". <i style='font-size:0.7em; color:brown'>This is the maximum number of matches that Flickr will return. Some of the images suggested below (as being absent from the "+type+") may in fact already be present.</i>";
  1096.             }
  1097.             qDiv.innerHTML = msg;
  1098.         }
  1099.         // We need information from both the tag query and the pre-existing members to continue:
  1100.         if (!ta.exists || !ta.results) return;
  1101.  
  1102.         var toShow = new Array();
  1103.         var available = 0;
  1104.         for (var r = 0; r < ta.results.length; r++) {
  1105.             var rdat = ta.results[r];
  1106.             if (rdat.done) continue; // do not process result set if already processed
  1107.             var kept = rdat.photos;
  1108.             // Find results that are not already in pool / set
  1109.             var ok = 0;
  1110.             for (var k = 0; k < kept.length; k++) {
  1111.                 if (!ta.exists[ kept[k].id ]) {
  1112.                     // This photo is not in the pool
  1113.                     toShow.push( kept[k] );
  1114.                     ok++;
  1115.                 }
  1116.             }
  1117.             var msg = rdat.args.div.innerHTML;
  1118.             if (ok == 0) {
  1119.                 msg += ", all of which are already in the " + type;
  1120.             } else {
  1121.                 msg += ", <span style='font-weight:bold; color:green'>"+ok+ "</span> of which " +
  1122.                     (ok == 1 ? 'is' : 'are')+ " not yet in the " +type;
  1123.                 if (ok > available) available = ok;
  1124.             }
  1125.             rdat.args.div.innerHTML = msg;
  1126.             rdat.done = 1;
  1127.         }
  1128.         GM_setValue(this.groupID() + this.fids.grpAvl, available);
  1129.         if (toShow.length == 0) return;
  1130.  
  1131.         var you  = this.whoami();
  1132.         var form = ta.form;
  1133.         if (!form) {
  1134.             var clr  = document.createElement('button'); clr.innerHTML = "Clear All";
  1135.             var chk  = document.createElement('button'); chk.innerHTML = "Check All";
  1136.             var form = ta.form = document.createElement('form');
  1137.             form.innerHTML = "<input style='font-weight:bold; background-color: #6f6' type='submit' value='Submit to "+type+"' /> | ";
  1138.             form.appendChild(clr);
  1139.             form.appendChild(chk);
  1140.             targ.appendChild(form);
  1141.             // Arm the various buttons
  1142.             form.addEventListener('submit', function (e) {
  1143.                     // GM_log("E: " +e);
  1144.                 e.preventDefault();
  1145.                 return CatFlickrSuite.tagAssocSubmit(form);}, false);
  1146.             clr.addEventListener('click', function (e) {
  1147.                 e.preventDefault();
  1148.                 return CatFlickrSuite.setCheckboxes('orgIds', false);}, false);
  1149.             chk.addEventListener('click', function (e) {
  1150.                 e.preventDefault();
  1151.                 return CatFlickrSuite.setCheckboxes('orgIds', true);}, false);
  1152.         }
  1153.         var lim   = ta.limit;
  1154.         var defc  = (type == 'Set') ? " checked='checked'" : '';
  1155.         var togF  = this.toggleChildVisibility;
  1156.  
  1157.         for (var ts = 0; ts < toShow.length; ts++) {
  1158.             if (lim && ta.shownum >= lim) {
  1159.                 // Limit reached
  1160.                 ta.complete = 1;
  1161.                 var comp = document.createElement('div');
  1162.                 comp.innerHTML = "Requested limit of "+lim+" reached.";
  1163.                 comp.style.fontSize  = '0.7em';
  1164.                 comp.style.fontStyle = 'italic';
  1165.                 comp.style.color     = 'brown';
  1166.                 targ.appendChild(comp);
  1167.                 break;
  1168.             }
  1169.             var photo = toShow[ts];
  1170.             var pid   = photo.id;
  1171.             if (ta.shown[ pid ]) continue;
  1172.             var div   = document.createElement('div');
  1173.             div.className = 'photodiv';
  1174.             div.innerHTML = "<input type='checkbox' name='orgIds' value='"+pid+"' "+defc+"><a target='_blank' style='color: blue ! important' href='http://www.flickr.com/photos/"+you+"/"+pid+"/'>"+ photo.title+"</a><div style='display:none; position:relative;'><img src='"+photo.src+"' style='position:absolute; top: 5px; left:2em;' /></div>";
  1175.             div.addEventListener('mouseout',  togF, false);
  1176.             div.addEventListener('mouseover', togF, false);
  1177.             form.appendChild( div );
  1178.             ta.shown[ pid ] = 1;
  1179.             ta.shownum++;
  1180.         }
  1181.       // http://www.flickr.com/photos/organize/?ids=189644777,189670488
  1182.     },
  1183.     toggleChildVisibility: function( e ) {
  1184.         var obj  = e.target;
  1185.         while (obj && obj.className != 'photodiv') {
  1186.            obj = obj.parentNode;
  1187.         }
  1188.         if (!obj) return;
  1189.         var kids = obj.childNodes;
  1190.         if (!kids) return;
  1191.         if (e.type == 'mouseout') {
  1192.             kids[2].style.display = 'none';
  1193.             kids[1].style.backgroundColor = null;
  1194.        } else {
  1195.             kids[2].style.display = 'block';
  1196.             kids[1].style.backgroundColor = '#ff9';
  1197.          }
  1198.     },
  1199.     setCheckboxes: function(name, bool) {
  1200.         var ids = document.getElementsByName(name);
  1201.         if (!ids) return;
  1202.         for (var i=0; i<ids.length; i++) { ids[i].checked = bool }
  1203.     },
  1204.     tagAssocSubmit: function (frm) {
  1205.         var ids = document.getElementsByName('orgIds');
  1206.         if (!ids) return;
  1207.         var apiArgs = {  };
  1208.         var type    = this.env.pageType;
  1209.         if (type == 'Group') {
  1210.             apiArgs.method   = 'flickr.groups.pools.add';
  1211.             apiArgs.group_id = this.groupID();
  1212.         } else if (type == 'Set' && this.env.set) {
  1213.             apiArgs.method   = 'flickr.photosets.addPhoto';
  1214.             apiArgs.photoset_id = this.env.set;
  1215.         }
  1216.         if (!apiArgs.method) { alert("Failed to find ID for "+type); return; }
  1217.         var tot = 0;
  1218.         // We are going to be stripping elements out - this mucks up the ids[] array, so we will first map the checkboxes into a static array
  1219.         var elements = new Array();
  1220.         for (var i=0; i < ids.length; i++) {
  1221.             elements.push(ids[i]);
  1222.         }
  1223.         // Now we can cycle over elements:
  1224.         for (var i=0; i < elements.length; i++) {
  1225.             var el = elements[i];
  1226.             if (!el || !el.checked) continue;
  1227.             var par  = el.parentNode;
  1228.             var span = document.createElement('span');
  1229.             par.insertBefore(span,el);
  1230.             span.style.color = 'orange';
  1231.             span.style.fontSize = 'smaller';
  1232.             span.innerHTML = "Loading...";
  1233.             apiArgs.photo_id = el.value;
  1234.             par.removeChild( el );
  1235.             this.getAuthToken();
  1236.             this.flickrApi( apiArgs, 'tasubCB', {ticktype: 'groupLoad', el: span, failok: 1} );
  1237.             tot++;
  1238.         }
  1239.         if (tot < 1) { alert("Please select at least one photo"); return }
  1240.     },
  1241.     tasubCB: function (rsp, args, cfsArgs) {
  1242.         // This function just reports on the success or failure of an
  1243.         // attempt to add photos to a group or set
  1244.         var el  = cfsArgs.el;
  1245.         if (!el) return;
  1246.         var txt = rsp.toString();
  1247.         if (!txt || /^\s*$/.test(txt)) {
  1248.             // A response of nothing means success:
  1249.             el.style.color = 'green';
  1250.             el.innerHTML = 'Success! ';
  1251.         } else {
  1252.             el.style.color = 'red';
  1253.             var err = cfsArgs.error;
  1254.             if (!err) { err = "|Unknown Error|"; GM_log(txt) }
  1255.             el.innerHTML = err + ' ';
  1256.        }
  1257.     },
  1258.     cleanComments: function () {
  1259.         // Only relevant for "Comments You've Made":
  1260.         if (this.env.pageView != 'YourComments' ) return;
  1261.         var tabs = document.getElementsByTagName('table');
  1262.         var re  = new RegExp("Here's the latest \\d+\\)", "g");
  1263.         for (var t=0; t < tabs.length; t++) {
  1264.             var tab = tabs[t];
  1265.             if (tab.className != 'NewComments') continue;
  1266.             var par = tab.parentNode;
  1267.             var partabs = par.getElementsByTagName('table');
  1268.             var prior = partabs[0];
  1269.             var html = prior.innerHTML;
  1270.             var hit  = html.match(re);
  1271.             if (!hit || hit.length < 1) continue;
  1272.             tab.style.display = 'none';
  1273.  
  1274.             var span = document.createElement('span');
  1275.             span.style.color = 'blue';
  1276.             span.style.backgroundColor = 'yellow';
  1277.             span.innerHTML = "click to view comments";
  1278.             par.insertBefore(span, tab);
  1279.             tab.style.display = 'none';
  1280.             span.addEventListener('click', function (e) {
  1281.                 this.innerHTML = 'clicked';
  1282.                 var targ = this.nextSibling.style;
  1283.                 if (targ.display == 'none') {
  1284.                     this.innerHTML = 'click to hide comments';
  1285.                     targ.display   = 'block';
  1286.                 } else {
  1287.                     this.innerHTML = 'click to view comments';
  1288.                     targ.display   = 'none';
  1289.                 }
  1290.             }, false);
  1291.         }
  1292.     },
  1293.     annotateGroupList: function () {
  1294.         // alert(this.env.pageView);
  1295.         if (this.env.pageView != 'YourGroups' ) return;
  1296.         this.groupsWithTagMatches();
  1297.     },
  1298.     sortGroups: function() {
  1299.         var avail = this.groupsWithTagMatches();
  1300.         if (!avail.length) return;
  1301.         if (1) {
  1302.             sorted = avail.sort( function (a,b) { return b[1] - a[1]; } );
  1303.         } else {
  1304.             sorted = avail.sort( function (a,b) { return a[1] - b[1]; } );
  1305.         }
  1306.        
  1307.         for (var l = 0; l < sorted.length; l++) {
  1308.             var li = sorted[l][0];
  1309.             var ul = li.parentNode;
  1310.             if (!ul) continue;
  1311.             // GM_log("#"+l+" = "+li+" Group: "+li.cfsGroup+" Num: "+sorted[l][1]);
  1312.             ul.removeChild(li);
  1313.             ul.appendChild(li);
  1314.         }
  1315.     },
  1316.     groupsWithTagMatches: function () {
  1317.         if (this.groupsAvailable) return this.groupsAvailable;
  1318.         var lis    = document.getElementsByTagName('li');
  1319.         var idTest = /group_(\S+)/;
  1320.         var tot    = 0;
  1321.         var par;
  1322.         var found = new Array();
  1323.         for (var l = 0; l < lis.length; l++) {
  1324.             var li = lis[l];
  1325.             var id = li.id;
  1326.             if (!id) continue;
  1327.             var hits = id.match(idTest);
  1328.             if (!hits) continue;
  1329.             var available = GM_getValue(hits[1] + this.fids.grpAvl);
  1330.             if (available == null) {
  1331.                 available = -1;
  1332.             } else {
  1333.                 var ht = document.createElement('i');
  1334.                 ht.style.color = available == 0 ? 'gray' : 'orange';
  1335.                 ht.innerHTML = ' '+ available;
  1336.                 li.appendChild(ht);
  1337.                 tot += available;
  1338.                 par = li;
  1339.             }
  1340.             found.push([li, available]);
  1341.             li.cfsGroup = found.length;
  1342.         }
  1343.         if (par) {
  1344.             var msg = "<i style='color:orange'>"+tot+
  1345.             "</i> = photos matching your tag criteria available ";
  1346.             var mli = document.createElement('li');
  1347.             mli.innerHTML = msg;
  1348.             var srt = document.createElement('button'); srt.innerHTML = "Sort";
  1349.             mli.appendChild(srt);
  1350.             par  = par.parentNode;
  1351.             par.insertBefore(mli, par.firstChild);
  1352.             srt.addEventListener('click', function (e) {
  1353.                     e.preventDefault();
  1354.                     return CatFlickrSuite.sortGroups();}, false);
  1355.         }
  1356.         return this.groupsAvailable = found;
  1357.     },
  1358.     colorStats: function () {
  1359.         if (this.env.pageView != 'Stats' ) return;
  1360.         var nodes = document.getElementsByTagName('a');
  1361.         var isSearch = new RegExp('Searched for:');
  1362.         var isGroup  = new RegExp('\/groups\/');
  1363.         var isSet    = new RegExp('\/sets\/');
  1364.     var isTag    = new RegExp('\/([^\/]+)\/tags\/[^\/]+')
  1365.         for (var n=0; n<nodes.length; n++) {
  1366.         var node = nodes[n];
  1367.             if (!node || !node.href) continue;
  1368.         var styles = 0;
  1369.             var iH = node.innerHTML;
  1370.              if (isSearch.test(iH)) {
  1371.          styles = { color: 'green', fontWeight: 'bold', border:'solid green 1px' };
  1372.          } else if (isTag.test(iH)) {
  1373.          mat  = iH.match(isTag);
  1374.          styles = { fontWeight : 'bold', color: mat[1] == 'photos' ? 'purple' : 'blue' };
  1375.          } else if (isGroup.test(iH)) {
  1376.          styles = { fontWeight : 'bold', color: 'orange' };
  1377.          } else if (isSet.test(iH)) {
  1378.          styles = { fontWeight : 'bold', color: '#f0f' };
  1379.          }
  1380.         if (!styles) continue;
  1381.         for (var s in styles) {
  1382.             node.style[ s ] = styles[s];
  1383.         }
  1384.         }
  1385.     },
  1386.     findMultiPost: function () {
  1387.         // Only relevant for group photo pools:
  1388.         if (this.env.pageView != 'Pool' ) return;
  1389.         // Find users that have posted more than one photo on the current page
  1390.         var struct = new Object();
  1391.         // Scan all 'user photo links' - as found by registerUserPhoto()
  1392.         var arr  = this.liveUserPhotoList();
  1393.         var pool = this.objects.poolImages = new Object();
  1394.         for (var i=0; i < arr.length; i++) {
  1395.             var el  = arr[i];
  1396.             var par = el.parentNode;
  1397.             // Only take note of links inside a PoolList classed object
  1398.             if (par.className != 'PoolList') continue;
  1399.             var pid = this.imageIdFromNode(par);
  1400.             if (pid) pool[pid] = par;
  1401.             var purl   = this.privateHash(el, 'purl');
  1402.             if (!struct[purl]) {
  1403.                 // Initiate data stucture for this user
  1404.                 struct[purl] = {
  1405.                     pars: new Array(),
  1406.                     name: this.privateHash(el, 'dispid'),
  1407.                 };
  1408.             }
  1409.             struct[purl].pars.push( par );
  1410.         }
  1411.         var pcount = 0; // Total thumbnails on the page
  1412.         var ucount = 0; // Total unique users on the page
  1413.         var multi = new Array();
  1414.         // Now look at each unique user
  1415.         for (var purl in struct) {
  1416.             ucount++;
  1417.             var pars  = struct[purl].pars;
  1418.             var count = pars.length;
  1419.             pcount   += count;
  1420.             if (count > 1) {
  1421.                 // This user has more than one photo on the page
  1422.                 // Get the user's automatically generated color...
  1423.                 var col  = "rgb("+this.color4string( purl )+")";
  1424.                 // ... and set the background of each thumbnail to that color
  1425.                 if (this.user.colorMult == 1) {
  1426.                     for (var p=0; p < pars.length; p++) {
  1427.                         pars[p].style.backgroundColor = col;
  1428.                     }
  1429.                 }
  1430.                 var name = struct[purl].name;
  1431.                 // Now make a summary token to put at the top of the
  1432.                 // page - we will have a link that will be activated
  1433.                 // as a pop up:
  1434.                 var link = document.createElement('a');
  1435.                 link.href = "/photos/" + purl +"/";
  1436.                 link.innerHTML = name;
  1437.                 this.registerUserPhoto(link);
  1438.                 // ... which will be held in a span that will have the
  1439.                 // user's auto-color:
  1440.                 var span = document.createElement('span');
  1441.                 span.innerHTML = "<b>"+count+":</b>&nbsp;";
  1442.                 span.appendChild(link);
  1443.                 span.style.backgroundColor = col;
  1444.                 // Store in array for later sorting:
  1445.                 multi.push( [count, span ] );
  1446.             }
  1447.         }
  1448.         // If all images are singletons, return with no action:
  1449.         if (multi.length < 1) return;
  1450.         // Also exit if the user does not want a summary
  1451.         if (this.user.sumMult != 1) return;
  1452.         // Sort the users high-to-low:
  1453.         multi = multi.sort( function (a,b) { return b[0] - a[0]; } );
  1454.         // Slap in the little spans under the Main div:
  1455.         var target  = document.getElementById(this.fids.main);
  1456.         for (var m=0; m < multi.length; m++) {
  1457.             target.parentNode.insertBefore(multi[m][1],target);
  1458.         }
  1459.         // Generate a summary of how many users are unique:
  1460.         var divId = 'CatFlickrSuiteMultiDiv';
  1461.         var div = document.getElementById(divId);
  1462.         if (!div) {
  1463.             div = document.createElement('div');
  1464.             div.id = divId;
  1465.         }
  1466.         var uperc = Math.floor(100 * ucount / pcount);
  1467.         div.innerHTML = "<b>"+ucount + "</b> users = <b>"+uperc+"%</b> of maximum";
  1468.         target.parentNode.insertBefore(div,target);
  1469.     },
  1470.     getAllComments: function () {
  1471.         // Only relevant for group photo pools:
  1472.         if (this.env.pageView != 'Pool' ) return;
  1473.         // Do nothing if the user has requested so:
  1474.         if (this.user.getCom != 1) return;
  1475.         var pool = this.objects.poolImages;
  1476.         this.objects.comments = new Object();
  1477.         this.objects.shownComments = new Object();
  1478.         for (var pid in pool) {
  1479.             var ticket = this.requestImageComments( pid );
  1480.         }
  1481.     },
  1482.     imageIdFromNode: function(el) {
  1483.         var focus = el;
  1484.         while (!focus.href || !/\/photos\/[^\/]+\/\d+/.test(focus.href)) {
  1485.             if (focus.hasChildNodes()) {
  1486.                 focus = focus.firstChild;
  1487.             } else if (focus.nextSibling) {
  1488.                 focus = focus.nextSibling;
  1489.             } else {
  1490.                 // Failed to find image link
  1491.                 focus = null; break;
  1492.             }
  1493.         }
  1494.         var id;
  1495.         if (focus && focus.href) {
  1496.             var hits = focus.href.match( this.re.photoID );
  1497.             if (hits) id = hits[2];
  1498.         }
  1499.         return id;
  1500.     },
  1501.     requestImageComments: function( id ) {
  1502.         if (!id) return;
  1503.         // If we have already recovered comments for this id, do not do so again:
  1504.         if (!this.doneTask.getComments) this.doneTask.getComments = new Object();
  1505.         if (this.doneTask.getComments[ id ]++) return true;
  1506.         var tkey = 'getComments';
  1507.         // Set up ticket status queue if needed
  1508.         if (!this.ticketStatus[tkey]) this.ticketStatus[tkey] = new Object();
  1509.         return this.flickrApi
  1510.         ( { method: 'flickr.photos.comments.getList', photo_id: id },
  1511.           'ricCB', {ticktype: tkey} );
  1512.     },
  1513.     ricCB: function(rsp) {
  1514.         var hash = this.objects.comments;
  1515.         for each (comments in rsp.comments) {
  1516.             // for (var cs = 0; cs < rsp.comments.length; cs++) {
  1517.             // var comments = rsp.comments[cs];
  1518.             var pid  = comments['@photo_id'];
  1519.             for each (com in comments.comment) {
  1520.                 var uname  = com['@authorname'];
  1521.                 var nsid   = com['@author'];
  1522.                 this.setTranslation( { uname: uname, nsid: nsid } );
  1523.                 // var create = new Date( com.@datecreate );
  1524.                 var ctxt  = com + '';
  1525.                 // Strip out HTML tags:
  1526.                 ctxt = ctxt.replace(/(\<|\&lt\;).+?(\>|\&gt\;)/g,'');
  1527.                 // Collapse all whitespace runs to single spaces:
  1528.                 ctxt = ctxt.replace(/[\s\n\r\t]+/g, ' ');
  1529.                 if (/^\s*$/.test(ctxt)) ctxt = "HTML only" ;
  1530.                 // Store data under both authorname and photo ID (hash
  1531.                 // will collide only if someone is using a pure
  1532.                 // integer as a name AND a photo has same integer).
  1533.                 var info = { txt: ctxt, uname: uname, photo: pid };
  1534.                 if (!hash[uname]) hash[uname] = new Array();
  1535.                 if (!hash[pid])   hash[pid]   = new Array();
  1536.                 hash[uname].push(info);
  1537.                 hash[pid].push(info);
  1538.             }
  1539.         }
  1540.         this.msg();
  1541.     },
  1542.     checkClickEvent: function(evt) {
  1543.         if (!evt) {
  1544.             GM_log("Click event fails to pass the event object!");
  1545.             return false;
  1546.         }
  1547.         if (evt.which != 1) return false; // Only consider for left button
  1548.         var el = evt.target;
  1549.         while (1) {
  1550.             if (el.getAttribute && el.getAttribute('userPhoto')) {
  1551.                 // This is a link to a user photo stream
  1552.                 return this.userPhotoClick(el, evt);
  1553.             }
  1554.             if (!el.parentNode) break;
  1555.             el = el.parentNode;
  1556.         }
  1557.         // GM_log("Click on "+el+" deemed not a user photo link");
  1558.         return false;
  1559.     },
  1560.     registerUserPhoto: function(el) {
  1561.         // Take a link with target '/photos/USERID/' and add pop-up
  1562.         // functionality to it. This method also stores the link in an
  1563.         // internal structure
  1564.         var purl = this.isUserPhoto(el);
  1565.         if (!purl) return 0;
  1566.         var dispid  = el.text;
  1567.         if (this.privateHash(el, 'parsed')) return dispid;
  1568.         // Ok, this looks like the sort of link we want to modify
  1569.         // (and have not already done so)
  1570.         this.privateHash(el, 'purl', purl);
  1571.         this.privateHash(el, 'dispid', dispid);
  1572.         this.privateHash(el, 'parsed', true);
  1573.         this.setTranslation( { dispid: dispid, purl: purl } );
  1574.         el.setAttribute('userPhoto', dispid);
  1575.         return dispid;
  1576.     },
  1577.     insertSettings: function() {
  1578.         // Add a settings menu
  1579.         var targ = document.getElementById(this.fids.navOrg);
  1580.         if (!targ) {
  1581.             GM_log("Failed to find 'Organize' menu item for settings");
  1582.             return;
  1583.         }
  1584.         var liL  = document.createElement('li');
  1585.         var setL = document.createElement('a');
  1586.         setL.href = "javascript:void(0)";
  1587.         setL.innerHTML = "Flickr Suite Settings";
  1588.         setL.addEventListener('click', function (e) {
  1589.             return CatFlickrSuite.settingsClick(this, e);}, false);
  1590.         liL.appendChild(setL);
  1591.         targ.appendChild(liL);
  1592.     },
  1593.     settingsClick: function (el, evt) {
  1594.         var items = new Array();
  1595.  
  1596.        items.push("<span class='CancelButt'>[x]</span>&nbsp;"+
  1597.                    "<span style='font-weight:bold;color:blue'>"+
  1598.                    "Flickr Suite GreaseMonkey Settings</span>");
  1599.         for (var type in this.userSet) {
  1600.             // Cycle through each data type
  1601.             var info = this.userSet[type];
  1602.             if (type == 'checkbox') items.push( "<b>Active Suite Functions:</b>" );
  1603.             for (var tag in info) {
  1604.                 var val  = this.user[tag];
  1605.                 var desc = info[tag][0];
  1606.                 var inpt = { tag: 'input', type: type, id: 'CFS'+tag };
  1607.                 if (type == 'checkbox') {
  1608.                     inpt.text = desc;
  1609.                     if (val == 1) inpt.checked = 'checked';
  1610.                 } else if (type == 'text') {
  1611.                     inpt.text  = desc;
  1612.                     inpt.value = val;
  1613.                     inpt.size  = 5;
  1614.                 } else if (type == 'textarea') {
  1615.                     delete inpt.type;
  1616.                     inpt.tag  = type;
  1617.                     inpt.cols = 30;
  1618.                     inpt.rows = 10;
  1619.                     inpt.pre  = "<b>"+desc+":</b><br />";
  1620.                     inpt.text = val;
  1621.                 }
  1622.                 items.push(inpt);
  1623.             }
  1624.         }
  1625.         items.push( "<i>Close menu, then <b>reload page</b> to see changes</i>" );
  1626.         items.push({ pre: "Check ", post: " for updates to this suite", text: 'userscripts.org', target:'userscripts', href: 'http://userscripts.org/scripts/show/5016', });
  1627.         var html;
  1628.         try {
  1629.             // Some weirdness during development, so be safe in a try/catch
  1630.             html = this.makeMenu( items );
  1631.         } catch(e) {
  1632.             this.err("Failed to make settings menu for ", e);
  1633.             return false;
  1634.         }
  1635.         // Pop up the window
  1636.         var div = this.popUp(el, html, evt);
  1637.         this.privateHash(div, 'onclose', function() {
  1638.                 CatFlickrSuite.updateSettings();
  1639.             } );
  1640.         return false;
  1641.     },
  1642.     updateSettings: function (el) {
  1643.         // Note that we have succesfully gotten to the callback
  1644.         this.privateHash(el, 'onclose', false );
  1645.         // Scan all user configurable settings, put values in GreaseMonkey persistant store
  1646.         var uarr = this.userSetArr;
  1647.         for (var u=0; u < uarr.length; u++) {
  1648.             var type = uarr[u][0];
  1649.             var tag  = uarr[u][1];
  1650.             var inpt = document.getElementById('CFS' + tag);
  1651.             if (!inpt) continue;
  1652.             var val;
  1653.             if (type == 'checkbox') {
  1654.                 // Data in checkboxes
  1655.                 val = (inpt.checked) ? 1 : 0;
  1656.             } else {
  1657.                 val = inpt.value;
  1658.             }
  1659.             GM_setValue(tag , val);
  1660.         }
  1661.         // Reparse all user settings
  1662.         this.setSettings();
  1663.     },
  1664.     updateUser: function (el) {
  1665.         // Note that we have succesfully gotten to the callback
  1666.         this.privateHash(el, 'onclose', false );
  1667.         var purl    = this.privateHash(el, 'purl');
  1668.         var setCol = document.getElementById(this.fids.csfCols);
  1669.         if (setCol) {
  1670.             // There is a list of colors attributed to this user
  1671.             var kids = setCol.childNodes;
  1672.             var setCols = new Array();
  1673.             for (var k=0; k < kids.length; k++) {
  1674.                 var col = kids[k].getAttribute('colName');
  1675.                 if (col) setCols.push(col);
  1676.             }
  1677.             GM_setValue("UserColor"+purl, setCols.join(" "));
  1678.         }
  1679.         // Re-color any user links
  1680.         this.colorUserPhotos( purl );
  1681.     },
  1682.     color4string: function( txt ) {
  1683.         // This method takes a string (for example a user ID) and
  1684.         // converts it to a reproducible RGB color. There are probably
  1685.         // more elegant ways to do this (I'd like to know of them) -
  1686.         // the basic goal is to get good spread of the color spectrum,
  1687.         // without being too dark or too light, and avoiding gray
  1688.         // scales.
  1689.         // Make a string that's just the concatenation of all the decimal ascii codes:
  1690.         var hash = "";
  1691.         for (var j = 0; j < txt.length; j++) {
  1692.             var code = txt.charCodeAt(j);
  1693.             hash    += code.toString();
  1694.         }
  1695.         var col     = new Array();
  1696.         var colMv   = 0;
  1697.         // Break the long integer into three equal sized pieces:
  1698.         var block   = Math.floor(hash.length/3);
  1699.         var colSpan = this.colMax - this.colMin + 1;
  1700.         var colBuf  = this.colBuf;
  1701.         if (colBuf > colSpan / 4) colBuf = Math.floor(colSpan / 4);
  1702.         for (var b = 0; b < 3; b++) {
  1703.             var si   = b * block;
  1704.             var subh = hash.substring( si, si + block - 1 );
  1705.             // Turn the sub-hash into colMin-colMax (modulus colSpan)
  1706.             var val = this.colMin + ((parseInt(subh) * 7353) % colSpan);
  1707.             for (var c = 0; c < b; c++) {
  1708.                 // make sure this color value is far enough from the prior ones
  1709.                 var pval = col[c];
  1710.                 if (val > pval - this.colBuf && val < pval + this.colBuf) {
  1711.                     // This color index is too close to another
  1712.                     if (colMv == 0) colMv = (val < pval) ? -1 : 1;
  1713.                     if (colMv > 0) {
  1714.                         val = pval + this.colBuf;
  1715.                         if (val > this.colMax) val -= colSpan;
  1716.                     } else {
  1717.                         val = pval - this.colBuf;
  1718.                         if (val < this.colMin) val += colSpan;
  1719.                     }
  1720.                 }
  1721.             }
  1722.             col.push(val);
  1723.         }
  1724.         // Now finally rotate the three colors
  1725.         var rot = parseInt(hash) %3;
  1726.         for (var r = 0; r < rot; r++) {
  1727.             col.push( col.shift() );
  1728.         }
  1729.         return col;
  1730.     },
  1731.     popUp: function (el, html, evt) {
  1732.         // Popup a mini menu on a mouse click
  1733.         var div = document.getElementById(this.fids.csfPop);
  1734.         if (!div) {
  1735.             // Create the object once, then keep it
  1736.             div = document.createElement('div');
  1737.             div.id = this.fids.csfPop;
  1738.             div.className = 'ToolTip';
  1739.             div.style.zIndex = '9999';
  1740.             document.body.appendChild(div);
  1741.             // Using an event listener to monitor activity on our popup
  1742.             div.addEventListener('click', function (e) {
  1743.                     return CatFlickrSuite.popClick(e);
  1744.                 }, false);
  1745.         } else {
  1746.             // We are recycling the same object as the popup (so only
  1747.             // one popup allowed at a time). Registration of user
  1748.             // changes in the popup occurs when the user closes the
  1749.             // window - make sure that if the window was not
  1750.             // explicitly closed (that is, it is open in another
  1751.             // location) that we still save the user settings:
  1752.             var cb = this.privateHash(div, 'onclose');
  1753.             if (cb) cb( div );
  1754.         }
  1755.         // Position div under click (-15 offset attempts to get close box under mouse)
  1756.         div.style.top     = (evt.pageY - 15) + 'px';
  1757.         div.style.left    = (evt.pageX - 15) + 'px';
  1758.         // Update content:
  1759.         div.innerHTML     = html;
  1760.         // Make sure it is visible:
  1761.         div.style.display = 'block';
  1762.         // clear any private variables associated with the popup
  1763.         this.clearPrivate(div);
  1764.         return div;
  1765.     },
  1766.     popClick: function (e) {
  1767.         // Respond to a click event in our popup
  1768.         if (!e || !e.originalTarget) return;
  1769.         var targ  = e.originalTarget;
  1770.         var par   = targ.parentNode;
  1771.         var cname = targ.className;
  1772.         while (!cname && par) {
  1773.             // Back out of DOM tree until we find a classed target
  1774.             targ  = par;
  1775.             par   = targ.parentNode;
  1776.             cname = targ.className;
  1777.         }
  1778.         if (!par || !cname) return;
  1779.         if (cname == 'CancelButt') {
  1780.             // A click within a close button [x] - hide the popup
  1781.             this.popClose(par);
  1782.         } else if (cname == 'CloseComment') {
  1783.             this.toggleComments(par);
  1784.         } else if (cname == 'SetColor') {
  1785.             // A click within a 'set user color' selection
  1786.             var addTo = document.getElementById
  1787.             (par.id == this.fids.csfCols ? this.fids.csfAvl : this.fids.csfCols);
  1788.             if (!addTo) return;
  1789.             addTo.appendChild(targ);
  1790.         } else if (cname == 'ShowComments') {
  1791.             this.toggleComments(par);
  1792.         }
  1793.     },
  1794.     toggleComments: function (el) {
  1795.         var dispid = this.registerUserPhoto(el);
  1796.         var uname  = this.getTranslation(dispid, 'uname');
  1797.         if (!uname) return;
  1798.         var coms   = this.objects.comments[uname];
  1799.         if (!coms) return;
  1800.         var list  = this.objects.shownComments[uname];
  1801.         if (list) {
  1802.             // Already showing comments - hide them
  1803.             for (var l=0; l < list.length; l++) {
  1804.                 var el = list[l];
  1805.                 el.parentNode.removeChild(el);
  1806.             }
  1807.             this.objects.shownComments[uname] = null;
  1808.             return;
  1809.         }
  1810.         list = this.objects.shownComments[uname] = new Array();
  1811.         var struct = new Object();
  1812.         for (var i=0; i < coms.length; i++) {
  1813.             var info = coms[i];
  1814.             var pid  = info.photo;
  1815.             if (!struct[pid]) struct[pid] = new Array();
  1816.             struct[pid].push( info.txt );
  1817.         }
  1818.         var pool = this.objects.poolImages;
  1819.         var purl  = this.privateHash(el, 'purl');
  1820.         var col  = "rgb("+this.color4string( purl )+")";
  1821.         var elips = "<span style='color:red;font-weight:bold'>&hellip;</span>";
  1822.         for (var pid in struct) {
  1823.             var targ = pool[pid];
  1824.             if (!targ) {
  1825.                 this.err("Could not find pool image ID="+pid);
  1826.                 continue;
  1827.             }
  1828.             var html = "<span style='color:red;background-color:yellow' class='CloseComment'>["+dispid+"]</span>";
  1829.             var maxlen = this.user.comWidth;
  1830.             for (var c=0; c < struct[pid].length; c++) {
  1831.                 // If there are multiple comments, separate them by
  1832.                 // slightly differnt background colors
  1833.                 var com = struct[pid][c];
  1834.                 if (maxlen > 0 && com.length > maxlen) com = com.substr(0,maxlen) + elips;
  1835.                 html += "<span style='background-color:"+( c%2 ? '#cfc' : '#9f9')+"'>"+com+"</span>";
  1836.             }
  1837.             var el = document.createElement('div');
  1838.             el.innerHTML = html;
  1839.             targ.appendChild(el);
  1840.             el.style.fontSize  = this.user.comSize;
  1841.             el.style.border    = col+" solid 1px";
  1842.             el.style.textAlign = 'left';
  1843.             el.style.zIndex   = 100;
  1844.             el.style.position = 'relative';
  1845.             el.style.left     = '-4px';
  1846.             el.style.width    = '118px';
  1847.             el.className      = "CommentBox";
  1848.             this.privateHash(el, 'dispid', dispid);
  1849.             list.push(el);
  1850.             el.addEventListener('click', function (e) {
  1851.                     return CatFlickrSuite.popClick(e);
  1852.                 }, false);
  1853.             //targ.style.height = "100%";
  1854.         }
  1855.     },
  1856.     popClose: function (el) {
  1857.         // Does the window have a callback associated with it?
  1858.         var cb = this.privateHash(el, 'onclose');
  1859.         if (cb) cb( el );
  1860.         // Set display to none to hide menu
  1861.         el.style.display = 'none';
  1862.     },
  1863.     makeMenu: function( arr ) {
  1864.         // Build a little menu given an array of 'lines'
  1865.         if (!arr || arr.length < 1) return "";
  1866.         var lines = new Array();
  1867.         try {
  1868.             for (var i=0; i < arr.length; i++) {
  1869.                 var info = arr[i];
  1870.                 if (typeof(info) == 'string') {
  1871.                     // If this entry is a simple string, use it as is
  1872.                     lines.push(info);
  1873.                     continue;
  1874.                 }
  1875.                 // Otherwise, assume it is an object that will be turned
  1876.                 // into a tag, with keys being attribute names. The
  1877.                 // 'text' attribute is taken as the link text:
  1878.                 var tag = info.tag;
  1879.                 if (!tag || tag == '') tag = 'a';
  1880.                 var txt = ">"+info.text+"</"+tag+">";
  1881.                 // Free text to put after the link
  1882.                 if (info.post) txt += info.post;
  1883.                 // Remove special attrs so they do not become an part of the tag
  1884.                 delete info.tag; delete info.post; delete info.text;
  1885.                 var attrs = new Array();
  1886.                 for (var attr in info) {
  1887.                     var val = info[attr];
  1888.                     if (!val) val = "";
  1889.                     // Escape single quotes
  1890.                     if (typeof(val) == 'string') val = val.replace("'", "\\'");
  1891.                     attrs.push(attr+"='"+val+"'");
  1892.                 }
  1893.                 txt = "<"+tag+" "+attrs.join(' ')+txt;
  1894.                 if (info.pre) txt = info.pre + txt;
  1895.                 // Join all attributes into an anchor tag
  1896.                 lines.push(txt);
  1897.             }
  1898.         } catch (e) {
  1899.             this.err("Failed to make menu for "+arr.length+" items", e);
  1900.             return "";
  1901.         }
  1902.         // Join all lines into a single block of text
  1903.         return lines.join("<br />\n");
  1904.     },
  1905.     hashToLog: function (obj, title) {
  1906.         var msg = "Hash report for "+obj+":\n";
  1907.         if (title) msg += title + "\n";
  1908.         if (obj) {
  1909.             var num = 0;
  1910.             for (var key in obj) {
  1911.                 msg += key + ": "+obj[key]+"\n";
  1912.                 num++;
  1913.             }
  1914.             msg += num + " key"+(num == 1 ? '' : 's')+"\n";
  1915.         } else {
  1916.             msg += "/null/\n";
  1917.         }
  1918.         GM_log(msg);
  1919.     },
  1920.     valuesForNamedInput: function(form, name) {
  1921.         /* Huh. It used to work that if I had an <input> named 'foo' in a form
  1922.            represented by object bar, I could get it with bar.foo, but
  1923.            not anymore... */
  1924.         var rv = new Array();
  1925.         if (!form || !form.elements || !name) return null;
  1926.         name = name.toLowerCase();
  1927.         for (var e = 0; e < form.elements.length; e++) {
  1928.             var inp = form.elements[e];
  1929.             if (inp.name.toLowerCase() != name) continue;
  1930.             rv.push(inp.value);
  1931.         }
  1932.         return rv;
  1933.     },
  1934.     privateHash: function(el, tag, val) {
  1935.         // Private hash holding tag / value pairs on HTML elements
  1936.         // The function is both a setter and a getter
  1937.         var key = this.setElementId(el);
  1938.         if (!key || !tag)  return null;
  1939.         // Initialize the hash if this is the first access on the element:
  1940.         if (!this.privateData[key]) {
  1941.             // this.gmMsg += "Establish new private data for " + key+"\n";
  1942.             this.privateData[key] = new Object();
  1943.         }
  1944.         tag = tag.toLowerCase();
  1945.         if (val != null) {
  1946.             // Request to set the value
  1947.             this.privateData[key][tag] = val;
  1948.             // this.gmMsg += "Set "+tag+"="+val+" for " + key+"\n";
  1949.         }
  1950.         // Return the current value
  1951.         return this.privateData[key][tag];
  1952.     },
  1953.     logPrivateData: function( hash ) {
  1954.         if (!hash) hash = this.privateData;
  1955.         var txt = "Hash dump for " + hash + "\n";
  1956.         for (var key in hash) {
  1957.             txt += "["+key+"]\n";
  1958.             var kh = hash[key];
  1959.             if (typeof(kh) == 'object') {
  1960.                 for (var tag in kh) {
  1961.                     txt += "  ["+tag+"] = '"+kh[tag]+"'\n";
  1962.                 }
  1963.             } else {
  1964.                 txt += "  !! Hash expected, found '"+kh+"'\n";
  1965.             }
  1966.         }
  1967.         GM_log(txt);
  1968.     },
  1969.     setTranslation: function (data, debugMsg) {
  1970.         // Are any other data associated with these?
  1971.         for (var type in data) {
  1972.             var existing = this.translate[ data[type] ];
  1973.             if (existing) {
  1974.                 // One of these values is already recorded
  1975.                 var novel = this.mergeHash( existing, data );
  1976.                 if (novel == 0) {
  1977.                     // No new additions to the tranlsation hash:
  1978.                     return;
  1979.                 }
  1980.                 data = existing;
  1981.                 break;
  1982.             }
  1983.         }
  1984.         // If uname is not set it is the same as the display ID, if it is not elipsed
  1985.         if (!data.uname && data.dispid &&
  1986.             !this.re.elipsed.test(data.dispid)) data.uname = data.dispid;
  1987.         // We can generally get the username from the displayed ID
  1988.         if (!data.dispid && data.uname) {
  1989.             // I *THINK* 20 is the upper limit... ?
  1990.             if (data.uname < 20) {
  1991.                 data.dispid = uname;
  1992.             } else {
  1993.                 // Hmm...
  1994.             }
  1995.         }
  1996.         // Cycle through the hash again, update all keys in translation to point to same hash:
  1997.         for (var type in data) {
  1998.             if (debugMsg) this.gmMsg += type + " = " + data[type] + "\n";
  1999.             this.translate[data[type]] = data;
  2000.         }
  2001.     },
  2002.     getTranslation: function( term, type ) {
  2003.         var thash = this.translate;
  2004.         var data  = (term in thash) ? thash[term] : null;
  2005.         if (!data) return null; // Nothing at all found
  2006.         if (!type) return data; // The user wants the full hash
  2007.         // Specific term type requested for return
  2008.         if (type in data) return data[type]; // That type is present, return it
  2009.         // We found data, but no match for this type
  2010.         if ('dispid' in data && !('uname' in data) &&  this.re.elipsed.test(term)) {
  2011.             // The query term is an elipsed display id, which does not
  2012.             // yet have a true uname associated with it - see if we
  2013.             // can find a match to a username
  2014.             var elipre  = this.re.elipsed;
  2015.             // Thanks to John Carney for pointing out that I need to
  2016.             // escape RE tokens in the username when building this
  2017.             // regexp. I miss \Q..\E in perl!
  2018.             var matcher = new RegExp(term.replace(elipre,'').
  2019.                                      replace(/([(){}.^$*?+\[\]\\])/g, '\\$1')+'.+$');
  2020.             for (var tag in thash) {
  2021.                 // Ignore if this tag does not match, or is itself
  2022.                 // elipsed, or the matched hash does not have a
  2023.                 // username defined.
  2024.                 if (!matcher.test(tag) || elipre.test(tag) ||
  2025.                     !('uname' in thash[tag])) continue;
  2026.                 // We have a match - combine the two hashes
  2027.                 this.mergeHash(data, thash[tag]);
  2028.                 this.setTranslation(data);
  2029.                 if (type in data) return data[type];
  2030.             }
  2031.         }
  2032.         return null;
  2033.     },
  2034.     mergeHash: function(hashA, hashB) {
  2035.         // Adds the key/val pairs of hashB to hashA
  2036.         var newVals = 0;
  2037.         for (var tag in hashB) {
  2038.             if (!(tag in hashA)) { hashA[tag] = hashB[tag]; newVals++; }
  2039.         }
  2040.         return newVals;
  2041.     },
  2042.     setElementId: function(el) {
  2043.         if (!el) return null;
  2044.         if (!el.id) {
  2045.             // this.gmMsg += "New ID added to " + el + "\n";
  2046.             el.id = "CFS" + "_" + this.ms + '_' + ++this.counter;
  2047.         }
  2048.         return el.id;
  2049.     },
  2050.     clearPrivate: function(el) {
  2051.         // Clear out private variables associated with an element
  2052.         if (!el) return;
  2053.         var key = this.setElementId(el);
  2054.         var rv  = this.privateData[key];
  2055.         // Totally wipe the settings:
  2056.         // this.gmMsg += "Clearing private data for " +key+"\n";
  2057.         this.privateData[key] = new Object();
  2058.         return rv; // Return the old settings
  2059.     },
  2060.     buildGetString: function (args, noToken) {
  2061.         delete args[ "api_sig" ];
  2062.         if (unsafeWindow.global_auth_hash) {
  2063.             // I believe this is the old authentication?
  2064.             args[ "auth_hash" ] = unsafeWindow.global_auth_hash;
  2065.         } else {
  2066.             delete args[ "auth_hash" ];
  2067.         }
  2068.         // Always add the api_key:
  2069.         args[ "api_key" ] = this.apikey;
  2070.         // Add the auth token if it is available
  2071.         if (this.authTok) args[ "auth_token" ] = this.authTok;
  2072.         // if (!noToken && ! args['frob']) args[ "auth_token" ] = this.getAuthToken();
  2073.  
  2074.         // Sort all the parameter names:
  2075.         var argList  = new Array();
  2076.         for (var arg in args) { argList.push( arg ); }
  2077.         argList = argList.sort();
  2078.         // Build the basic parameter list
  2079.         var get = "";
  2080.         for (var al = 0; al < argList.length; al++) {
  2081.             var arg = argList[al];
  2082.             var val = args[arg];
  2083.             if (val == null) continue;
  2084.             if (get) get += "&";
  2085.             get += arg + "=" + val;
  2086.             sig += arg + val;
  2087.         }
  2088.         var signIt = args['auth_token'] || args['frob'] ? 1 : 0;
  2089.         if (signIt) {
  2090.             // We also need to sign the GET parameters
  2091.             var sig = this.getSecKey();
  2092.             for (var al = 0; al < argList.length; al++) {
  2093.                 var arg = argList[al];
  2094.                 var val = args[arg];
  2095.                 if (val == null) continue;
  2096.                 sig += arg + val;
  2097.             }
  2098.             // MD5 the signature string and append as a new parameter:
  2099.             var md5 = hex_md5(sig);
  2100.             get += "&api_sig="+md5;
  2101.         }
  2102.         return get;
  2103.     },
  2104.     getSecKey : function () {
  2105.         return this.seckey;
  2106.     },
  2107.     getAuthToken : function () {
  2108.         if (this.authTok) return this.authTok;
  2109.         // Try to get token from local store:
  2110.         this.authTok = GM_getValue("FlickrAuthTok");
  2111.         if (this.authTok) {
  2112.             GM_log("Authorization token recovered from local storage - " + this.authTok);
  2113.             return this.authTok;
  2114.         }
  2115.         // Need to generate new token:
  2116.         return this.frobToAuth();
  2117.     },
  2118.     frobToAuth: function () {
  2119.         var frob = this.getFrob();
  2120.         this.flickrApi( { method: "flickr.auth.getToken", frob: frob }, 'parseAuth' );
  2121.         return this.authTok;
  2122.     },
  2123.     parseAuth: function (rsp) {
  2124.         var toks = new Array();
  2125.         for each (auth in rsp.auth) {
  2126.            for each (tok in auth.token) {
  2127.                var token = tok + "";
  2128.                if (token) toks.push(token);
  2129.            }
  2130.         }
  2131.         if (toks.length == 1) {
  2132.             this.authTok = toks[0];
  2133.             GM_setValue("FlickrAuthTok", toks[0]);
  2134.             GM_log("Authorization token returned by Flickr API");
  2135.         } else {
  2136.             this.err("Failed to recover auth_token");
  2137.         }
  2138.         return this.authTok;
  2139.     },
  2140.     getFrob: function () {
  2141.         if (this.frob) return this.frob;
  2142.         // Try to get frob from local store:
  2143.         this.frob = GM_getValue("FlickrFrob");
  2144.         if (this.frob) {
  2145.             GM_log("Frob recovered from local storage");
  2146.             return this.frob;
  2147.         }
  2148.         // Need to go to authentication page
  2149.         var get = this.buildGetString( { perms: 'write' }, 'NO AUTH' );
  2150.         var url = "http://www.flickr.com/services/auth/?" + get;
  2151.         // Need to open a new page
  2152.         window.open(url, "_blank");
  2153.         var msg = "";
  2154.         if (this.frobTry) msg += "Hm. You have tried "+this.frobTry+
  2155.                               " time(s) but have not authenticated...\n";
  2156.         msg +=
  2157.         "Flicker Functional Suite has opened a new window.\n"+
  2158.         "It will request 'write' permission for your photo stream.\n"+
  2159.         "If you are comfortable with that, please grant permissions\n"+
  2160.         "and close this alert AFTER you grant them.\n"+
  2161.         "If you are not, you may ignore the request, but FFS will not function properly"
  2162.         alert(msg);
  2163.         this.frobTry++;
  2164.         return grabFrob();
  2165.     },
  2166.     grabFrob: function () {
  2167.         var loc = document.location.href;
  2168.         var mat = loc.match(this.re.frob);
  2169.         if (!mat) return;
  2170.         GM_setValue("FlickrFrob", this.frob = mat[1]);
  2171.         GM_log("Frob recognized from Flickr authentication page");
  2172.     },
  2173.     flickrApi: function( args, cbname, cfsArgs ) {
  2174.         /* Generic method for an AJAX call to the Flickr API
  2175.          * cfsArgs
  2176.          *   failok: if true, then still execute the callback when error code encountered
  2177.          */
  2178.         var callback = this[cbname];
  2179.         var get      = this.buildGetString( args );
  2180.         if (!get) {
  2181.             // Failed to build get string. This usually means that authentication is under way
  2182.             // Store the arguments for recovery after
  2183.             return this.delayApi( args, cbname, cfsArgs );
  2184.         }
  2185.  
  2186.         var url = "http://api.flickr.com/services/rest/?" + get;
  2187.  
  2188.         var ticket = ++this.ticket;
  2189.         if (!cfsArgs) cfsArgs = new Object();
  2190.         cfsArgs.ticket = ticket;
  2191.         cfsArgs.url = url;
  2192.         if (cfsArgs.ticktype) {
  2193.             var tkey = cfsArgs.ticktype;
  2194.             if (!this.ticketStatus[tkey]) this.ticketStatus[tkey] = new Object();
  2195.             this.ticketStatus[tkey][ticket] = 'pending';
  2196.         }
  2197.         GM_xmlhttpRequest
  2198.         ({ method: "GET", url: url, headers: {
  2199.             "User-agent": "Mozilla/4.0 (compatible) Greasemonkey (Flickr Functional Suite)",
  2200.                 "Accept": "application/atom+xml,application/xml,text/xml",
  2201.             }, onload: function(rsp) { CatFlickrSuite.parseXML(rsp,cbname,args,cfsArgs, url) } } );
  2202.         return ticket;
  2203.     },
  2204.     delayApi: function ( args, cbname, cfsArgs ) {
  2205.         if (!this.apiDelayStack) this.apiDelayStack = new Array;
  2206.         this.apiDelayStack.push( [ args, cbname, cfsArgs ] );
  2207.         return this.apiDelayStack.length;
  2208.     },
  2209.     resumeApi : function () {
  2210.         var stack = this.apiDelayStack;
  2211.         // Transfer full contents of delayed stack to local array
  2212.         var lStck = new Array();
  2213.         while (stack.length) {
  2214.             lStck.push( stack.shift() );
  2215.         }
  2216.         while (lStck.length) {
  2217.             var dat = lStck.shift();
  2218.             var ticket = this.flickrApi( dat[0], dat[1], dat[2] );
  2219.             GM_log("Resuming API call: "+dat[1]);
  2220.         }
  2221.     },
  2222.     parseXML: function(response, cbname, args,cfsArgs, url) {
  2223.         // Takes an XML response from Flickr services and turns it into a E4X object
  2224.         // http://developer.mozilla.org/presentations/xtech2005/e4x/
  2225.         var txt  = response.responseText;
  2226.         txt      = txt.replace(/\s*\<\?[^\>]+\?\>\s*/g,'');
  2227.         var rsp  = new XML(txt);
  2228.         var stat = rsp['@stat'];
  2229.         var tick = cfsArgs.ticket;
  2230.         var tt   = cfsArgs.ticktype;
  2231.         var rv   = null;
  2232.         if (stat != 'ok') {
  2233.             var msg = "Failed to retrieve Flickr data via API:\n";
  2234.             cfsArgs.error = '|';
  2235.             var seenErrs = new Object();
  2236.             for each (err in rsp.err) {
  2237.                 var ec = err['@code'];
  2238.                 seenErrs[ec] = 1;
  2239.                 msg += "  Error: " +ec+ " = "+err['@msg']+"\n";
  2240.                 // cfsArgs.error += 'id='+args.photo_id+' ';
  2241.                 cfsArgs.error += err['@msg'] + '|';
  2242.             }
  2243.             for (var arg in args) {
  2244.                 msg += "  "+arg+'='+args[arg]+"\n";
  2245.             }
  2246.             msg += "URL: "+ url;
  2247.             if (seenErrs['99']) {
  2248.                 // Insufficient priveleges. We need to start the authentication chain
  2249.                 if (cfsArgs.pendingAuth) {
  2250.                     msg += "\nFAILED PRIOR AUTHENTICATION";
  2251.                 } else {
  2252.                     this.delayApi( args, cbname, cfsArgs );
  2253.                     cfsArgs.error = '[Authenticating...]';
  2254.                     cfsArgs.pendingAuth = 1;
  2255.                     this.getAuthToken();
  2256.                     this.resumeApi();
  2257.                     return '[Authenticating...]';
  2258.                     msg = "Authentication required, attempting to authenticate";
  2259.                 }
  2260.             }
  2261.             this.err(msg);
  2262.             if (tt) this.ticketStatus[tt][tick] = 'failed';
  2263.             if (!cfsArgs.failok) return rv;
  2264.         }
  2265.         try {
  2266.             rv = this[cbname](rsp, args, cfsArgs);
  2267.         } catch (e) {
  2268.             this.err("Failed to execute API callback "+cbname, e);
  2269.             if (tt) this.ticketStatus[tt][tick] = 'failed';
  2270.         }
  2271.         // Remove the ticket from the queue as being completed
  2272.         if (tt) delete this.ticketStatus[tt][tick];
  2273.         return rv;
  2274.     },
  2275.     apiStatus: function(tt) {
  2276.         // Report the status of an API queue
  2277.         if (!(tt in this.ticketStatus)) return "";
  2278.         var struct = new Object();
  2279.         for (var ticket in this.ticketStatus[tt]) {
  2280.             var stat = this.ticketStatus[tt][ticket];
  2281.             if (!struct[ stat ]) struct[ stat ] = 0;
  2282.             struct[ stat ]++;
  2283.         }
  2284.         var list = new Array();
  2285.         for (var stat in struct) {
  2286.             list.push( struct[ stat ] + ' ' + stat);
  2287.         }
  2288.         return list.join(",");
  2289.     },
  2290. };
  2291.  
  2292. // This is the call that starts the ball rolling - it launches the
  2293. // init() method when the page finishes loading:
  2294. window.addEventListener('load', function (e) {CatFlickrSuite.init();}, false);
  2295.  
  2296.  
  2297. /*
  2298.  * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  2299.  * Digest Algorithm, as defined in RFC 1321.
  2300.  * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
  2301.  * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  2302.  * Distributed under the BSD License
  2303.  * See http://pajhome.org.uk/crypt/md5 for more info.
  2304.  */
  2305.  
  2306. /*
  2307.  * Configurable variables. You may need to tweak these to be compatible with
  2308.  * the server-side, but the defaults work in most cases.
  2309.  */
  2310. var hexcase = 0;   /* hex output format. 0 - lowercase; 1 - uppercase        */
  2311. var b64pad  = "";  /* base-64 pad character. "=" for strict RFC compliance   */
  2312.  
  2313. /*
  2314.  * These are the functions you'll usually want to call
  2315.  * They take string arguments and return either hex or base-64 encoded strings
  2316.  */
  2317. function hex_md5(s)    { return rstr2hex(rstr_md5(str2rstr_utf8(s))); }
  2318. function b64_md5(s)    { return rstr2b64(rstr_md5(str2rstr_utf8(s))); }
  2319. function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); }
  2320. function hex_hmac_md5(k, d)
  2321.   { return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
  2322. function b64_hmac_md5(k, d)
  2323.   { return rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
  2324. function any_hmac_md5(k, d, e)
  2325.   { return rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); }
  2326.  
  2327. /*
  2328.  * Perform a simple self-test to see if the VM is working
  2329.  */
  2330. function md5_vm_test()
  2331. {
  2332.   return hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72";
  2333. }
  2334.  
  2335. /*
  2336.  * Calculate the MD5 of a raw string
  2337.  */
  2338. function rstr_md5(s)
  2339. {
  2340.   return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
  2341. }
  2342.  
  2343. /*
  2344.  * Calculate the HMAC-MD5, of a key and some data (raw strings)
  2345.  */
  2346. function rstr_hmac_md5(key, data)
  2347. {
  2348.   var bkey = rstr2binl(key);
  2349.   if(bkey.length > 16) bkey = binl_md5(bkey, key.length * 8);
  2350.  
  2351.   var ipad = Array(16), opad = Array(16);
  2352.   for(var i = 0; i < 16; i++)
  2353.   {
  2354.     ipad[i] = bkey[i] ^ 0x36363636;
  2355.     opad[i] = bkey[i] ^ 0x5C5C5C5C;
  2356.   }
  2357.  
  2358.   var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
  2359.   return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
  2360. }
  2361.  
  2362. /*
  2363.  * Convert a raw string to a hex string
  2364.  */
  2365. function rstr2hex(input)
  2366. {
  2367.   try { hexcase } catch(e) { hexcase=0; }
  2368.   var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  2369.   var output = "";
  2370.   var x;
  2371.   for(var i = 0; i < input.length; i++)
  2372.   {
  2373.     x = input.charCodeAt(i);
  2374.     output += hex_tab.charAt((x >>> 4) & 0x0F)
  2375.            +  hex_tab.charAt( x        & 0x0F);
  2376.   }
  2377.   return output;
  2378. }
  2379.  
  2380. /*
  2381.  * Convert a raw string to a base-64 string
  2382.  */
  2383. function rstr2b64(input)
  2384. {
  2385.   try { b64pad } catch(e) { b64pad=''; }
  2386.   var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2387.   var output = "";
  2388.   var len = input.length;
  2389.   for(var i = 0; i < len; i += 3)
  2390.   {
  2391.     var triplet = (input.charCodeAt(i) << 16)
  2392.                 | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
  2393.                 | (i + 2 < len ? input.charCodeAt(i+2)      : 0);
  2394.     for(var j = 0; j < 4; j++)
  2395.     {
  2396.       if(i * 8 + j * 6 > input.length * 8) output += b64pad;
  2397.       else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
  2398.     }
  2399.   }
  2400.   return output;
  2401. }
  2402.  
  2403. /*
  2404.  * Convert a raw string to an arbitrary string encoding
  2405.  */
  2406. function rstr2any(input, encoding)
  2407. {
  2408.   var divisor = encoding.length;
  2409.   var i, j, q, x, quotient;
  2410.  
  2411.   /* Convert to an array of 16-bit big-endian values, forming the dividend */
  2412.   var dividend = Array(Math.ceil(input.length / 2));
  2413.   for(i = 0; i < dividend.length; i++)
  2414.   {
  2415.     dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
  2416.   }
  2417.  
  2418.   /*
  2419.    * Repeatedly perform a long division. The binary array forms the dividend,
  2420.    * the length of the encoding is the divisor. Once computed, the quotient
  2421.    * forms the dividend for the next step. All remainders are stored for later
  2422.    * use.
  2423.    */
  2424.   var full_length = Math.ceil(input.length * 8 /
  2425.                                     (Math.log(encoding.length) / Math.log(2)));
  2426.   var remainders = Array(full_length);
  2427.   for(j = 0; j < full_length; j++)
  2428.   {
  2429.     quotient = Array();
  2430.     x = 0;
  2431.     for(i = 0; i < dividend.length; i++)
  2432.     {
  2433.       x = (x << 16) + dividend[i];
  2434.       q = Math.floor(x / divisor);
  2435.       x -= q * divisor;
  2436.       if(quotient.length > 0 || q > 0)
  2437.         quotient[quotient.length] = q;
  2438.     }
  2439.     remainders[j] = x;
  2440.     dividend = quotient;
  2441.   }
  2442.  
  2443.   /* Convert the remainders to the output string */
  2444.   var output = "";
  2445.   for(i = remainders.length - 1; i >= 0; i--)
  2446.     output += encoding.charAt(remainders[i]);
  2447.  
  2448.   return output;
  2449. }
  2450.  
  2451. /*
  2452.  * Encode a string as utf-8.
  2453.  * For efficiency, this assumes the input is valid utf-16.
  2454.  */
  2455. function str2rstr_utf8(input)
  2456. {
  2457.   var output = "";
  2458.   var i = -1;
  2459.   var x, y;
  2460.  
  2461.   while(++i < input.length)
  2462.   {
  2463.     /* Decode utf-16 surrogate pairs */
  2464.     x = input.charCodeAt(i);
  2465.     y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
  2466.     if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
  2467.     {
  2468.       x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
  2469.       i++;
  2470.     }
  2471.  
  2472.     /* Encode output as utf-8 */
  2473.     if(x <= 0x7F)
  2474.       output += String.fromCharCode(x);
  2475.     else if(x <= 0x7FF)
  2476.       output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
  2477.                                     0x80 | ( x         & 0x3F));
  2478.     else if(x <= 0xFFFF)
  2479.       output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
  2480.                                     0x80 | ((x >>> 6 ) & 0x3F),
  2481.                                     0x80 | ( x         & 0x3F));
  2482.     else if(x <= 0x1FFFFF)
  2483.       output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
  2484.                                     0x80 | ((x >>> 12) & 0x3F),
  2485.                                     0x80 | ((x >>> 6 ) & 0x3F),
  2486.                                     0x80 | ( x         & 0x3F));
  2487.   }
  2488.   return output;
  2489. }
  2490.  
  2491. /*
  2492.  * Encode a string as utf-16
  2493.  */
  2494. function str2rstr_utf16le(input)
  2495. {
  2496.   var output = "";
  2497.   for(var i = 0; i < input.length; i++)
  2498.     output += String.fromCharCode( input.charCodeAt(i)        & 0xFF,
  2499.                                   (input.charCodeAt(i) >>> 8) & 0xFF);
  2500.   return output;
  2501. }
  2502.  
  2503. function str2rstr_utf16be(input)
  2504. {
  2505.   var output = "";
  2506.   for(var i = 0; i < input.length; i++)
  2507.     output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
  2508.                                    input.charCodeAt(i)        & 0xFF);
  2509.   return output;
  2510. }
  2511.  
  2512. /*
  2513.  * Convert a raw string to an array of little-endian words
  2514.  * Characters >255 have their high-byte silently ignored.
  2515.  */
  2516. function rstr2binl(input)
  2517. {
  2518.   var output = Array(input.length >> 2);
  2519.   for(var i = 0; i < output.length; i++)
  2520.     output[i] = 0;
  2521.   for(var i = 0; i < input.length * 8; i += 8)
  2522.     output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (i%32);
  2523.   return output;
  2524. }
  2525.  
  2526. /*
  2527.  * Convert an array of little-endian words to a string
  2528.  */
  2529. function binl2rstr(input)
  2530. {
  2531.   var output = "";
  2532.   for(var i = 0; i < input.length * 32; i += 8)
  2533.     output += String.fromCharCode((input[i>>5] >>> (i % 32)) & 0xFF);
  2534.   return output;
  2535. }
  2536.  
  2537. /*
  2538.  * Calculate the MD5 of an array of little-endian words, and a bit length.
  2539.  */
  2540. function binl_md5(x, len)
  2541. {
  2542.   /* append padding */
  2543.   x[len >> 5] |= 0x80 << ((len) % 32);
  2544.   x[(((len + 64) >>> 9) << 4) + 14] = len;
  2545.  
  2546.   var a =  1732584193;
  2547.   var b = -271733879;
  2548.   var c = -1732584194;
  2549.   var d =  271733878;
  2550.  
  2551.   for(var i = 0; i < x.length; i += 16)
  2552.   {
  2553.     var olda = a;
  2554.     var oldb = b;
  2555.     var oldc = c;
  2556.     var oldd = d;
  2557.  
  2558.     a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
  2559.     d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
  2560.     c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
  2561.     b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
  2562.     a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
  2563.     d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
  2564.     c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
  2565.     b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
  2566.     a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
  2567.     d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
  2568.     c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
  2569.     b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
  2570.     a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
  2571.     d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
  2572.     c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
  2573.     b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);
  2574.  
  2575.     a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
  2576.     d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
  2577.     c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
  2578.     b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
  2579.     a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
  2580.     d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
  2581.     c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
  2582.     b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
  2583.     a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
  2584.     d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
  2585.     c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
  2586.     b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
  2587.     a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
  2588.     d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
  2589.     c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
  2590.     b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
  2591.  
  2592.     a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
  2593.     d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
  2594.     c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
  2595.     b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
  2596.     a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
  2597.     d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
  2598.     c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
  2599.     b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
  2600.     a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
  2601.     d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
  2602.     c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
  2603.     b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
  2604.     a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
  2605.     d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
  2606.     c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
  2607.     b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
  2608.  
  2609.     a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
  2610.     d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
  2611.     c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
  2612.     b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
  2613.     a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
  2614.     d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
  2615.     c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
  2616.     b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
  2617.     a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
  2618.     d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
  2619.     c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
  2620.     b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
  2621.     a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
  2622.     d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
  2623.     c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
  2624.     b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
  2625.  
  2626.     a = safe_add(a, olda);
  2627.     b = safe_add(b, oldb);
  2628.     c = safe_add(c, oldc);
  2629.     d = safe_add(d, oldd);
  2630.   }
  2631.   return Array(a, b, c, d);
  2632. }
  2633.  
  2634. /*
  2635.  * These functions implement the four basic operations the algorithm uses.
  2636.  */
  2637. function md5_cmn(q, a, b, x, s, t)
  2638. {
  2639.   return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
  2640. }
  2641. function md5_ff(a, b, c, d, x, s, t)
  2642. {
  2643.   return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
  2644. }
  2645. function md5_gg(a, b, c, d, x, s, t)
  2646. {
  2647.   return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
  2648. }
  2649. function md5_hh(a, b, c, d, x, s, t)
  2650. {
  2651.   return md5_cmn(b ^ c ^ d, a, b, x, s, t);
  2652. }
  2653. function md5_ii(a, b, c, d, x, s, t)
  2654. {
  2655.   return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
  2656. }
  2657.  
  2658. /*
  2659.  * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  2660.  * to work around bugs in some JS interpreters.
  2661.  */
  2662. function safe_add(x, y)
  2663. {
  2664.   var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  2665.   var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  2666.   return (msw << 16) | (lsw & 0xFFFF);
  2667. }
  2668.  
  2669. /*
  2670.  * Bitwise rotate a 32-bit number to the left.
  2671.  */
  2672. function bit_rol(num, cnt)
  2673. {
  2674.   return (num << cnt) | (num >>> (32 - cnt));
  2675. }
  2676.  
Add Comment
Please, Sign In to add comment