
// this file is built in to impact
// with a url like http://lonestar.smartz.com/api or http://localhost/Impact3/api

/* 
Functions in the api:

  * impact.renderSkin(skin, callback)
    Renders the specified text as a skin.
    skin: Some text to render.
    callback: Function called when the results are ready.  Should take a single parameter called 
        html.
    Example: 
        impact.renderSkin("[[Menu1]]", function(html) {
            document.getElementById("menu").innerHTML = html;
        });

  * impact.getContent(path, callback)
    Gets a section's content
    path: Path to the section.  / is the home page.
    callback: Function called when the results are ready.  Should take a single parameter called 
        html.
    Example: 
        impact.getContent("/aboutus/", function(html) {
            document.getElementById("content").innerHTML = html;
        });

  * impact.setContent(path, value, callback)
    Sets a section's content to a new value and returns the rendered content.
    path: Path to the section.  / is the home page.
    value: The new content.
    callback: Function called when the results are ready.  Should take a single parameter called 
        html.
    Example: 
        impact.setContent("/", function(html) {
            document.getElementById("content").innerHTML = html;
        });

  * impact.getAlbumContents(type, albumName, callback)
    Gets a list of all the files in an album.
    type: type of library: Image, Media, System, or Binary.
    albumName: name of the album.
    callback: Function called when the results are ready.  Should take a single parameter called 
        files that is an array of file objects.

*/

if (!window.impact) {

var impact = function() {

    var nextId = 1;

    // Methods here are not globally accessible.

    function ajax(url, data, callback) {
        try {
            ajaxXhr(url, data, callback);
        } catch(e) {
            
            if (window['console'] && window['console']['warn']) console.warn(e);
            
            ajaxScriptTag(url, data, callback);
        }
    }

    function ajaxXhr(url, data, callback) {
        var request = window.XMLHttpRequest ?
            new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
        request.open('POST', url, true);
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200 && request.responseText) {
                var result = data.output == 'json' ? eval(request.responseText) : request.responseText;
                callback(result);
            }
        };
        var body = objectToQuery(data);
        //request.setRequestHeader('Content-Length', body.length);
        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: impact.callback1()
        var callbackName = 'callback' + id;
        
        impact[callbackName] = function(result) {
            // remove the callback wrapper
            impact[callbackName] = null;
            
            // remove the script tag
            var script = document.getElementById('impactapi' + id);
            if (script)
                script.parentNode.removeChild(script);

            // call the real callback
            callback(result);
        };

        // return the name;
        return 'impact.' + callbackName;
    }

    function objectToQuery(data) {
        var query = '';
        for (var key in data) {
            query += key + '=' + encodeURIComponent(data[key]) + '&';
        }
        return query.substr(0, query.length-1);
    }

    function makeScriptTag(url, query, callback, id) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        var src = url + '?' + query + '&output=json&callback=' + callback;
        if (src.length > 2000)
            throw "Url length is over 2000 characters, not creating script tag";
        script.src = src;
        script.id = 'impactapi' + id;
        script.className = 'impactapi';
        return script;
    }

    // Return just the 'public' functions.
    return {

        renderSkin: function(skin, callback) {
            var url = impact.urlBase + 'RenderSkin';
            var data = {'domain':impact.domain, 'skin':skin};
            ajax(url, data, callback);
        },

        getContent: function(path , callback) {
            var url = impact.urlBase + 'GetContent';             
            var data = {domain:impact.domain, path: path};
            ajax(url, data, callback);           
        },
        
        setContent: function(path, value, callback) {
            var url = impact.urlBase + 'SetContent';
            var data = {'domain':impact.domain, 'path':path, 'value':value};
            ajax(url, data, callback);
        },
        
        getAlbumContents: function(type, albumName, callback) {
            var url = impact.urlBase + 'GetAlbumContents';
            var data = {'domain':impact.domain, 'type':type, 'albumName':albumName, 'output':'json'};
            ajax(url, data, callback);
        },
        
        deleteItem: function(itemId, callback) {
            var url = impact.urlBase + 'deleteItem';
            var data = {'itemId':itemId};
            ajax(url, data, callback);
        },
        
        // Necessary context info.
        domain: 'www.lonestarcandlesupply.com',
        urlBase: 'http://www.lonestarcandlesupply.com/api/'
    };

}();

} // if (!window['impact'])
