// PhotoShow Developer Center Common JavaScript Include

// Visible Strings

var tocDocumentInfoTitle = "Document Info"; // Inserted <h2> introducing tags and comments in the TOC

// Configuration Constants

var developerCodeBaseURL = "http://www.photoshow.com/developer/"; // codegens and app config run here


/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////

// The following code is adapted from the book JavaScript: The Definitive Guide, 5th Edition,
// by David Flanagan. Copyright 2006 O'Reilly Media, Inc. (ISBN #0596101996)
// See http://davidflanagan.com/javascript5/ for the original version.

/**
 * getElements(classname, tagname, root):
 * Return an array of DOM elements that are members of the specified class,
 * have the specified tagname, and are descendants of the specified root.
 *
 * If no classname is specified, elements are returned regardless of class.
 * If no tagname is specified, elements are returned regardless of tagname.
 * If no root is specified, the document object is used.  If the specified
 * root is a string, it is an element id, and the root
 * element is looked up using getElementsById()
 */
function getElements(classname, tagname, root) {
    // If no root was specified, use the entire document
    // If a string was specified, look it up
    if (!root) root = document;
    else if (typeof root == "string") root = document.getElementById(root);

    // if no tagname was specified, use all tags
    if (!tagname) tagname = "*";

    // Find all descendants of the specified root with the specified tagname
    var all = root.getElementsByTagName(tagname);

    // If no classname was specified, we return all tags
    if (!classname) return all;

    // Otherwise, we filter the element by classname
    var elements = [];  // Start with an emtpy array
    for(var i = 0; i < all.length; i++) {
        var element = all[i];
        if (isMember(element, classname)) // isMember() is defined below
            elements.push(element);       // Add class members to our array
    }

    // Note that we always return an array, even if it is empty
    return elements;

    // Determine whether the specified element is a member of the specified
    // class.  This function is optimized for the common case in which the
    // className property contains only a single classname.  But it also
    // handles the case in which it is a list of whitespace-separated classes.
    function isMember(element, classname) {
        var classes = element.className;  // Get the list of classes
        if (!classes) return false;             // No classes defined
        if (classes == classname) return true;  // Exact match

        // We didn't match exactly, so if there is no whitespace, then
        // this element is not a member of the class
        var whitespace = /\s+/;
        if (!whitespace.test(classes)) return false;

        // If we get here, the element is a member of more than one class and
        // we've got to check them individually.
        var c = classes.split(whitespace);  // Split with whitespace delimiter
        for(var i = 0; i < c.length; i++) { // Loop through classes
            if (c[i] == classname) return true;  // and check for matches
        }

        return false;  // None of the classes matched
    }
}


/**
 * TOC.js: create a table of contents for a document.
 *
 * This module defines a single maketoc() function and registers an onload
 * event handler so the function is automatically run when the document
 * finishes loading.  When it runs, maketoc() first looks for a document
 * element with an id of "toc". If there is no such element, maketoc() does
 * nothing.  If there is such an element, maketoc() traverses the document
 * to find all <h1> through <h6> tags and creates a table of contents, which
 * it appends to the "toc" element.  maketoc() adds section numbers
 * to each section heading and inserts a link back to the table of contents
 * before each heading.  maketoc() generates links and anchors with names that
 * begin with "TOC", so you should avoid this prefix in your own HTML.
 *
 * The entries in the generated TOC can be styled with CSS.  All entries have
 * a class "TOCEntry".  Entries also have a class that corresponds to the level
 * of the section heading.  <h1> tags generate entries of class "TOCLevel1",
 * <h2> tags generate entries of class "TOCLevel2", and so on.  Section numbers
 * inserted into headings have class "TOCSectNum" and the generated links back
 * to the TOC have class "TOCBackLink".
 *
 * By default, the generated links back to the TOC read "Contents".
 * Override this default (for internationalization, e.g.) by setting
 * the maketoc.backlinkText property to the desired text.
 **/
