﻿// JScript File
// Contains extensions to perform callbacks to ASP.NET scripts and services.
// Based on prototype.js (1.5.0)

// use to call a service or arbitrary URL on the server
function callServer(callbackURI, arg, ctrlID, ReceiveServerData, ProcessError) 
{    // sub $ for _ in control ID, as per MS
    var dollarCtrlID = ctrlID.substring(0,1) + ctrlID.substring(1,ctrlID.length).replace(/_/g,'$');
    // create the request arguments
    var postHash = {
        __CALLBACKID: dollarCtrlID, 
        __CALLBACKPARAM: arg,
        __EVENTARGUMENT: '',
        __EVENTTARGET: ''
    };
    if ($('__EVENTVALIDATION')) { postHash.__EVENTVALIDATION = $('__EVENTVALIDATION').value; }
    // send the request and get the callback to the success/failure functions passed in above.
    new Ajax.Request(callbackURI, {
        method: 'post', 
        parameters: postHash, 
        onSuccess: function(transport) { ReceiveServerData(transport.responseText); },
        onFailure: function(transport) { ProcessError(transport.responseText); }    
    });
}
// use to perform a callback to the same page
function callMeBack(arg, ctrlID, ReceiveServerData, ProcessError) {
    // get the URL from the current document, then perform a callback as above.
    var callbackURI = document.forms[0].action;
    if (theForm) { callbackURI = theForm.action; }
    callServer(callbackURI, arg, ctrlID, ReceiveServerData, ProcessError);
}

// use to send a SOAP 1.2 request to a MS Web Service
function callSOAPService(callbackURI, serviceNameSpace, methodName, proxyName, params, ReceiveServerData, ProcessError) {
    serviceNameSpace = (serviceNameSpace == '') ? 'http://www.orvis.com' : serviceNameSpace;
    var xml; xml = '<?xml version="1.0" encoding="utf-8"?>';
    xml += '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
    xml += '<soap12:Body><' + methodName + ' xmlns="' + serviceNameSpace + '">';
    if (proxyName != '') {xml += '<' + proxyName + '>';}
    for (p in params) { 
        xml += '<' + p + '>' + eval('params.' + p) + '</' + p + '>';
    } 
    if (proxyName != '') {xml += '</' + proxyName + '>';}
    xml += '</' + methodName + '></soap12:Body>';
    xml += '</soap12:Envelope>';
    //alert(xml);
    new Ajax.Request(callbackURI, { 
        method: 'post', 
        contentType: 'application/soap+xml; action=' + serviceNameSpace + '/' + methodName, 
        postBody: xml, 
        onSuccess: function(transport) { 
        if (window.DOMParser)
          {
          parser=new DOMParser();
          xmlDoc=parser.parseFromString(transport.responseText,"text/xml");
          }
        else // Internet Explorer
          {
          xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async="false";
          xmlDoc.loadXML(transport.responseText); 
          }
          ReceiveServerData(xmlDoc); 
        },
        onFailure: function(transport) {ProcessError(transport.responseText); }    
    });
};

//Used to send a JSON based Web Service Request to the server
//Note: The __type property must be the first JSON property of an object to ensure proper serialization/deserialization
function CallJSONService(callbackURI, methodName, params, ReceiveServerData, ProcessError) {
    new Ajax.Request(callbackURI + '/' + methodName, { 
        method: 'post', 
        contentType: 'application/json',        //Informs the server that it should respond as JSON and serialize/deserialize
        postBody: Object.toJSON(params),  //Turns the parameters into JSON strings
        onSuccess: function(response) { ReceiveServerData(response.responseJSON); },   //Response is already parsed as JSON  with the 
        onFailure: function(response) { ProcessError(response.responseJSON); }                //responseJSON property
    });
}


//Used to call an aspx page on the server to generate a string of either HTML or JSON
// transportType can be [ 'JSON' | 'XML' | 'TEXT' | 'ARRAY' | <custom> ]
function CallPageService(callbackURI, methodName, params, ReceiveServerData, ProcessError, transportType) {
    if (typeof(traceMe) == 'undefined') { traceMe = ''; }
    traceMe += "CallPageService-->";
    var contentType, successFunction, failFunction;
    successFunction = function(response) { ReceiveServerData(response.responseText); };
    failFunction = function(response) { ProcessError(response.responseText); };
    
    switch (transportType.toUpperCase()) {
        case 'XML' :
            params = FormatXMLParams(params);
            contentType = 'application/xml';
            methodName += '&KBH=true';
            successFunction = function(response) { ReceiveServerData(response); };
            break;
        case 'JSON' :
            params = (params == null ? null : Object.toJSON(params));
            contentType = 'application/json';
            successFunction = function(response, json) { ReceiveServerData(response.responseText); };
            failFunction = function(response, json) { ProcessError(response.responseText); };
            break;
        default :
            contentType = 'application/x-www-form-urlencoded';
            methodName += '&KBH=true';
    }
    
    new Ajax.Request(callbackURI + '?methodName=' + methodName + '&transport=' + transportType.toUpperCase(), { 
        method: 'post',     
        contentType: contentType,
        postBody: params,
        onSuccess: successFunction,   
        onFailure: failFunction, 
        onException: function(response, exception) { LogError(response.responseText + traceMe, exception); }
    });
}

//Helper function to turn the basic object into XML
//Will do objects inside of the object recursively.
function FormatXMLParams(params) { return '<params>' + FormatXML(params) + '</params>'; };
function FormatXML(params){    
    var xml = '';
    for (var p in params) {
        if (typeof(params[p]) != 'function') {
            xml += '<' + p + '>';
            //alert(p + ': ' + typeof(params[p]));
            if (typeof(params[p]) == 'object') {
                xml += FormatXML(params[p]);            
            } else {
                xml += params[p];
            }
            xml += '</' + p + '>';
        }        
    } 
   return xml; 
}

//Generic function to handle and log failed server side calls
//That result in client side error messages
function FailedCallback(error)
{
    var errorString = '';
   
   errorString += 'Message:==>' + error.Message + '\n\n';
   errorString += 'StackTrace:==>' + error.StackTrace + '\n\n';
   errorString += 'ExceptionType:==>' + error.ExceptionType;

    alert(errorString);
        
}

var LogError = function(msg, exception) {
    var callbackURI = "/services/LoggingService.asmx";
    var methodName = "LogClientError";
    if (typeof(exception) != 'undefined') { msg += Object.toJSON(exception); }
    var params = { "message": msg }
    var ReceiveServerData = function(r) { if (r.retStatus == 'False') { alert('Unable to log error:' + msg) }};
    var ProcessError = function(r) { alert('Server Error. Unable to log error: ' + msg); };
    CallJSONService(callbackURI, methodName, params, ReceiveServerData, ProcessError);
}
