/*! This file came from Pixelsilk at http://www.glasweld.com/api2.js  (Smaller version available at http://www.glasweld.com/api2.min.js)
 *  Version: 3.0.16.8437 | 8/16/2011 11:28:30 AM */

/*********************************************************
 * DOCUMENTATION:
 *
 * Example usage: 
 * pixelsilk2.addNewPageType({ pageTypeName: 'test', baseId: '25E52B42-1580-4843-A76E-023F7340EEE4', image: 'HTML' }, function(pageType) {
 *     alert('Added page type ' + pageType.name + ' with id ' + pageType.id + '.');
 * });
 *
 *
 * pixelsilk2 API Functions:
 *
 **** Category: Configuration ****
 *
 ** {"name":"enablePlugin","httpMethod":"POST"}({ pluginName: String, enabled: Boolean })
 *    Turn a plugin on or off.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getConfiguration","httpMethod":"POST"}()
 *    Return the key-value set of config settings for the site.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getEdgeEnabled","httpMethod":"POST"}()
 *    Gets a value indicating if the site uses Pixelsilk Edge
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getIsSiteQueued","httpMethod":"POST"}()
 *    Gets a value indicating if this site is already queued to be invalidated in the Pixelsilk Edge
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getPlugins","httpMethod":"POST"}()
 *    Get a list of plugins.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getPluginsWithJavaScript","httpMethod":"POST"}()
 *    Gets a list of plugins with and without a JavaScriptFilename member
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"purgeEdgeHost","httpMethod":"POST"}()
 *    Sends a request to purge the Edge cache for an entire host
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"purgeEdgeUrls","httpMethod":"POST"}({ urls: String[] })
 *    Sends a request to purge one or more URL's from the Edge cache.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"updateConfig","httpMethod":"POST"}({ oldKey: String, newKey: String, value: String })
 *    Edit a configuration setting.
 *    Requires the advanced-admin-access permission.
 *
 *
 **** Category: Content ****
 *
 ** {"name":"getContent","httpMethod":"GET"}({ path: String })
 *    Get the unparsed content of a section by its path relative to the root.  Used by the content editor. 
 *
 ** {"name":"getWebboxContent","httpMethod":"GET"}({ webboxName: String, path: String })
 *    Get the unparsed content of a webbox.  Used by the content editor.
 *
 ** {"name":"setContent","httpMethod":"POST"}({ path: String, value: String })
 *    Update the content of a section by its path relative to the root.
 *
 ** {"name":"setWebboxContent","httpMethod":"POST"}({ webboxName: String, value: String, path: String })
 *    Update the content of a webboox.
 *
 *
 **** Category: Controls ****
 *
 ** {"name":"checkValidNewControl","httpMethod":"POST"}({ name: String, type: String })
 *    Validate a control name to check if it conflicts with another control or field.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"copyControl","httpMethod":"POST"}({ controlId: Guid })
 *    Make a copy of the control with its settings and skins.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"createControl","httpMethod":"POST"}({ name: String, type: String })
 *    Add a new control.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"deleteControl","httpMethod":"POST"}({ controlId: Guid })
 *    Remove a control.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getControlProperties","httpMethod":"POST"}({ controlId: Guid })
 *    Get the properties on a control.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getControls","httpMethod":"POST"}()
 *    Get the list of controls.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getControlSecurity","httpMethod":"POST"}({ controlId: Guid })
 *    Get the security options for a control.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getControlSettings","httpMethod":"POST"}({ controlName: String })
 *    Gets a list of settings for a control.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getControlSkins","httpMethod":"POST"}({ controlId: Guid })
 *    Gets the skins for a control.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getControlTypes","httpMethod":"POST"}()
 *    Get the list of types of controls (for new controls ui.)
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"promoteControl","httpMethod":"POST"}({ controlId: Guid })
 *    Make a copy of the theme at the top most group.  Currently only available to limited users. 
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"updateControlProperties","httpMethod":"POST"}({ controlId: Guid, controlName: String, properties: KeyValue, permissions: Array })
 *    Requires the advanced-admin-access permission.
 *
 *
 **** Category: Email ****
 *
 ** {"name":"getEmailSettings","httpMethod":"POST"}()
 *    Retrieve the email settings for a site 
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"updateEmailSettings","httpMethod":"POST"}({ settings: Setting[] })
 *    Update the email settings for a Site 
 *    Requires the advanced-admin-access permission.
 *
 *
 **** Category: Files ****
 *
 ** {"name":"addNewSystemFile","httpMethod":"POST"}({ filename: String })
 *    Create a system file.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"copySystemFile","httpMethod":"POST"}({ filename: String })
 *    Copy the file. 
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"deleteAlbum","httpMethod":"POST"}({ type: String, albumName: String })
 *    Delete an album from the site.
 *    Requires the access-libraries permission.
 *
 ** {"name":"deleteFile","httpMethod":"POST"}({ type: String, filename: String, albumName: String })
 *    Deletes a file from an album.
 *    Requires the access-libraries permission.
 *
 ** {"name":"deleteSystemFile","httpMethod":"POST"}({ filename: String })
 *    Remove a system file.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getAlbumContents","httpMethod":"POST"}({ type: String, albumName: String })
 *    Gets the list of files inside an album 
 *    Requires the access-libraries permission.
 *
 ** {"name":"getAlbums","httpMethod":"POST"}({ type: String })
 *    Gets the list of files inside an album
 *    Requires the access-libraries permission.
 *
 ** {"name":"getFile","httpMethod":"POST"}({ type: String, filename: String })
 *    Returns a file based on type and filename
 *    Requires the access-libraries permission.
 *
 ** {"name":"getSystemFile","httpMethod":"POST"}({ filename: String })
 *    Get the contents of a system file.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getSystemFilenames","httpMethod":"POST"}()
 *    Get a list of system files.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getSystemFiles","httpMethod":"POST"}()
 *    Get a list of system files.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"moveFile","httpMethod":"POST"}({ type: String, filename: String, albumId: Guid })
 *    Moves a file to an album. 
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"promoteFile","httpMethod":"POST"}({ type: String, filename: String })
 *    Make a copy of the file at the top most group.  Currently only available to limited users. 
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"renameFile","httpMethod":"POST"}({ type: String, oldName: String, album: String, newName: String })
 *    Renames a library file. 
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"renameSystemFile","httpMethod":"POST"}({ oldName: String, newName: String })
 *    Rename a file in the SystemFiles tab.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"saveAlbum","httpMethod":"POST"}({ type: String, albumName: String })
 *    Saves an album, either adding a new one or updating an existing one. 
 *    Requires the access-libraries permission.
 *
 ** {"name":"updateSystemFile","httpMethod":"POST"}({ filename: String, text: String })
 *    Edit a system file.
 *    Requires the advanced-admin-access permission.
 *
 *
 **** Category: List Items ****
 *
 ** {"name":"copyListItem","httpMethod":"POST"}({ itemId: Guid })
 *    Copies a list item and returns the new item.
 *
 ** {"name":"deleteItem","httpMethod":"POST"}({ itemId: Guid, deleteMode: String })
 *    Delete a list item.
 *
 ** {"name":"getListItems","httpMethod":"GET"}({ sorts: Array, filters: Array, filterrel: String, pageSize: String, page: String, path: String, fields: Array })
 *
 *
 **** Category: Page Types ****
 *
 ** {"name":"addNewPageType","httpMethod":"POST"}({ name: String, baseType: String, image: String })
 *    Create a new page type based on an existing site type or a system type
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"addPageTypeField","httpMethod":"POST"}({ pageTypeId: Guid, fieldName: String, fieldType: String })
 *    Add a new field to a page type.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"addPageTypeFieldValue","httpMethod":"POST"}({ pageTypeId: Guid, fieldId: Guid, listValue: String, listText: String })
 *    Add a value to a field's values.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"checkValidNewPageTypeField","httpMethod":"POST"}({ pageTypeId: Guid, fieldName: String })
 *    Validate a field name to make sure it does not conflict with another field or control. 
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"copyPageType","httpMethod":"POST"}({ pageTypeId: Guid })
 *    Make a copy of a page type.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"deletePageType","httpMethod":"POST"}({ pageTypeId: Guid })
 *    Deletes a page type.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"deletePageTypeField","httpMethod":"POST"}({ pageTypeId: Guid, fieldId: Guid })
 *    Delete a field from a page type.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"deletePageTypeFieldValue","httpMethod":"POST"}({ pageTypeId: Guid, fieldId: Guid, valueId: Guid })
 *    Delete's one of a field's values.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getBaseTypes","httpMethod":"POST"}()
 *    Return an object containing all of the page types available sorted into system and site specific types. 
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getPageTypeFields","httpMethod":"POST"}({ pageTypeId: Guid })
 *    Get the fields in a page type.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getPageTypeFieldValues","httpMethod":"POST"}({ pageTypeId: Guid, fieldId: Guid })
 *    Get the values for a page type (choices in a drop down for example.)
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getPageTypes","httpMethod":"POST"}()
 *    Return an object containing all of the page types available sorted into system and site specific types. 
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"getPageTypeSkins","httpMethod":"POST"}({ pageTypeId: Guid })
 *    Gets the skins object for a page type.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"movePageTypeFieldValueInsertBefore","httpMethod":"POST"}({ pageTypeId: Guid, fieldId: Guid, valueToMoveId: Guid, valueToInsertBeforeId: Guid })
 *    When a field value is dragged to be above another value.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"movePageTypeFieldValueInsertBefore","httpMethod":"POST"}({ pageTypeId: String, fieldId: String, valueToMoveId: String, valueToInsertBeforeId: String })
 *    When a field value is dragged to be above another value.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"promotePageType","httpMethod":"POST"}({ pageTypeId: Guid })
 *    Copy a page type to the root group.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"updatePageType","httpMethod":"POST"}({ id: Guid, name: String, image: String })
 *    Edit a page type's properties.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"updatePageTypeField","httpMethod":"POST"}({ pageTypeId: Guid, input: PageTypeFieldForJson })
 *    Save changes to a page type's field.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"updatePageTypeFieldValue","httpMethod":"POST"}({ pageTypeId: Guid, fieldId: Guid, valueId: Guid, listValue: String, listText: String })
 *    Modify one of a field's values.
 *    Requires the advanced-admin-access permission.
 *
 *
 **** Category: Plugins ****
 *
 ** {"name":"getPluginSettings","httpMethod":"POST"}({ pluginName: String })
 *    Gets all plugin settings for a plugin.
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"updatePluginSettings","httpMethod":"POST"}({ name: String, settings: KeyValue })
 *    Requires the advanced-admin-access permission.
 *
 *
 **** Category: Sections ****
 *
 ** {"name":"addSection","httpMethod":"POST"}({ name: String, parentId: Guid, typeId: Guid })
 *    Adds a new section.
 *    Requires the add-page permission.
 *
 ** {"name":"createNewSectionSkin","httpMethod":"POST"}({ sectionId: Guid })
 *    Create a new skin for a section that will override its type skin.
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"deleteSectionById","httpMethod":"POST"}({ sectionId: Guid })
 *    Delete a section (used from the Manage Pages UI)
 *    Requires the delete-page permission.
 *
 ** {"name":"deleteSectionSkin","httpMethod":"POST"}({ sectionId: Guid })
 *    Deletes a section's skin and falls back to the type skin for the section.
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"enableSectionById","httpMethod":"POST"}({ sectionId: Guid, enabled: Boolean })
 *    Enable or disable a section (used from the Manage Pages UI).
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"getAllSections","httpMethod":"POST"}()
 *    Get a list of all the sections (used from the Manage Pages UI). 
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"getPotentialUrl","httpMethod":"POST"}({ sectionId: Guid, urlMode: String, pathName: String, extension: String, rewriteUrl: String, toLowerCase: Boolean, useParentSettings: Boolean })
 *    Returns what a section's url would be with different settings on the URL tab in admin. 
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"getSection","httpMethod":"POST"}({ sectionId: Guid })
 *    Get full information about a given section. 
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"getSections","httpMethod":"POST"}({ parentId: Nullable`1 })
 *    Get a list of sections based on the parent. 
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"getSectionsUrl","httpMethod":"POST"}({ sectionId: Guid })
 *    Get's a section's relative url.
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"getSiteListSections","httpMethod":"POST"}()
 *    Get List sections in the site.
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"getSkins","httpMethod":"POST"}({ sectionId: Guid })
 *    Gets the skins object for a section.
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"moveSectionInsertBefore","httpMethod":"POST"}({ sectionToMoveId: Guid, sectionToInsertBeforeId: Guid })
 *    Move a section to be immediately before another section (used from the Manage Pages UI). 
 *    Requires the move-page permission.
 *
 ** {"name":"moveSectionMakeChild","httpMethod":"POST"}({ childId: Guid, parentId: Guid })
 *    Move a section to be a child of another section (used from the Manage Pages UI). 
 *    Requires the move-page permission.
 *
 ** {"name":"newSection","httpMethod":"POST"}()
 *    Create an empty section. 
 *    Requires the add-page permission.
 *
 ** {"name":"showSectionInMenu","httpMethod":"POST"}({ sectionId: Guid, show: Boolean })
 *    Hide or unhide a section (used from the Manage Pages UI).
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"showSectionInSitemap","httpMethod":"POST"}({ sectionId: Guid, show: Boolean })
 *    Hide or unhide a section (used from the Manage Pages UI).
 *    Requires the edit-page-properties permission.
 *
 ** {"name":"updateSection","httpMethod":"POST"}({ input: FullSectionForJson })
 *    Updates the properties of a section.
 *    Requires the edit-page-properties permission.
 *
 *
 **** Category: Security ****
 *
 ** {"name":"getSecuritySettings","httpMethod":"POST"}()
 *    Retrieve the settings for a site 
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"updateSecuritySettings","httpMethod":"POST"}({ settings: KeyValue })
 *    Requires the advanced-admin-access permission.
 *
 *
 **** Category: Skins ****
 *
 ** {"name":"renderSkin","httpMethod":"GET"}({ skin: String, path: String, format: String })
 *    Renders a simple skin.
 *
 *
 **** Category: Themes ****
 *
 ** {"name":"addTheme","httpMethod":"POST"}({ themeName: String })
 *    Add a theme to the site.
 *    Requires the edit-skin permission.
 *
 ** {"name":"copyTheme","httpMethod":"POST"}({ themeId: Guid })
 *    Duplicate a theme.
 *    Requires the edit-skin permission.
 *
 ** {"name":"deleteTheme","httpMethod":"POST"}({ themeId: Guid })
 *    Delete a theme.
 *    Requires the edit-skin permission.
 *
 ** {"name":"editTheme","httpMethod":"POST"}({ input: ThemeForJson })
 *    Edit a theme's name.
 *    Requires the edit-skin permission.
 *
 ** {"name":"getLayoutSkins","httpMethod":"POST"}({ themeId: Guid })
 *    Gets the layout skin for the theme.
 *    Requires the edit-skin permission.
 *
 ** {"name":"getThemes","httpMethod":"POST"}()
 *    Get the themes in the site.
 *    Requires the edit-skin permission.
 *
 ** {"name":"promoteTheme","httpMethod":"POST"}({ themeId: Guid })
 *    Make a copy of the theme at the top most group.  Currently only available to limited users. 
 *    Requires the advanced-admin-access permission.
 *
 ** {"name":"updateSkins","httpMethod":"POST"}({ input: SkinsForJson })
 *    Save changes to any skins object.
 *    Requires the edit-skin permission.
 *
 *
 **** Category: Users ****
 *
 ** {"name":"addRole","httpMethod":"POST"}({ name: String, description: String, isHidden: String, isSystemRole: String, adminAccess: String[] })
 *    Add a new role.
 *    Requires the access-users permission.
 *
 ** {"name":"addUser","httpMethod":"POST"}({ username: String, emailAddress: String, firstName: String, lastName: String, password: String, sendPasswordLink: Boolean, enabled: Boolean, locked: Boolean, emailVerified: Boolean, roles: Guid[] })
 *    Add a new user.
 *    Requires the access-users permission.
 *
 ** {"name":"canEditPassword","httpMethod":"POST"}()
 *    Determines if the user has a Role with the "edit-password" permission.
 *    Requires the access-users permission.
 *
 ** {"name":"deleteRole","httpMethod":"POST"}({ roleName: String })
 *    Delete a role.
 *    Requires the access-users permission.
 *
 ** {"name":"deleteUser","httpMethod":"POST"}({ userId: String })
 *    Delete a user.
 *    Requires the access-users permission.
 *
 ** {"name":"getEmailAddressMessages","httpMethod":"POST"}()
 *    Get Email Messages from Site Settings.
 *
 ** {"name":"getEveryone","httpMethod":"POST"}()
 *    Returns only the everyone role.  Needed currently because sections need to "show Everyone plus all the roles on the roles tab"  See bug [I3-2692]. 
 *    Requires the access-users permission.
 *
 ** {"name":"getLoginMessages","httpMethod":"POST"}()
 *    Get Login Messages from Site Settings.
 *
 ** {"name":"getPasswordMessages","httpMethod":"POST"}()
 *    Get Password Messages from Site Settings.
 *
 ** {"name":"getPasswordRequirements","httpMethod":"POST"}()
 *    Get Password Requirements from Site Settings.
 *
 ** {"name":"getRoles","httpMethod":"POST"}()
 *    Get site roles.
 *    Requires the access-users or edit-page-properties permission.
 *
 ** {"name":"getUsernameMessages","httpMethod":"POST"}()
 *    Get Username Messages from Site Settings.
 *
 ** {"name":"getUsers","httpMethod":"POST"}()
 *    Get site users.
 *    Requires the access-users permission.
 *
 ** {"name":"login","httpMethod":"POST"}({ username: String, password: String })
 *    Login function for external application.  Takes a username and password, retuns an auth cookie and a token. 
 *
 ** {"name":"sendEmailVerificationLink","httpMethod":"POST"}({ userId: String })
 *    Send an email to the user with the password link.
 *    Requires the access-users permission.
 *
 ** {"name":"sendMailForPasswordUpdate","httpMethod":"POST"}({ originalUser: SiteUser, newPassword: String })
 *    Cause an email to be sent to a user with thier new password.
 *    Requires the access-users permission.
 *
 ** {"name":"sendPasswordLink","httpMethod":"POST"}({ userId: String })
 *    Send an email to the user with the password link.
 *    Requires the access-users permission.
 *
 ** {"name":"sendVerificationEmail","httpMethod":"POST"}({ user: PixelsilkUser })
 *    Send an email to the user with the password link. 
 *    Requires the access-users permission.
 *
 ** {"name":"updateRole","httpMethod":"POST"}({ hiddenName: String, name: String, description: String, isHidden: String, isSystemRole: String, adminAccess: String[] })
 *    Edit a role.
 *    Requires the access-users permission.
 *
 ** {"name":"updateUser","httpMethod":"POST"}({ username: String, emailAddress: String, firstName: String, lastName: String, password: String, enabled: Boolean, locked: Boolean, emailVerified: Boolean, roles: Guid[], id: String })
 *    Edit a user.
 *    Requires the access-users permission.
 *
 ** {"name":"updateUserByObject","httpMethod":"POST"}({ id: Guid, keyValues: KeyValue })
 *    Requires the access-users permission.
 *
 ** {"name":"useEmailAsUsername","httpMethod":"POST"}()
 *    Determines if the site encourages to use the email address as the username.
 *    Requires the access-users permission.
 *
 ** {"name":"verifyUserUniqueness","httpMethod":"POST"}({ id: String, loginId: String, email: String })
 *    Determines if the username and email given as parameters already exist.
 *
 *
 **** Category: unspecified ****
 *
 ** {"name":"checkPermissions","httpMethod":"POST"}({ permissionsNeeded: String[] })
 *    Sees if the user has at least one of the specified permissions.
 *
 ** {"name":"getTokens","httpMethod":"POST"}({ skinId: Nullable`1 })
 *    Get the tokens for a given page if it is a special page. Otherwise the TscGetTokens() function is called. 
 *    Requires the edit-skin permission.
 *
 *
 *********************************************************/

