﻿var vajaxpostcallinprogress = false;
var vajaxpostcallstack = new Array();

function AjaxPost(form, targetElement) {
    //object instance variables
    this.inputs = form.getElementsByTagName("input");
    this.selects = form.getElementsByTagName("select");
    this.form = form;
    this.loadingHTML = "";
    this.target = targetElement;
    this.url = form.action;
    this.callback = null;
    var me = this;

    //object instance methods
    this.paramString = function () {
        var ret = "";
        for (var i = 0; i < this.inputs.length; i++) {
            if (this.inputs[i].type == "hidden" || this.inputs[i].type == "text")
                ret += this.inputs[i].name + "=" + this.inputs[i].value + "&";
            else if ((this.inputs[i].type == "radio" || this.inputs[i].type == "checkbox") && this.inputs[i].checked)
                ret += this.inputs[i].name + "=" + this.inputs[i].value + "&";
        }
        for (var i = 0; i < this.selects.length; i++) {
            if (this.selects[i].name != "") {
                ret += this.selects[i].name + "=" + this.selects[i].options[this.selects[i].selectedIndex].value + "&";
            }
        }
        ret = ret.substr(0, ret.length - 1);
        return ret;
    };
    this.insertAjax = function () {
        if (vajaxpostcallinprogress) {
            vajaxpostcallstack.push(this);
            return;
        }
        vajaxpostcallinprogress = true;
        this.setLoadingDiv();
        this.postAjaxCall();
    };
    this.postAjaxCall = function () {
        xmlhttp = false;
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            xmlhttp = new XMLHttpRequest();
            if (xmlhttp.overrideMimeType) {
                // set type accordingly to anticipated content type
                //xmlhttp.overrideMimeType('text/xml');
                xmlhttp.overrideMimeType('text/html');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) { }
            }
        }
        if (!xmlhttp) {
            alert('Cannot create XMLHTTP instance');
            return false;
        }
        xmlhttp.onreadystatechange = function () {
            me.stateChange();
        }; 
        xmlhttp.open('POST', this.url, true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        try {
            xmlhttp.setRequestHeader("Content-length", parameters.length);
            xmlhttp.setRequestHeader("Connection", "close");
        }
        catch (Error) { }
        //        alert(this.paramString());
        xmlhttp.send(this.paramString());
    };
    this.setLoadingDiv = function () {
        this.target.innerHTML = this.loadingHTML;
    };


    this.stateChange = function () {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200 || xmlhttp.status == 0) {
                if (typeof (me.callback) == "function") {
                    me.callback();
                }
                me.target.innerHTML = xmlhttp.responseText;
            }
            else {
                alert("There was a problem in the returned data");
            }
            vajaxpostcallinprogress = false;
            if (vajaxpostcallstack.length > 0) {
                var next = vajaxpostcallstack.pop();
                next.insertAjax();
            }

        }
    };
}

function jQueryLoadHelper(element, wrapper, url, usePost) 
{
    $.ajaxSetup({
        cache: false
    });  
    
    //Add this to the wrapper so that we can style in some sort of loading element
    var ajax_load_element = "<span class='ajaxLoading'>&nbsp;</span>";

    // have to eval so that we can create the keyvalue pairs from controls as a property list for the .load method
    if (usePost)
        eval('wrapper.html(ajax_load_element).load(url,' + jQueryBuildQueryString(element, usePost) + ')');
    else
        wrapper.html(ajax_load_element).load(url + jQueryBuildQueryString(element, usePost));

    return false;
}

function jQueryBuildQueryString(node, usePost) 
{
    var returnVal = null;

    //This will use the get method and dump values on the querystring
    if (!usePost)
    {
        returnVal = "";
        node
        .find('input:text, input:checked, input:hidden, select, textarea')
        .each(function () {
            var element = $(this);
            var name = element.attr("name");
            var value = element.val();
            if (name != null && name.length > 0 && value != null && value.length > 0)
                returnVal += '&' + name + '=' + escape(value);
        });
    }
    //This will use the post method to make it seem like it was posted directly from the form
    else
    {
        returnVal = '{';
        node
        .find('input:text, input:checked, input:hidden, select, textarea')
        .each(function () {
            var element = $(this);
            var name = element.attr("name");
            var value = element.val();
            if (name != null && name.length > 0 && value != null && value.length > 0) {
                if (returnVal != '{')
                    returnVal += ',';
                returnVal += name + ' : "' + escape(value) + '"';
            }
        });
        returnVal += '}';
    }
    
    return returnVal;
}
