//*------------------------------------------------------------------------------------------------*
//* Library: AsyncPost
//* Desc: Package & post HTML forms to the specified URL.
//*------------------------------------------------------------------------------------------------*

// Global Variables
var request;
var queryString;
var editmode = false;
var idstr;

// Name: ShowHide
// Desc: Show or Hide a <DIV> region. Used to display onMouseOver hover menus.
function ShowHide(id, visibilityflag)
{ 
    // Catch error gracefully of control is not found
    try
    {
        var div = document.getElementById(id);
        document.getElementById(id).style.visibility = visibilityflag;
    } catch(err) {}
    
    return;
}

// STEP 0: Controller function called when a form is submitted.
function submitForm(formId)
{
    setQueryString(formId);
    httpRequest("POST", "/admin/inline/savecontent.aspx" + "?" + queryString, true);    
}

// STEP 1: Construct a querystring from all FORM elements.
function setQueryString(formId)
{
    queryString = "";
    //var frm = document.forms[0];
    var frm = document.getElementById(formId);
    var numberElements = frm.elements.length;
    for(var i=0; i < numberElements; i++)
    {
        var element = frm.elements[i].name;
        if(element != "__VIEWSTATE" && element != "__EVENTARGUMENT" && element != "__EVENTTARGET")
        {
            if(i < numberElements)
            {
                queryString += frm.elements[i].name + "=" + 
                    encodeURIComponent(frm.elements[i].value)+"&";
            } else {
                queryString += frm.elements[i].name + "=" + 
                    encodeURIComponent(frm.elements[i].value);
            }
        }
    }
}

/* Wrapper function for constructing a request object.
    Parameters: 
        reqType: The HTTP request type. GET or POST
        url: The URL of the server program.
        asynch: Whether to send asynchronously or not.
*/
// STEP 2: Initialize XMLHttpRequest. Handles IE & Mozilla
function httpRequest(reqType, url, asynch)
{
    // Mozilla-based browsers
    if(window.XMLHttpRequest)
    {
        request = new XMLHttpRequest();
    } else if(window.ActiveXObject)
    {
        request = new ActiveXObject("Msxml2.XMLHTTP");
        if(!request)
        {
            request = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    
    // the request could still be null if neither intialization suceeded.
    if(request)
    {
        initReq(reqType, url, asynch);
    } else {
        alert("Your browser must have JavaScript enabled to use all of this applications features!");
    }
}

// STEP 3: Initialize the Request content-type and specify a callback function to handle the response.
function initReq(reqType, url, isAsync)
{
    /* Specify the function that will handle the HTTP response */
    request.onreadystatechange = handleResponse;
    request.open(reqType, url, isAsync);
    
    /* Set the Content-Type header for a POST request */
    if(reqType == "POST")
    {
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    } else
    {
        request.setRequestHeader("Content-Type", "text/xml,application/xml,application/xhtml+xml,text/html; charset=UTF-8");
    }
    
    request.send(queryString);
}   

// STEP 4: Callback function to handle HTTP response. Called for each readyState change.
// readyState values:
// 0 : uninitialized. open() has not been called.
// 1 : loading. send() has not been called.
// 2 : loaded. send() has been called. The headers/status are availble.
// 3 : interactive. responseText holds partial data.
// 4 : completed.
function handleResponse()
{ 
    var results = "There's a problem"; 
          
    if(request.readyState == 4)
    {
        if(request.status == 200)
        {
            var results = request.responseText;
            var control = document.getElementById(idstr);
            
            // Reset DIV content
            try
            {
                control.innerHTML = "";
                control.innerHTML = results;    
            } catch(err)
            {
            }
            
        } else {
            alert("No Data Found: " + request.status);
        }
    }
}

// STEP 6: Retrieve HTML fragement from Response and render
// Parse HTML Fragment from the response XML
/* Get information about XML results via a DOM object */
function getDocInfo(doc)
{
    var root;
    var info = "";
    var ndx = 0;
    var itemlist;
    try
    {
        // Get the RSS node
        root = doc.documentElement;
        
        // If the document is not empty, get the 'item' child nodes
        if(root.hasChildNodes())
        {
            // Get the 'item' nodes
            itemlist = doc.getElementsByTagName("html");
            
            info = "";
            var nodeList = "";
           
            // Do something with each <item> node in the list
            for(var i = 0; i < itemlist.length; i++)
            {
                try
                {					
                  nodeList = itemlist[i].childNodes;
                  info = nodeList[0].nodeValue; 
                  return info;                     

                 } catch(err) 
                 {
                 }
            }
        } 
     } catch(err)
     {}

     return info;   
}

// Name: saveData()
// Package form fields in the 'form_[id]' and send to the specified URL.
// Restore post_[id] DIV with original data
function saveData(id, url)
{   
    setQueryString(url);

    //var url = url + "?id=" + id + "&action=save";      // http://www.localhost.com/rsshome.aspx 
    
    httpRequest("POST", url, true);
    
    //window.setTimeout(disableEdit, 1500);
}

// Name: cancelEdit()
// Package form fields in the 'form_[id]' and send to the specified URL.
// Restore post_[id] DIV with original data
//function cancelEdit(id, url)
//{
//    setQueryString(url);
//    
//    // Cancel the edit/update, but still need to retrieve data from server to redraw the item.
//    url = url + "?id=" + id + "&action=cancel";      // http://www.localhost.com/rsshome.aspx
//    
//    httpRequest("GET", url, true);
//    
//    // Set a timer to wait .5 seconds before restore edit mode
//    window.setTimeout(disableEdit, 1500);
//}