if (!window['pixelsilk2']) {

    window['pixelsilk2'] = (function () {

        var nextId = 1;
        var maxUrlLength = 1200;    // Prevents ajax GET requests from exceeding the length of a valid URL.
        var token;  // prevents csrf
        var appId;  // id of the application, can be blank at this time.
        var privateKey;  // key used for signing if the application is specified.

        // Methods here are not globally accessible.

        var startHandler, endHandler, errorHandler;
        function start() {
            if (typeof (startHandler) === 'function') {
                startHandler();
            }
        }

        function end() {
            if (typeof (endHandler) === 'function') {
                endHandler();
            }
        }

        function error(e) {
            if (typeof (errorHandler) === 'function') {
                errorHandler(e);
            } else if (e.error) {
                alert(e.message);
            }
        }

        function ajax(url, method, data, auth, callback) {
            includeJson('JSON', '/_System/Scripts/json2.min.js');
            start();

            if (typeof (callback) !== 'function' && typeof (auth) === 'function') {
                // If there's callback, but no auth.
                callback = auth;
                auth = null;
            } else if (typeof (callback) !== 'function' && typeof (data) === 'function') {
                // If there's a callback, but no data.
                callback = data;
                data = null;
            }

            var eventCallback = function (data) {
                end();
                if (callback) {
                    callback(data);
                }
            };

            // This will first try an XmlHttpRequest, if that is unavailable it will try a JSONP script request.
            ajaxXhr(url, method, data, auth, eventCallback);
        }

        function ajaxXhr(url, method, data, auth, callback) {
            // Setup the request
            var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
            if (method === "GET") {
                var fullUrl = url + objectToQueryString(data, auth) + "&format=json";
                // If the URL is too long, fall back to using a POST.
                if (fullUrl.length > maxUrlLength)
                    method = "POST";
                else
                    url = fullUrl;
            }

            request.open(method, url, true);
            //request.open("POST", url, true);
            request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

            // Event handler
            request.onreadystatechange = function () {
                // If the request is done without error.
                if (request.readyState === 4 && request.status === 200 && (request.responseText || request.responseText === "")) {

                    // Parse the result.
                    var result = JSON.parse(request.responseText);

                    if (result && result.error === true) {  // Error could be a 200 with json if noHttp500 is set to true.
                        error(result);
                    } else if (callback !== null) {  // Call the callback in client code.
                        callback(result);
                    }

                    // If the request completed with an error...
                } else if (request.readyState === 4 && request.status === 500) {
                    var json = JSON.parse(request.responseText);
                    error(json);
                } else if (request.readyState === 4 && request.status === 0) {
                    // Try a JSONP request.
                    ajaxScriptTag(url, data, eventCallback);  // no post == no auth :(
                }
            };

            // Set the data
            var body = objectToQuery(data, auth);
            // Send the request to the server
            request.send(body);
        }

        function ajaxScriptTag(url, data, callback) {
            var id = nextId++;
            var callbackName = setupCallback(id, callback);
            var query = objectToQuery(data);
            var script = makeScriptTag(url, query, callbackName, id);

            var head = document.getElementsByTagName('head')[0];
            head.appendChild(script);
        }

        function setupCallback(id, callback) {
            // Generate a name because the callback needs to be globally accessable: pixelsilk2.callback1()
            var callbackName = 'callback' + id;

            window['pixelsilk2'][callbackName] = function (result) {
                // remove the callback wrapper
                window['pixelsilk2'][callbackName] = null;

                // remove the script tag
                var script = document.getElementById('pixelsilk2api' + id);
                if (script) {
                    script.parentNode.removeChild(script);
                }

                // call the real callback
                callback(result);
            };

            // return the name;
            return 'pixelsilk2.' + callbackName;
        }

        function objectToQueryString(data, auth) {
            var result = '?';

            for (var key in data) {
                result += key + '='
                if (typeof (data[key]) == 'object' && (data[key] instanceof Array)) {
                    result += '[';
                    if (data[key].length > 0) {
                        if (typeof (data[key][0]) == 'object') {
                            for (var i = 0; i < data[key].length; i++) {
                                result += "{";
                                for (var subkey in data[key][i]) {
                                    result += subkey + "=" + data[key][i][subkey] + ",";
                                }
                                result = result.substr(0, result.length - 1) + "},";
                            }
                        }
                        else
                            for (var i = 0; i < data[key].length; i++)
                                result += data[key][i] + ",";

                        result = result.substr(0, result.length - 1);
                    }
                    result += ']';
                }
                else
                    result += data[key];

                result += '&';
            }

            if (appId) {
                var signature = signRequest(result);
                result += 'appId=' + encodeURIComponent(appId) + '&signature=' + encodeURIComponent(signature) + '&';
            }
            if (token && !auth) {
                result += 'token=' + encodeURIComponent(token) + '&';
            }
            if (auth) {
                result += 'auth=' + encodeURIComponent(auth.auth) + '&token=' + encodeURIComponent(auth.token) + '&';
            }

            return result.substr(0, result.length - 1);
        }

        function objectToQuery(data, auth) {
            var query = 'json=';

            if (typeof (data) !== 'undefined') {
                var json = JSON.stringify(data);
                query += encodeURIComponent(json);
            }

            if (token && !auth) {
                query += '&token=' + encodeURIComponent(token);
            }
            if (appId) {
                var signature = signRequest(json);
                query += '&appId=' + encodeURIComponent(appId) + '&signature=' + encodeURIComponent(signature);
            }
            if (auth) {
                query += '&auth=' + encodeURIComponent(auth.auth) + '&token=' + encodeURIComponent(auth.token);
            }
            return query;
        }

        function signRequest(json) {
            // TODO: include the user's token and a random string (nonce) in the toHash var.
            if (typeof (json) === 'undefined') {
                json = '';
            }
            var toHash = json + privateKey;
            includeJson('SHA1', '/_System/Scripts/webtoolkit.sha1.min.js');
            return SHA1(toHash);
        }

        function makeScriptTag(url, query, callback, id) {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            var src = url + '?' + query + '&callback=' + callback;
            if (src.length > 2000) {
                throw "URL length is over 2000 characters, not creating script tag.";
            }
            script.src = src;
            script.id = 'pixelsilk2api' + id;
            script.className = 'pixelsilk2api';
            return script;
        }

        function createApiFunction(functionInfo) {
            return function (data, auth, callback) {
                var url = window['pixelsilk2'].urlBase + functionInfo.name;
                ajax(url, functionInfo.httpMethod, data, auth, callback);
            };
        }

        // Return just the 'public' functions.
        var api = {
            // init must be called first if you need to do anything as a logged in user
            init: function (t) {
                token = t;
            },
            setKey: function (id, key) {
                appId = id;
                privateKey = key;
            },
            start: function (handler) {
                startHandler = handler;
            },
            end: function (handler) {
                endHandler = handler;
            },
            error: function (handler) {
                errorHandler = handler;
            },
            ajaxPost: function (url, data, auth, callback) {
                ajax(url, "POST", data, auth, callback);
            },

            // Necessary context info.
            domain: 'www.glasweld.com',
            urlBase: 'http://www.glasweld.com/api2/',
            appPath: ''
        };

        function includeJson(name, path) {
            if (!window[name]) {
                var url = window.location.protocol + '//' + api.domain;
                if (api.appPath) {
                    url += '/' + api.appPath;
                }
                url += path;

                var script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = url;

                var head = document.getElementsByTagName('head')[0];
                head.appendChild(script);
            }
        }

        /*!
        *
        *  Secure Hash Algorithm (SHA1)
        *  http://www.webtoolkit.info/
        *
        **/
        function SHA1(msg) {

            function rotate_left(n, s) {
                var t4 = (n << s) | (n >>> (32 - s));
                return t4;
            };

            function lsb_hex(val) {
                var str = "";
                var i;
                var vh;
                var vl;

                for (i = 0; i <= 6; i += 2) {
                    vh = (val >>> (i * 4 + 4)) & 0x0f;
                    vl = (val >>> (i * 4)) & 0x0f;
                    str += vh.toString(16) + vl.toString(16);
                }
                return str;
            };

            function cvt_hex(val) {
                var str = "";
                var i;
                var v;

                for (i = 7; i >= 0; i--) {
                    v = (val >>> (i * 4)) & 0x0f;
                    str += v.toString(16);
                }
                return str;
            };


            function Utf8Encode(string) {
                string = string.replace(/\r\n/g, "\n");
                var utftext = "";

                for (var n = 0; n < string.length; n++) {

                    var c = string.charCodeAt(n);

                    if (c < 128) {
                        utftext += String.fromCharCode(c);
                    }
                    else if ((c > 127) && (c < 2048)) {
                        utftext += String.fromCharCode((c >> 6) | 192);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }
                    else {
                        utftext += String.fromCharCode((c >> 12) | 224);
                        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }

                }

                return utftext;
            };

            var blockstart;
            var i, j;
            var W = new Array(80);
            var H0 = 0x67452301;
            var H1 = 0xEFCDAB89;
            var H2 = 0x98BADCFE;
            var H3 = 0x10325476;
            var H4 = 0xC3D2E1F0;
            var A, B, C, D, E;
            var temp;

            msg = Utf8Encode(msg);

            var msg_len = msg.length;

            var word_array = new Array();
            for (i = 0; i < msg_len - 3; i += 4) {
                j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 |
                    msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
                word_array.push(j);
            }

            switch (msg_len % 4) {
                case 0:
                    i = 0x080000000;
                    break;
                case 1:
                    i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
                    break;

                case 2:
                    i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
                    break;

                case 3:
                    i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
                    break;
            }

            word_array.push(i);

            while ((word_array.length % 16) != 14) word_array.push(0);

            word_array.push(msg_len >>> 29);
            word_array.push((msg_len << 3) & 0x0ffffffff);


            for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {

                for (i = 0; i < 16; i++) W[i] = word_array[blockstart + i];
                for (i = 16; i <= 79; i++) W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);

                A = H0;
                B = H1;
                C = H2;
                D = H3;
                E = H4;

                for (i = 0; i <= 19; i++) {
                    temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotate_left(B, 30);
                    B = A;
                    A = temp;
                }

                for (i = 20; i <= 39; i++) {
                    temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotate_left(B, 30);
                    B = A;
                    A = temp;
                }

                for (i = 40; i <= 59; i++) {
                    temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotate_left(B, 30);
                    B = A;
                    A = temp;
                }

                for (i = 60; i <= 79; i++) {
                    temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotate_left(B, 30);
                    B = A;
                    A = temp;
                }

                H0 = (H0 + A) & 0x0ffffffff;
                H1 = (H1 + B) & 0x0ffffffff;
                H2 = (H2 + C) & 0x0ffffffff;
                H3 = (H3 + D) & 0x0ffffffff;
                H4 = (H4 + E) & 0x0ffffffff;

            }

            var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);

            return temp.toLowerCase();

        }
        /**
        *
        *  End SHA1
        *
        **/


        // Define API functions..
        var apiFunctions = [{"name":"addNewPageType","httpMethod":"POST"},{"name":"addNewSystemFile","httpMethod":"POST"},{"name":"addPageTypeField","httpMethod":"POST"},{"name":"addPageTypeFieldValue","httpMethod":"POST"},{"name":"addRole","httpMethod":"POST"},{"name":"addSection","httpMethod":"POST"},{"name":"addTheme","httpMethod":"POST"},{"name":"addUser","httpMethod":"POST"},{"name":"canEditPassword","httpMethod":"POST"},{"name":"checkPermissions","httpMethod":"POST"},{"name":"checkValidNewControl","httpMethod":"POST"},{"name":"checkValidNewPageTypeField","httpMethod":"POST"},{"name":"copyControl","httpMethod":"POST"},{"name":"copyListItem","httpMethod":"POST"},{"name":"copyPageType","httpMethod":"POST"},{"name":"copySystemFile","httpMethod":"POST"},{"name":"copyTheme","httpMethod":"POST"},{"name":"createControl","httpMethod":"POST"},{"name":"createNewSectionSkin","httpMethod":"POST"},{"name":"deleteAlbum","httpMethod":"POST"},{"name":"deleteControl","httpMethod":"POST"},{"name":"deleteFile","httpMethod":"POST"},{"name":"deleteItem","httpMethod":"POST"},{"name":"deletePageType","httpMethod":"POST"},{"name":"deletePageTypeField","httpMethod":"POST"},{"name":"deletePageTypeFieldValue","httpMethod":"POST"},{"name":"deleteRole","httpMethod":"POST"},{"name":"deleteSectionById","httpMethod":"POST"},{"name":"deleteSectionSkin","httpMethod":"POST"},{"name":"deleteSystemFile","httpMethod":"POST"},{"name":"deleteTheme","httpMethod":"POST"},{"name":"deleteUser","httpMethod":"POST"},{"name":"editTheme","httpMethod":"POST"},{"name":"enablePlugin","httpMethod":"POST"},{"name":"enableSectionById","httpMethod":"POST"},{"name":"getAlbumContents","httpMethod":"POST"},{"name":"getAlbums","httpMethod":"POST"},{"name":"getAllSections","httpMethod":"POST"},{"name":"getBaseTypes","httpMethod":"POST"},{"name":"getConfiguration","httpMethod":"POST"},{"name":"getContent","httpMethod":"GET"},{"name":"getControlProperties","httpMethod":"POST"},{"name":"getControls","httpMethod":"POST"},{"name":"getControlSecurity","httpMethod":"POST"},{"name":"getControlSettings","httpMethod":"POST"},{"name":"getControlSkins","httpMethod":"POST"},{"name":"getControlTypes","httpMethod":"POST"},{"name":"getEdgeEnabled","httpMethod":"POST"},{"name":"getEmailAddressMessages","httpMethod":"POST"},{"name":"getEmailSettings","httpMethod":"POST"},{"name":"getEveryone","httpMethod":"POST"},{"name":"getFile","httpMethod":"POST"},{"name":"getIsSiteQueued","httpMethod":"POST"},{"name":"getLayoutSkins","httpMethod":"POST"},{"name":"getListItems","httpMethod":"GET"},{"name":"getLoginMessages","httpMethod":"POST"},{"name":"getPageTypeFields","httpMethod":"POST"},{"name":"getPageTypeFieldValues","httpMethod":"POST"},{"name":"getPageTypes","httpMethod":"POST"},{"name":"getPageTypeSkins","httpMethod":"POST"},{"name":"getPasswordMessages","httpMethod":"POST"},{"name":"getPasswordRequirements","httpMethod":"POST"},{"name":"getPlugins","httpMethod":"POST"},{"name":"getPluginSettings","httpMethod":"POST"},{"name":"getPluginsWithJavaScript","httpMethod":"POST"},{"name":"getPotentialUrl","httpMethod":"POST"},{"name":"getRoles","httpMethod":"POST"},{"name":"getSection","httpMethod":"POST"},{"name":"getSections","httpMethod":"POST"},{"name":"getSectionsUrl","httpMethod":"POST"},{"name":"getSecuritySettings","httpMethod":"POST"},{"name":"getSiteListSections","httpMethod":"POST"},{"name":"getSkins","httpMethod":"POST"},{"name":"getSystemFile","httpMethod":"POST"},{"name":"getSystemFilenames","httpMethod":"POST"},{"name":"getSystemFiles","httpMethod":"POST"},{"name":"getSystemImages","httpMethod":"POST"},{"name":"getThemes","httpMethod":"POST"},{"name":"getTokens","httpMethod":"POST"},{"name":"getTypeSkins","httpMethod":"POST"},{"name":"getUsernameMessages","httpMethod":"POST"},{"name":"getUsers","httpMethod":"POST"},{"name":"getWebboxContent","httpMethod":"GET"},{"name":"login","httpMethod":"POST"},{"name":"moveFile","httpMethod":"POST"},{"name":"movePageTypeFieldValueInsertBefore","httpMethod":"POST"},{"name":"movePageTypeFieldValueInsertBefore","httpMethod":"POST"},{"name":"moveSectionInsertBefore","httpMethod":"POST"},{"name":"moveSectionMakeChild","httpMethod":"POST"},{"name":"newSection","httpMethod":"POST"},{"name":"promoteControl","httpMethod":"POST"},{"name":"promoteFile","httpMethod":"POST"},{"name":"promotePageType","httpMethod":"POST"},{"name":"promoteTheme","httpMethod":"POST"},{"name":"purgeEdgeHost","httpMethod":"POST"},{"name":"purgeEdgeUrls","httpMethod":"POST"},{"name":"renameFile","httpMethod":"POST"},{"name":"renameSystemFile","httpMethod":"POST"},{"name":"renderSkin","httpMethod":"GET"},{"name":"saveAlbum","httpMethod":"POST"},{"name":"sendEmailVerificationLink","httpMethod":"POST"},{"name":"sendMailForPasswordUpdate","httpMethod":"POST"},{"name":"sendPasswordLink","httpMethod":"POST"},{"name":"sendVerificationEmail","httpMethod":"POST"},{"name":"setContent","httpMethod":"POST"},{"name":"setWebboxContent","httpMethod":"POST"},{"name":"showSectionInMenu","httpMethod":"POST"},{"name":"showSectionInSitemap","httpMethod":"POST"},{"name":"updateConfig","httpMethod":"POST"},{"name":"updateControlProperties","httpMethod":"POST"},{"name":"updateEmailSettings","httpMethod":"POST"},{"name":"updatePageType","httpMethod":"POST"},{"name":"updatePageTypeField","httpMethod":"POST"},{"name":"updatePageTypeFieldValue","httpMethod":"POST"},{"name":"updatePluginSettings","httpMethod":"POST"},{"name":"updateRole","httpMethod":"POST"},{"name":"updateSection","httpMethod":"POST"},{"name":"updateSecuritySettings","httpMethod":"POST"},{"name":"updateSkins","httpMethod":"POST"},{"name":"updateSystemFile","httpMethod":"POST"},{"name":"updateUser","httpMethod":"POST"},{"name":"updateUserByObject","httpMethod":"POST"},{"name":"useEmailAsUsername","httpMethod":"POST"},{"name":"verifyUserUniqueness","httpMethod":"POST"}];
        for (var i = 0; i < apiFunctions.length; i++) {
            var functionInfo = apiFunctions[i];
            api[functionInfo.name] = createApiFunction(functionInfo);
        }

        return api;

    } ());

} // if (!window['pixelsilk2'])

