/**
 * Copyright (c) 2005-2006
 *      Marc Wandschneider. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name Marc Wandschneider may not be used to endorse or promote
 *    products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; DEATH OF YOUR PET CAT, DOG, OR FISH; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

var _global = this;

function getNewHTTPObject()
{
        var xmlhttp;

        /** Special IE only code ... */
        /*@cc_on
          @if (@_jscript_version >= 5)
              try
              {
                  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
              }
              catch (e)
              {
                  try
                  {
                      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                  }
                  catch (E)
                  {
                      xmlhttp = false;
                  }
             }
          @else
             xmlhttp = false;
        @end @*/

        /** Every other browser on the planet */
        if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
        {
            try
            {
                xmlhttp = new XMLHttpRequest();
            }
            catch (e)
            {
                xmlhttp = false;
            }
        }

        return xmlhttp;
}




function FormPayjacksAjax(in_form, in_url, in_callback)
{
    this.formElement = in_form;
    this.sendUrl = in_url;
    this.callbackFunction = in_callback;
    this.xmlHttpObject = null;
}


FormPayjacksAjax.prototype.submitForm = function()
{
    var postData = '';

    for (var x = 0; x < this.formElement.elements.length; x++)
    {
        if (this.formElement.elements[x].type == 'submit')
            continue; 

        if (this.formElement.elements[x].type == 'radio'
            && this.formElement.elements[x].checked == false)
            continue;

        if (postData != '')
            postData += '&';

        postData += this.formElement.elements[x].name;
        postData += '=';

        /**
         * For checkboxes, we'll special case them and send the values as 
         * true or false since that's far more palatable.
         */
        if (this.formElement.elements[x].type == 'checkbox')
        {
            if (this.formElement.elements[x].checked)
                postData += 'true';
            else
                postData += 'false';
        }
        else if (this.formElement.elements[x].type == 'radio')
        {
            if (this.formElement.elements[x].checked)
                postData += this.formElement.elements[x].value;
        }
        else
        {
            postData += encodeURIComponent(this.formElement.elements[x].value);
        }
    }

    return this.sendToServer(postData);
    
}


FormPayjacksAjax.prototype.sendToServer = function(in_postData)
{
    this.xmlHttpObject = getNewHTTPObject();

    var varName = "payjacksV" + (Math.floor(Math.random() * 100000000));
    _global[varName] = this;

    var str = " \
        var fpa = _global['" + varName + "'];\n\
        if (fpa.xmlHttpObject.readyState != 4)\n\
            return;\n\
        var results = fpa.xmlHttpObject.responseText + \n\
                      \"_global['" + varName + "'].callbackFunction(new PayjacksResponseObject())\"\n\
        eval(results);\n\
        _global['" + varName + "'] = null;";

    this.xmlHttpObject.onreadystatechange = new Function(str);

    this.xmlHttpObject.open('POST', this.sendUrl, true);
    this.xmlHttpObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    this.xmlHttpObject.send(in_postData);

    return false;
}




/**
 * You can use the DirectPayjacksAjax object in three ways.
 *
 * 1. You can just create it and tell it to execute the URL.
 *
 *     (new DirectPayjacksAjax(URL, 'callbackFunctionName')).submit();
 *
 * 2. You can pass it a string which will be sent as POST data
 *    to the URL:
 *
 *     (new DirectPayjacksAjax(URL, 'callbackFunctionName')).submit("data=extra%20data%20to%20send");
 *
 * 3. You can pass it an array, which will contain an even number of
 *    items -- name/value pairs.
 *
 *    var data = new Array("name", "Marc", "address", "china", "age", 85);
 *     (new DirectPayjacksAjax(URL, 'callbackFunctionName')).submit(data);
 */
function DirectPayjacksAjax(in_url, in_callback)
{
    this.sendUrl = in_url;
    this.callbackFunction = in_callback;
    this.xmlHttpObject = null;
}


DirectPayjacksAjax.prototype.submit = function()
{
    var postData = '';
    var i;

    if (arguments.length == 1)
    {
        if ((typeof arguments[0]) == "string")
        {
            postData = arguments[0];
        }
        else if ((typeof arguments[0]) == "object")
        {
            if (arguments[0].length % 2 == 0)
            {
                for (i = 0; i < arguments[0].length; i += 2)
                {
                    if (postData != '') postData += "&";
                    postData += arguments[0][i] + "=" + arguments[0][i + 1];
                }
            }
        }
    }

    return this.sendToServer(postData);
}


DirectPayjacksAjax.prototype.sendToServer = function(in_postData)
{
    this.xmlHttpObject = getNewHTTPObject();

    var varName = "payjacksV" + (Math.floor(Math.random() * 100000000));
    _global[varName] = this;

    var str = " \
        var fpa = _global['" + varName + "'];\n\
        if (fpa.xmlHttpObject.readyState != 4)\n\
            return;\n\
        var results = fpa.xmlHttpObject.responseText + \n\
                      \"_global['" + varName + "'].callbackFunction(new PayjacksResponseObject())\"\n\
        eval(results);\n\
        _global['" + varName + "'] = null;";

    this.xmlHttpObject.onreadystatechange = new Function(str);

    this.xmlHttpObject.open('POST', this.sendUrl, true);
    this.xmlHttpObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    this.xmlHttpObject.send(in_postData);

    return false;
}

