
var ppDbgStr = "";
var ppLastException;
var ppDbgFlg = false;

// ------------------------------------------------------------------------

function Print(str)
{
    // uncomment this for debugging, and make sure there's a div called 'dbg'
    // $('dbg').innerHTML += str;
    ppDbgStr += str;
}

function PrintLine(str)
{
    Print( str + "\n" );
}

// ------------------------------------------------------------------------

function doPrototypePostback(success, failure)
{

    var form = $('aspnetForm');
    if(form == null) { form = $('form1'); }
    if(form == null) { alert("Unable to find ASP Form"); return; }
    var params = form.serialize();
    var ajaxinsert = new Ajax.Request('?ajax=true', {
            method: 'post',
            parameters: params,
            onSuccess: function(transport) { ppUpdateASPPageVars(transport); if(success != null) { success(transport); } },
            onFailure: function(transport) { if(success != null) { failure(); } }
        }
    );
}

function ppUpdateASPPageVars(transport)
{
    PrintLine("ppUpdateASPPageVars()");
    var json = "";
    try {
        json = transport.responseText.evalJSON();
    } catch(e) {
        if(e instanceof SyntaxError)
        {
            PrintLine("Malformed json response");
        } else {
            PrintLine("Unable to parse json response text!");
        }
        ppLastException = e;
        throw e;
    }
    if(json.__EVENTTARGET != null) { ppSetASPFieldValue('__EVENTTARGET', json.__EVENTTARGET); }
    if(json.__EVENTARGUMENT != null) { ppSetASPFieldValue('__EVENTARGUMENT', json.__EVENTARGUMENT); }
    if(json.__VIEWSTATE != null) { ppSetASPFieldValue('__VIEWSTATE', json.__VIEWSTATE); }
    if(json.__EVENTVALIDATION != null) { ppSetASPFieldValue('__EVENTVALIDATION', json.__EVENTVALIDATION); }
}

function ppSetASPFieldValue(fieldName, fieldValue)
{
    if($(fieldName) == null)
    {
        var input = document.createElement('input');
        input.setAttribute('type', 'hidden');
        input.setAttribute('name', fieldName);
        input.setAttribute('id', fieldName);
        input.setAttribute('value', '');
        $('form1').appendChild(input);
    }
    if($(fieldName) != null)
    {
        var before = $(fieldName).value;
        $(fieldName).value = fieldValue;
        var after = $(fieldName).value;
        if( before != fieldValue && before == after ) {
            PrintLine("Field update failed for " + fieldName);
        } else {
            PrintLine("Field update succeeded for " + fieldName);
        }
    } else {
        PrintLine("Field creation/update failed for " + fieldName);
    }
}

