﻿
//CONSTRUCTOR FOR THE HRD_AJAXCLIENT OBJECT
function AjaxClient() {
    this.DeclareVariables = DeclareVariables;
    this.DeclareFunctions = DeclareFunctions;

    this.DeclareVariables();
    this.DeclareFunctions();

} //HRD_AjaxClient 

//FUNCTION DECLARING ALL THE VARIABLES NEEDED
function DeclareVariables() {
    this.baseUrl = ''; //THE URL OF THE SERVER
    this.callType = 'GET'; //THE TYPE OF CALL TO BE MADE
    this.command = ''; //THE COMMAND TO BE EXECUTED ON THE GIVEN URL
    this.async = true; //BOOLEAN DETERMINING WHETHER OR NOT THE CALL IS MADE ASYNCHRONOUSLY

    this.parameters = null; //ARRAY OF PARAMETER OBJECTS USED IN POST REQUESTS
    this.responseHandler = null; //DELEGATE FOR THE METHOD WHICH WILL HANDLE THE SERVER RESPONSE

    this.returnsXML = false; //BOOLEAN DETERMINING WHETHER THE REQUEST RETURNS XML OR TEXT
    this.requestObject = null; //THE REQUEST OBJECT

} //DeclareVariables

//FUNCTION DECLARING ALL THE FUNCTIONS AVAILABLE
function DeclareFunctions() {
    //PROPERTY SETTERS
    this.SetUrl = SetUrl;
    this.SetCallType = SetCallType;

    this.SetCommand = SetCommand;
    this.SetAsync = SetAsync;

    this.AddParameter = AddParameter;
    this.ClearParameters = ClearParameters;

    this.SetTypeToPost = SetTypeToPost;
    this.SetTypeToGet = SetTypeToGet;

    this.SetResponseHandler = SetResponseHandler;

    this.ReturnXML = ReturnXML;

    //FUNCTIONAL FUNCTIONS
    this.GetUrl = GetUrl;

    this.GetUpperType = GetUpperType;
    this.GetLowerType = GetLowerType;

    this.GetParameters = GetParameters; //FUNCTION USED TO 'COMPILE' THE PARAMETERS IN A SUITABLE QUERY STRING

    this.GetResponseXML = GetResponseXML;
    this.GetResponseText = GetResponseText;
    this.GetResponseDOM = GetResponseDOM;
    this.GetResponseFragment = GetResponseFragment;
    this.GetResponseFragmentByTag = GetResponseFragmentByTag;

    this.InitializeRequest = InitializeRequest; // INITIALIZE THE REQUEST OBEJCT
    this.ExecuteRequest = ExecuteRequest; //EXECUTES THE AJAX REQUEST
    this.HandleServerResponse = HandleServerResponse; //METHOD HANDLING THE ONREADYSTATECHANGE OF THE REQUEST OBJECT

} //DeclareFunctions

/*
------------------------------------------------------------------
PROPERTY SETTERS OF THE AJAX CLIENT 
------------------------------------------------------------------
*/

function SetUrl(url) { this.baseUrl = url; } //SetUrl
function SetCallType(type) { this.callType = type; } //SetCallType
function SetCommand(command) { this.command = command; } //SetCommand 
function SetAsync(async) { this.async = async; } //SetAsync

function SetTypeToPost() { this.SetCallType('POST'); } //SetTypeToPost
function SetTypeToGet() { this.SetCallType('GET'); } //SetTypeToGet

//FUNCTION USED TO ADD A PARAMETER TO THE ARRAY
function AddParameter(name, value) {
    if (this.parameters === null)
        this.parameters = new Array();

    this.parameters[this.parameters.length] = new Parameter(name, value);
} //AddParameter

//FUNCTION USED TO CLEAR THE PARAMETER ARRAY
function ClearParameters() {
    if (this.parameters !== null)
        this.parameters.length = 0;
} //ClearParameters

function ReturnXML(returnXML) { this.returnsXML = returnXML; } //ReturnXML

function SetResponseHandler(responseHandler) { this.responseHandler = responseHandler; } //SetResponseHandler

/*
------------------------------------------------------------------
PROPERTY GETTERS OF THE AJAX CLIENT 
------------------------------------------------------------------
*/
//FUNCTION USED TO RETRIEVE THE URL. IF A COMMAND IS SPECIFIED, IT IS APPENDED AS A QUERYSTRING TO THE BASE URL
function GetUrl() {
    var urlFormat = '{0}{1}';
    var sb = new StringBuilder();

    //sb.Append ( this.baseUrl );

    if (this.command != '') {
        sb.Append('?');
        sb.Append(this.GetLowerType());
        sb.Append('=');
        sb.Append(this.command);
    } //if
    else if (this.GetUpperType() == 'POST') {
        sb.Append('?');
        sb.Append(this.GetLowerType());
        sb.Append('=');
        sb.Append('true');
    } //else if

    var params = this.GetParameters();

    if (params !== null) {
        sb.Append((sb.GetLength() > 0) ? '&' : '?');
        sb.Append(this.GetParameters());
    } //if

    var retUrl = Format(urlFormat, this.baseUrl, sb.ToString());

    return retUrl;

} //GetUrl

function GetUpperType() {
    return this.callType.toUpperCase();
} //GetUpperType

function GetLowerType() {
    return this.callType.toLowerCase();
} //GetLowerType

