

// candidates for commons

function loadingImage() {
    var imageEl = new Image();
    imageEl.src = "/dirSearchPortlet/img/ajax-loader.gif";
    imageEl.alt = "Loading ...";
    imageEl.height = 100;
    imageEl.width = 100;
    imageEl.style.display = "block";
    imageEl.style.marginLeft = "auto";
    imageEl.style.marginRight = "auto";
    return imageEl;
}

function removeChildren(el) {
    while ( el.childNodes.length >= 1 ) {
        el.removeChild( el.firstChild );
    }
}


function AsyncJSONRequest(errordiv) {

    var SESSION_REDIRECT = "http://my.unc.edu/portal/dt?dt.isPortletRequest=true&dt.action=process&dt.provider=PortletWindowProcessChannel&dt.windowProvider.targetPortletChannel=JSPTabContainer/HomeTabContainer/WelcomeTabContainer/AccountPortletChannel&dt.containerName=JSPTabContainer/HomeTabContainer/WelcomeTabContainer&dt.windowProvider.currentChannelMode=VIEW&dt.window.portletAction=ACTION&errorMessageId=error.session";
    
    this.success = function(o) {
        try {
            var portletResponseCode = o.getResponseHeader['portlet.http-status-code'];
            if(portletResponseCode && portletResponseCode != 200) {
                this.failure(o);
                return;
            }
            var jsonObj = YAHOO.lang.JSON.parse(o.responseText);
            this.handleJSON(jsonObj);
        }
        catch(ex) {
            this.failure(o);
        }
    }
    this.failure = function(o) {
        if(o.responseText.match("Invalid Session")) {
            window.location = SESSION_REDIRECT;
        } else {
            removeChildren(errordiv);
            errordiv.appendChild(document.createTextNode(o.responseText));
        }
    }
    this.timeout = 1000 * 60 * 2;

    this.asyncRequest = function(method, url, postData) {
        try {
            var cObj = YAHOO.util.Connect.asyncRequest(method, url, this, postData);
        } catch(ex) {
            this.showException(ex, url);
        }
    }

    this.showException = function(ex, location) {
        removeChildren(errordiv);
        var mesg = "Error accessing " + location + ": " + ex.message + " (" + ex.name + ")";
        errordiv.appendChild(document.createTextNode(mesg));
    }

    this.setForm = function(form) {
        YAHOO.util.Connect.setForm(form);
    }

    this.post = function(url, postData) {       
        this.asyncRequest('POST', url, postData);
    }

    this.get = function(url) {
        this.asyncRequest('GET', url);
    }
}