// ------------------------------------------------------------------------
function AjaxPostback(sender, onSuccess, onFailure, onTickerStart, onTickerStop)
{
    PrintLine("AjaxPostback()");
    if(sender == null)
    {
        if(onFailure != null)
        {
            onFailure();
        }
        PrintLine("sender is null");
        return false;
    }

    var form = $('aspnetForm');
    if(form == null) { form = $('form1'); }
    if(form == null) { alert("Unable to find ASP Form"); return; }
    
    // serialize form elements for use to mess with
    var postdata = form.serialize();
    var button_id = sender.id.gsub('_', '$');
    var newSubmitAction = "";
    var myInputs = form.getInputs();
    var formButtons = Array();

    // put together the correct submit button post data
    if(sender.type == "image")
    {
        PrintLine("Button clicked is an image button");
        newSubmitAction += "&"+encodeURIComponent(button_id) + ".x=5&"+encodeURIComponent(button_id) + ".y=5";
    } else if(sender.type == "submit") {
        PrintLine("Button clicked is a valid sender");
        newSubmitAction += "&"+encodeURIComponent(button_id) + "=" + encodeURIComponent(sender.value);
    } else {
        PrintLine("Button clicked is a NOT valid sender");
    }

    // gather inputs and arrange into possible submitters and regular buttons that don't submit
    for(var i=0, x=0, y=0;i<myInputs.length;i++)
    {
        if(myInputs[i].type == "submit" || myInputs[i].type == "button")
        {
            PrintLine("Adding for deletion: "+myInputs[i].name);
            formButtons[x++] = encodeURIComponent( myInputs[i].name) + "=" + encodeURIComponent( myInputs[i].value);
        }
    }

    // cycle through the possible submitters and replace them with the submit action we actually want.
    for(var i=0;i<formButtons.length;i++)
    {
        if( postdata.include(formButtons[i]) )
        {
            PrintLine("Deleting "+formButtons[i]);
            postdata = postdata.replace(formButtons[i], "");
        }
    }
    postdata += newSubmitAction;

    if(onTickerStart!=null) { onTickerStart(); }
    var destUrl = location.href;
    var qPos = destUrl.indexOf('?');
    if(qPos != -1) destUrl = destUrl.substring(0, qPos);
    destUrl+='?ajax=true';
    PrintLine("Ajax Post URL: "+destUrl);
    // send the request
    var ajaxinsert = new Ajax.Request(destUrl,
        {
            method: 'post',
            parameters: postdata,
            onSuccess: function(transport)
            {
                PrintLine("onSuccess triggered");
                if(onTickerStart != null)
                {
                    try {
                        onTickerStop();
                    }catch(e){
                        ppLastException = e;
                        PrintLine("onTickerStop exception!");
                    }
                }
                if( (transport.status == null || transport.status == 0) && transport.responseText == "")
                {
                    PrintLine("Status Code undefined or zero.  Unable to connect to host.");
                    PrintLine("Response Text: "+transport.responseText);
                    onFailure("Unable to connect to host.");
                    return false;
                }
                if(transport.responseText == "")
                {
                    PrintLine("transport.responseText is empty.");
                    onFailure("Empty response received.");
                    return false;
                }
                else
                {
                    PrintLine("transport.responseText is not empty.");
                }
                try
                {
                    ppUpdateASPPageVars(transport);
                }
                catch(e)
                {
                    ppLastException = e;
                    PrintLine("Unable to update ASP Page Form Variables");
                    onFailure("Internal response parser error");
                    return false;
                }
                if(onSuccess != null)
                {
                    try {
                        PrintLine("Executing onSuccess");
                        onSuccess(transport);
                    }catch(e){
                        ppLastException = e;
                        PrintLine("onSuccess exception!");
                        onFailure("Client onSuccess exception!");
                        return false;
                    }
                }
            },
            onFailure: function(transport)
            {
                PrintLine("onFailure triggered");
                if(onTickerStop != null)
                {
                    try {
                        onTickerStop();
                    }catch(e){
                        ppLastException = e;
                        onFailure("Connection failed, please try again.  Also, the AJAX ticker could not be stopped.");
                        return false;
                    }
                }
                PrintLine("transport.status: "+transport.status);
                if( transport.status >= 400 && transport.status < 500 )
                {
                    if(onFailure != null)
                    {
                        PrintLine("Executing failure function");
                        onFailure("Client Error 4xx");
                    }
                }
                else if( transport.status >= 500 && transport.status < 600 )
                {
                    if(onFailure != null)
                    {
                        PrintLine("Executing failure function");
                        onFailure("Internal Server Error: "+transport.status);
                    }
                }
                else
                {
                    if(onFailure != null)
                    {
                        PrintLine("Executing failure function");
                        onFailure("Connection failed.  Please try again.");
                    }
                }
            }
        }
    );
    return false;
}

// http://codejanitor.com/wp/2006/03/23/ajax-timeouts-with-prototype/
function callInProgress (xmlhttp)
{
    PrintLine("xmlhttp.readyState: "+xmlhttp.readyState);
    switch (xmlhttp.readyState)
    {
        case 1: case 2: case 3:
            return true;
            break;
        // Case 0/4
        default:
            return false;
            break;
    }
}

// Register global responders that will occur on all AJAX requests
PrintLine("Ajax.Responders.register");
Ajax.Responders.register(
    {
        onCreate: function(request)
        {
            PrintLine("onCreate triggered.");
            request['timeoutId'] = window.setTimeout(
                function()
                {
                    PrintLine("onTimeout triggered");
                    // If we have hit the timeout and the AJAX request is active, abort it and let the user know
                    if (callInProgress(request.transport))
                    {
                        PrintLine("Aborting Request...");
                        request.transport.abort();
                        // Run the onFailure method if we set one up when creating the AJAX object
                        if (request.options['onFailure'])
                        {
                            PrintLine("Calling failure func...");
                            request.options['onFailure'](request.transport, request.json);
                        }
                    } else {
                        PrintLine("Call is not in Progress, no abort necessary.");
                    }
                },
                30000
            );
        },
        onException: function(request, e)
        {
            PrintLine("onException triggered: "+e);
            ppLastException = e;
            request.transport.abort();
            if (request.options['onFailure'])
            {
                PrintLine("Calling failure func...");
                request.options['onFailure'](request.transport, request.json);
            }
        },
        onComplete: function(request) {
            PrintLine("onComplete triggered.");
            PrintLine("Clearing timeout timer");
            // Clear the timeout, the request completed ok
            window.clearTimeout(request['timeoutId']);
        }
    }
);

