/*! This file came from Pixelsilk at http://www.winecellarinnovations.com/api2.js  (Smaller version available at http://www.winecellarinnovations.com/api2.min.js)
 *  Version: 3.0.17.9029 | 2/17/2012 4:43:54 PM */

/*********************************************************
 * 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:
 *
 *********************************************************/

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 + "?" + objectToQuery(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 === "")) {
                    miniProfilerHook(request);

                    // 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) {
                    miniProfilerHook(request);
                    var json = JSON.parse(request.responseText);
                    error(json);
                } else if (request.readyState === 4 && request.status === 0) {
                    // Try a JSONP request.
                    ajaxScriptTag(url, data, eventCallbac );  // no post == no auth :(
                }
            };

            // Set the data
            var body = objectToQuery(data, auth);
            // Send the request to the server
            request.send(body);
        }

        // Used to update the mini-profiler on the page after an API call.
        function miniProfilerHook(request) {
            if (typeof MiniProfiler == 'undefined')
                return;
            var stringIds = request.getResponseHeader('X-MiniProfiler-Ids');
            if (stringIds) {
                var ids = JSON.parse(stringIds);
                MiniProfiler.fetchResultsExposed(ids);
            }
        }

        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 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.winecellarinnovations.com',
            urlBase: 'http://www.winecellarinnovations.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":"addDomain","httpMethod":"POST"},{"name":"addListItem","httpMethod":"POST"},{"name":"addNewPageType","httpMethod":"POST"},{"name":"addNewSystemFile","httpMethod":"POST"},{"name":"addPageTypeField","httpMethod":"POST"},{"name":"addPageTypeFieldValue","httpMethod":"POST"},{"name":"addRole","httpMethod":"POST"},{"name":"addSearchField","httpMethod":"POST"},{"name":"addSearchFieldSort","httpMethod":"POST"},{"name":"addSection","httpMethod":"POST"},{"name":"addTheme","httpMethod":"POST"},{"name":"addUser","httpMethod":"POST"},{"name":"canEditPassword","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":"deleteDomain","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":"deleteSearchField","httpMethod":"POST"},{"name":"deleteSearchFieldSort","httpMethod":"POST"},{"name":"deleteSectionById","httpMethod":"POST"},{"name":"deleteSectionSkin","httpMethod":"POST"},{"name":"deleteSystemFile","httpMethod":"POST"},{"name":"deleteTheme","httpMethod":"POST"},{"name":"deleteUser","httpMethod":"POST"},{"name":"editListItems","httpMethod":"POST"},{"name":"editTheme","httpMethod":"POST"},{"name":"enablePlugin","httpMethod":"POST"},{"name":"enableSectionById","httpMethod":"POST"},{"name":"fileUpload","httpMethod":"POST"},{"name":"fileUploadValidator","httpMethod":"POST"},{"name":"getAlbumContents","httpMethod":"POST"},{"name":"getAlbums","httpMethod":"POST"},{"name":"getAllSections","httpMethod":"POST"},{"name":"getApiPermissions","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":"getDomains","httpMethod":"POST"},{"name":"getEdgeEnabled","httpMethod":"POST"},{"name":"getEmailAddressMessages","httpMethod":"POST"},{"name":"getEmailSettings","httpMethod":"POST"},{"name":"getEveryone","httpMethod":"POST"},{"name":"getFile","httpMethod":"POST"},{"name":"getIndexUser","httpMethod":"POST"},{"name":"getIsSiteQueued","httpMethod":"POST"},{"name":"getLayoutSkins","httpMethod":"POST"},{"name":"getListItems","httpMethod":"GET"},{"name":"getLoginMessages","httpMethod":"POST"},{"name":"getPageType","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":"getPotentialUrl","httpMethod":"POST"},{"name":"getRole","httpMethod":"POST"},{"name":"getRoles","httpMethod":"POST"},{"name":"getSearchFields","httpMethod":"POST"},{"name":"getSearchFieldSorts","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":"getThemes","httpMethod":"POST"},{"name":"getTokens","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":"setContent","httpMethod":"POST"},{"name":"setWebboxContent","httpMethod":"POST"},{"name":"showSectionInMenu","httpMethod":"POST"},{"name":"showSectionInSitemap","httpMethod":"POST"},{"name":"updateConfig","httpMethod":"POST"},{"name":"updateControlProperties","httpMethod":"POST"},{"name":"updateDomain","httpMethod":"POST"},{"name":"updateEmailSettings","httpMethod":"POST"},{"name":"updateIndexUser","httpMethod":"POST"},{"name":"updatePageType","httpMethod":"POST"},{"name":"updatePageTypeField","httpMethod":"POST"},{"name":"updatePageTypeFieldValue","httpMethod":"POST"},{"name":"updatePluginSettings","httpMethod":"POST"},{"name":"updateRole","httpMethod":"POST"},{"name":"updateSearchField","httpMethod":"POST"},{"name":"updateSearchFields","httpMethod":"POST"},{"name":"updateSearchFieldSort","httpMethod":"POST"},{"name":"updateSearchFieldSorts","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":"userExists","httpMethod":"POST"},{"name":"validateIndexUser","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'])