function maketoc(tocId, rootId, minHLevel, maxHLevel) {
	if (!tocId)
		tocId = 'toc';
	if (!minHLevel)
		minHLevel = 1;
	if (!maxHLevel)
		maxHLevel = 6;

	// Find the container.  If there isn't one, return silently.
    var container = document.getElementById(tocId);
    if (!container) return;

	// Find the root of the DOM subtree to search for headings
	var rootNode = document;
	if (rootId)
		rootNode = document.getElementById(rootId);

	// Traverse the document from the root, adding all <h1>...<h6> tags to an array
	var sections = [];
    findSections(rootNode, sections);

    // Insert an anchor before the container element so we can link back to it
    var anchor = document.createElement("a");  // Create an <a> node
    anchor.name = "TOCtop";                    // Give it a name
    anchor.id = "TOCtop";                      // And an id (IE needs this)
    container.parentNode.insertBefore(anchor, container); // add before toc

    // Initialize an array that keeps track of section numbers
    var sectionNumbers = [0,0,0,0,0,0,0,0,0];

    // Now loop through the section header elements we found
    for(var s = 0; s < sections.length; s++) {
        var section = sections[s];

        // Figure out what level heading it is
        var level = parseInt(section.tagName.charAt(1));
        if (isNaN(level) || level < minHLevel || level > maxHLevel) continue;

        // Increment the section number for this heading level
        // And reset all lower heading level numbers to zero
        sectionNumbers[level-1]++;
        for(var i = level; i < maxHLevel; i++) sectionNumbers[i] = 0;

        // Now combine section numbers for all heading levels
        // to produce a section number like 2.3.1
        var sectionNumber = "";
        for(i = minHLevel - 1; i < level; i++) {
            sectionNumber += sectionNumbers[i];
            if (i < level-1) sectionNumber += ".";
        }

        // Add the section number and a space to the section header title.
        // We place the number in a <span> to make it styleable.
        var frag = document.createDocumentFragment(); // to hold span and space
        var span = document.createElement("span");    // span to hold number
        span.className = "TOCSectNum";                // make it styleable
        span.appendChild(document.createTextNode(sectionNumber)); // add sect#
        frag.appendChild(span);                         // Add span to fragment
        frag.appendChild(document.createTextNode(" ")); // Then add a space
        section.insertBefore(frag, section.firstChild); // Add both to header

        // Create an anchor to mark the beginning of this section.
        var anchor = document.createElement("a");
        anchor.name = "TOC"+sectionNumber;  // Name the anchor so we can link
        anchor.id = "TOC"+sectionNumber;    // In IE generated anchors need ids

		if (maketoc.addBackLinks) {
			// Wrap the anchor around a link back to the TOC
			var link = document.createElement("a");
			link.href = "#TOCtop";
			link.className = "TOCBackLink";
			link.appendChild(document.createTextNode(maketoc.backlinkText));
			anchor.appendChild(link);
		}

        // Insert the anchor and link immediately before the section header
        section.parentNode.insertBefore(anchor, section);

        // Now create a link to this section.
        var link = document.createElement("a");
        link.href = "#TOC" + sectionNumber;   // Set link destination
        link.innerHTML = section.innerHTML;   // Make link text same as heading

        // Place the link in a div that is styleable based on the level
        var entry = document.createElement("div");
        entry.className = "TOCEntry TOCLevel" + level; // For CSS styling
        entry.appendChild(link);

        // And add the div to the TOC container
        container.appendChild(entry);
    }

    // This method recursively traverses the tree rooted at node n, looking
    // for <h1> through <h6> tags and appends them to the sections array.
    function findSections(n, sects) {
        // Loop through all the children of n
        for(var m = n.firstChild; m != null; m = m.nextSibling) {
            // Skip any  nodes that are not elements.
            if (m.nodeType != 1 /* Node.Element_NODE */) continue;
            // Skip the container element since it may have its own heading
            if (m == container) continue;
            // As an optimization, skip <p> tags since headings are not
            // supposed to appear inside paragraphs.  (We could also skip
            // lists, <pre> tags, etc., but <p> is the most common one.)
            if (m.tagName == "P") continue;  // optimization

            // If we didn't skip the child node, check whether it is a heading.
            // If so, add it to the array.  Otherwise, recurse on it.
            // Note that the DOM is interface-based not class-based so we
            // cannot simply test whether (m instanceof HTMLHeadingElement).
            if (m.tagName.length==2 && m.tagName.charAt(0)=="H") sects.push(m);
            else findSections(m, sects);
        }
    }
}

