﻿/* This is exactly like the one in lib.js, except it also hands back the viewstate (it's 2 lines different) */
var FormFunctionsWithViewstate = new function() {

    var me = this;

    /* safe param */
    this.SafeParam = function(sParam) {
        if (sParam.replace) {
            return sParam.replace(/&/g, '&amp;').replace(/\|/g, '/\\pipe\\/');
        } else if (sParam.getDate && sParam.getUTCFullYear && sParam.toDateString) { // attempt to find out whether sParam is a Date object
            return d.ToSQLDate(sParam);
        } else {
            return sParam;
        }
    }

    /* call */
    this.Call = function(FunctionName, CallBack) {

        //work out the params
        var sParams = '';
        for (var i = 2; i <= this.Call.arguments.length - 1; i++) {
            sParams += this.SafeParam(this.Call.arguments[i]) + '|'
        }
        if (sParams != '') { sParams = s.Chop(sParams); }

        //build up the url
        var sURL = window.location.href;
        if (s.Right(sURL, 1) == '#') {
            sURL = s.Chop(sURL);
           }

           if (s.Right(sURL, 1) == '/') {
           	sURL += 'default.aspx';
           }

        sURL += '?executeformfunction';
        sURL += '&function=' + FunctionName;
        sURL += '&params=' + encodeURIComponent(sParams);

        //request
        var oRequest;
        if (window.XMLHttpRequest) {
            oRequest = new XMLHttpRequest();
            oRequest.open("POST", sURL, true);
        } else {
            oRequest = new ActiveXObject("Microsoft.XMLHTTP");
            oRequest.open("POST", sURL, true);
        }
        oRequest.onreadystatechange = function() {
            if (oRequest.readyState == 4) {
                if (oRequest.status != 200 && window.location.toString().indexOf('localhost') > -1) {
                    alert(oRequest.responseText);
                    return;
                }
                ff.Response(oRequest.responseText, CallBack);
            }
        }

        /* send viewstate back */
        oRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        var sParam = '__VIEWSTATE=' + encodeURIComponent(f.GetValue('__VIEWSTATE'));
        oRequest.send(sParam);
    }



    /* response */
    this.Response = function(sResponse, oCallBack) {

        if (typeof (oCallBack) == 'string') {
            eval(oCallBack + '(\'' + s.Replace(sResponse, '\'', '\\\'') + '\')');
        } else if (typeof (oCallBack == 'function')) {
            oCallBack(sResponse);
        }
    }

}