//FUNCTION USED TO CONCATINATE THE PARAMETERS IN A STRING, ONLY IF THE CALL TYPE IS 'POST'
function GetParameters() {
    if ((this.parameters === null) || (this.parameters.length == 0))
        return null;

    var sBuilder = new StringBuilder();

    for (var i = 0; i < this.parameters.length; i++) {
        if (i > 0) sBuilder.Append('&');

        sBuilder.Append(this.parameters[i].name);
        sBuilder.Append('=');
        sBuilder.Append(this.parameters[i].value);
    } //for

    return sBuilder.ToString();

} //GetParameters

function GetResponseXML() {
    if (this.requestObject !== null)
        return this.requestObject.responseXML;
    else
        return undefined;
} //GetResponseXML

function GetResponseText() {
    if (this.requestObject !== null)
        return this.requestObject.responseText;
    else
        return undefined;
} //GetResponseText


function GetResponseDOM()//HTMLstring)
{
    var text = this.GetResponseText();

    if (text === undefined)
        return undefined;

    var d = document.createElement('div');
    d.innerHTML = text;
    var docFrag = document.createDocumentFragment();

    while (d.firstChild)
        docFrag.appendChild(d.firstChild)

    return docFrag;
} //GetResponseDOM

function GetResponseFragment() {
    var docFrag = this.GetResponseDOM();

    if (docFrag === undefined)
        return undefined;

    var dc = docFrag.childNodes;

    var f = null;

    for (var i = 0; i < dc.length; i++)
        if (dc[i].tagName == 'FORM')
        f = dc[i];

    return f;
} //GetResponseFragment 

function GetResponseFragmentByTag(elementName, idName) {
    var f = this.GetResponseFragment();

    if (f !== undefined) {
        var elems = f.getElementsByTagName(elementName);

        for (var i = 0; i < elems.length; i++)
            if (elems[i].id == idName)
            return elems[i].innerHTML;

        return '';
    } //else

    return undefined;
} //GetResponseFragmentByTag

/*
------------------------------------------------------------------
REQUEST EXECUTION FUNCTIONS OF THE AJAX CLIENT 
------------------------------------------------------------------
*/

//FUNCTION USED TO INITIALIZE THE REQUEST OBJECT
function InitializeRequest(url, responseHandler, command, type) {
    if (url !== undefined)
        this.SetUrl(url);

    if (responseHandler !== undefined)
        this.SetResponseHandler(responseHandler);

    if (command !== undefined)
        this.SetCommand(command);

    if (type !== undefined)
        this.SetCallType(type);

} //InitializeRequest

//FUNCTION USED TO EXECUTE A REQUEST USING THE SET PROPERTIES AND VARIABLES
function ExecuteRequest() {
    window['ajaxClient'] = this;

    var paramString = this.GetParameters();
    var callType = this.GetUpperType();

    this.requestObject = GetRequestObject();

    this.requestObject.open(callType, this.GetUrl(), this.async);

    if (callType == 'POST') {
        this.requestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        this.requestObject.setRequestHeader("Content-length", ((paramString === null) ? 0 : paramString.length));
    } //if

    if (this.async) {
        this.requestObject.onreadystatechange = HandleServerResponse;
        this.requestObject.send(paramString);
    } //if
    else {
        this.requestObject.send(paramString);

        var retVal = ((this.returnsXML) ? this.requestObject.responseXml : this.requestObject.responseText);

        this.responseHandler(retVal);
        this.ClearParameters();
    } //if	  
} //ExecuteRequest

//FUNCTION USED TO HANDLE THE SERVER RESPONSE
function HandleServerResponse() {
    var client = window['ajaxClient'];

    if (client.requestObject.readyState == 4) {
        var retVal = ((client.returnsXML) ? client.GetResponseXML() : client.GetResponseText());
        client.responseHandler(retVal);
        client.ClearParameters();
    } //if is Ready
} //HandleServerResponse

/*
------------------------------------------------------------------
STATIC FUNCTIONS USED BY THE AJAX CLIENT 
------------------------------------------------------------------
*/

//FUNCTION USED TO CREATE A REQUEST OBJECT
function GetRequestObject() {
    var requestObject = null;

    if (window.ActiveXObject)
        requestObject = new ActiveXObject("Microsoft.XMLHTTP");
    else if (window.XMLHttpRequest)
        requestObject = new XMLHttpRequest();

    return requestObject;
} //GetRequestObject

/*
------------------------------------------------------------------
SECONDARY OBJECTS USED BY HRD_AjaxClient 
------------------------------------------------------------------
*/

//STRING BUIDLER OBJECT USED TO CONCATINATE STRINGS IN ONE VARIABLE
function StringBuilder() {
    this._strings = [];
    this.Append = function(s) { if (s !== null) this._strings.push(s); };
    this.GetLength = function() { return (this.ToString()).length; }
    this.ToString = function() { return this._strings.join(''); };
} //StringBuilder

//PARAMTER OBJECT USED TO CONTAIN THE PARAMETERS TO BE SENT TO THE SERVER
function Parameter(name, value) {
    this.name = name;
    this.value = value;
} //Parameter

//FUNCTION PROVIDING THE FUNCTIONALITY SIMILIAR TO THAT OF C# STRING.FORMAT 
function Format(str) {
    for (i = 1; i < arguments.length; i++)
        str = str.replace('{' + (i - 1) + '}', arguments[i]);

    return str;
} //StrFormat

function CurrentURL() {
    var url = location.href
    url = url.substring(0, url.indexOf('.com') + 4);
    return url;
} //CurrentURL