// This is the default text of links back to the TOC
maketoc.backlinkText = "[top]";
maketoc.addBackLinks = false;


// End of code adapted from the book JavaScript: The Definitive Guide, 5th Edition.

/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////


/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

// End of Paul Johnston MD5 implementation

/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////

// PAGE MUCKING

// I'm not at all proud of this code, but there are a large number of Mashery pages
// that need language changes, and that we don't have easy access to modify.

var mucks = [
{
	urlmatch: "^\/docs.*",
	mods:
	[ { // Add a table of contents to the sidebar in every Docs page
		id: "sub",
		callfunction: "insertToc"
	} ]
}, {
	urlmatch: "^\/member\/register.*",
	mods:
	[ { // Change "PhotoShow Registration" to "PhotoShow Developer Registration"
		selector: "h1.first",
		htmlfind: "PhotoShow",
		htmlreplace: "PhotoShow Developer"
	}, { // Change "Register a New Account" to "... New Developer Account"
		selector: "fieldset.fieldset-register_a_new_account legend",
		htmlfind: "New Account",
		htmlreplace: "New Developer Account"
	}, { // Attempt to discourage non-developers looking for support
		selector: "h1.first",
		insertnodeafter: "div",
		innerhtml: '<div style="background-color: #FFFFDD; padding: 1em; border: 2px solid #EC1C24;"><h3>Are you looking for product support?</h3> <p>If you need help using, installing, purchasing, or getting a refund for PhotoShow, <em>you&rsquo;re in the wrong place</em>. We want to help you, but we can&rsquo;t do that here.</p> <ul><li>If you are <em>not a web developer (programmer)</em>, <a href="http://support.photoshow.com">click here to go to our product support site</a>.</li> <li>If you <em>are</em> a developer, please continue with this form. (We just wanted to make sure.)</li></ul></div>'
	}, { // Change confirmation page -- appears under same url
		selector: "div#main p",
		htmlfind: "Thank you for using PhotoShow.",
		htmlreplace: "Thank you for setting up a PhotoShow developer account."
	} ]
}, {
	urlmatch: "^\/member\/confirm.*",
	mods:
	[ { // Change "PhotoShow Registration" to "PhotoShow Developer Registration"
		selector: "h1.first",
		innerhtml: "PhotoShow Developer Registration - Account Created"
	}, { // Change next steps
		selector: "div#main ol",
		replacenode: "ul",
		innerhtml: '<li><a href="/docs/Using_PhotoShow_Tools/Instashow_Widget">Get started in minutes</a> with the PhotoShow instashow widget</li> <li><a href="/docs">Read the detailed API docs</a> to learn about customization options</li> <li><a href="/apps/register">Get a developer key</a> to add authoring and customization</li>'
	}, { // Remove extraneous text
		selector: "div#main",
		htmlfind: "Go to the home page and sign in.",
		htmlreplace: ""
	} ]
}, {
	urlmatch: "^\/apps\/register.*",
	mods:
	[ { // Change "PhotoShow Application Registration" to "PhotoShow Developer Registration"
		selector: "h1.first",
		innerhtml: "PhotoShow Developer Key"
	}, { // Remove the 1.2.3. steps at the top of the page
		id: "step_label",
		display: "none"
	}, { // Remove the 1.2.3. steps at the top of the page
		id: "steps",
		display: "none"
	}, { // Remove "Select which Web Services your application will use"
		selector: "fieldset#step1 dt:first-of-type",
		display: "none"
	}, { // Remove "Select which Web Services your application will use"
		selector: "fieldset#step1 dd:first-of-type",
		display: "none"
	}, { // Auto-check "PhotoShow Developer Tools" box
		id: "qws37bfb6brpfhv4mvm2xdmc",
		setchecked: true
	}, { // Change label of continue button
		id: "continue",
		setvalue: "Proceed to Confirmation & Terms of Service",
		callfunction: "hackAppRegForm"
	} ]
} ];


function muckWithPage(mucks) {
	autoRegistrationIframe();
	for (var mucknum = 0; mucknum < mucks.length; mucknum++) {
		var muck = mucks[mucknum];

		// Does this muck apply to this page?
		var doMuck = false;
		if (muck.urlmatch && (new RegExp(muck.urlmatch, "i")).test(document.location.pathname)) {
			doMuck = true;
		}

		if (doMuck) {
			for (var modnum = 0; modnum < muck.mods.length; modnum++) {
				var mod = muck.mods[modnum];
				muckApplyMod(mod);
			}
		}
	}
}

function muckApplyMod(mod) {
	// Find the element to apply the mod to
	var elements = [];

	if (mod.id) {
		var element = document.getElementById(mod.id);
		if (element)
			elements[0] = element;
	} else if (mod.selector) {
		// CSS selector. We know that Mashery has loaded Prototype, so
		// we can use its selector functions
		elements = $$(mod.selector);
	} else {
		// apply the mod unconditionally to this page
		elements = document.getElementsByTagName("html");
	}

	for (var i = 0, len=elements.length; i < len; i++) {
		muckApplyModToElement(elements[i], mod);
	}
}


function muckApplyModToElement(element, mod) {
	// Apply all defined mods

	if (mod.replacenode) {
		var newnode = document.createElement(mod.replacenode);
		element.parentNode.replaceChild(newnode, element);
		element = newnode;
	} else if (mod.insertnodebefore) {
		var newnode = document.createElement(mod.insertnodebefore);
		element.parentNode.insertBefore(newnode, element);
		element = newnode;
	} else if (mod.insertnodeafter) {
		var newnode = document.createElement(mod.insertnodeafter);
		element.parentNode.insertBefore(newnode, element.nextSibling);
		element = newnode;
	}

	if (mod.display) {
		element.style.display = mod.display;
	}

	if (mod.innerhtml) {
		element.innerHTML = mod.innerhtml;
	}

	if (mod.htmlfind) {
		var replaced = element.innerHTML.replace(mod.htmlfind, mod.htmlreplace);
		element.innerHTML = replaced;
	}

	if (mod.setchecked) {
		element.checked = mod.setchecked;
	}

	if (mod.setvalue) {
		element.value = mod.setvalue;
	}

	if (mod.callfunction) {
		if (typeof(mod.callfunction) == "function") {
			mod.callfunction(element);
		} else {
			eval(mod.callfunction + "(element);");
		}
	}
}



function hackAppRegForm(button) {
	// The app reg form is generated dynamically by Mashery. Our
	// goal is to hide the "api-info" summary table that gets inserted
	// in step 2. We do that by hooking the button you click to get from
	// step 1 to step 2, and modifying the document after you get to that step.
	button.onclick = function() {
		var apitable = document.getElementById("api-info");
		if (apitable)
			apitable.style.display = "none";
	};
}


/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////

/**
 * Insert a Code Generator iframe into the named divId.
 */
function insertCodeGen(divId, codeGenType, devKey, signature) {
    var codeGenURL = developerCodeBaseURL + "codegen";
    codeGenURL += "?ikey=" + encodeURIComponent(devKey);
    codeGenURL += "&signature=" + encodeURIComponent(signature);
    codeGenURL += "&cgr=" + encodeURIComponent(codeGenType);

    var codeGenDiv = document.getElementById(divId);
    codeGenDiv.innerHTML = '<iframe class="codegen" frameborder="no" scrolling="no" width="651" height="600" '
		+ 'src="' + codeGenURL + '">Loading...</iframe>';
}


/**
 * Insert an email link, trying to avoid spam crawlers
 */
function insertEmailLink(user, domain, tld) {
	var email = user + "@" + domain + "." + tld;
	var mailto = '<a href="mailto:' + email + '">' + email + '</a>';
	document.write(mailto);
}

function insertToc(divAbove) {
	// Create and insert a div to hold the TOC, just below the existing sidebar
	var tocDiv = document.createElement("div");
	tocDiv.id = "toc";
	tocDiv.className = "TOC";
	tocDiv.innerHTML = "<h2>Page Contents</h2>";
	divAbove.parentNode.insertBefore(tocDiv, divAbove.nextSibling);

	// Mashery uses H3 to introduce Tags and Comments sections, which looks
	// confusing in the TOC. Insert an (invisible) H2 above them to improve the TOC.
	var metaDivs = getElements("section-meta", "div", "main"); // <div class="section-meta"> within #main
	var metaDiv = metaDivs.length > 0 ? metaDivs[0] : null;
	if (metaDiv) {
		var addedH2 = document.createElement("H2");
		addedH2.className = "phantomTOC";
		addedH2.innerHTML = tocDocumentInfoTitle;
		metaDiv.parentNode.insertBefore(addedH2, metaDiv);
	}

	maketoc("toc", "main", 2, 6);
}

//Insert Integrator Auto Registration IFRAME
function autoRegistrationIframe() {
	var divToShow;
	if (mashery_replacements) {
		if (!mashery_replacements.member_handle) {
			// Unregistered
			//divToShow = document.getElementById("unregistered_user");
		} else if (!mashery_replacements.member_key_qws37bfb6brpfhv4mvm2xdmc) {
			// Registered, but no developer key
			//divToShow = document.getElementById("unregistered_app");
		} else {
			// Registered, and developer key
			//divToShow = document.getElementById("configure_app");
			divToShow = document.createElement('div');

			//developerCodeBaseURL = "http://www8.qa.photoshow.com/developer/"; // FORCE THIS PAGE TO QA8 FOR TESTING
			//developerCodeBaseURL = "http://www8.dev.photoshow.com/developer/"; // FORCE THIS PAGE TO DEV8 FOR TESTING
			//developerCodeBaseURL = "http://wwwdev/developer/"; // FORCE THIS PAGE TO LOCAL FOR TESTING
			//developerCodeBaseURL = "http://www.stg.photoshow.com/developer/"; // FORCE THIS PAGE TO STG FOR TESTING
			developerCodeBaseURL = "http://www.photoshow.com/developer/"; // FORCE THIS PAGE TO LIVE FOR TESTING

			var configureAppUrl = developerCodeBaseURL + "autoReg";
			configureAppUrl += "?ikey=" + encodeURIComponent(mashery_replacements.member_key_qws37bfb6brpfhv4mvm2xdmc);
			configureAppUrl += "&signature=" + encodeURIComponent(mashery_replacements.member_signature);
			configureAppUrl += "&nonce=" + encodeURIComponent(mashery_replacements.member_nonce);
			configureAppUrl += "&name=" + encodeURIComponent(mashery_replacements.member_company);
			configureAppUrl += "&email=" + encodeURIComponent(mashery_replacements.member_email);

			var configureAppDiv = document.createElement('div');
			configureAppDiv.innerHTML = '<iframe class="codegen" frameborder="no" scrolling="no" width="831" height="600" '
				+ 'src="' + configureAppUrl + '">Loading...</iframe>';
			divToShow.appendChild(configureAppDiv);
		}

		if (divToShow) {
			divToShow.style.display = "none";
			document.body.appendChild(divToShow);
		}
	}
}
// Page load functions

function initPage() {
	muckWithPage(mucks);
}

if (window.addEventListener) window.addEventListener("load", initPage, false);
else if (window.attachEvent) window.attachEvent("onload", initPage);