﻿// IIS-Hosted Service (se debe colocar la url que corresponda para cada implementación)
var WebSiteServiceURL_IIS = "http://www.jerarquicossalud.com.ar/jswebsvc/serviciowebsite.svc/";
//var WebSiteServiceURL_IIS = "http://localhost:8089/WebSiteHost/ServicioWebSite.svc/";
// Self-Hosted Service
var WebSiteServiceURL_SHS = "http://localhost:8089/WebSiteHost/ServicioWebSite.svc/";

// El valor de esta variable se modificará automáticamente durante la generación en Deploy a WebSiteServiceURL_IIS.
var WebSiteServiceURL = WebSiteServiceURL_IIS;

var WebSiteServiceProxy = new serviceProxy(WebSiteServiceURL);
var AJAXError = $('#AJAXError');

// Función que activa el Overlay y muestra un mensaje parametrizado o por defecto
function wjBlockUI(msg) {

    var defaultMsg = 'Procesando...<br/><img src="http://www.jerarquicossalud.com.ar/jswebhost/images/activity.gif" />';

    if (null != msg) {
        defaultMsg = msg + '<br/><img src="http://www.jerarquicossalud.com.ar/jswebhost/images/activity.gif" />';
    }

    $.blockUI({ overlayCSS: { backgroundColor: '#aaa' }, message: defaultMsg });

}

// *** Generic Service Proxy class that can be used to 
// *** call JSON Services generically using jQuery
// *** Depends on JSON2 modified for MS Ajax usage
function serviceProxy(wjOrderServiceURL) {
    var _I = this;
    this.ServiceURL = wjOrderServiceURL;

    // *** Call a wrapped object
    this.invoke = function(options) {

        // Default settings
        var settings = {
            serviceMethod: '',
            data: null,
            callback: null,
            error: null,
            type: "POST",
            processData: false,
            contentType: "application/json",
            timeout: 120000, //Not Preferable, but needed for now.
            dataType: "text",
            bare: false
        };

        if (options) {
            $.extend(settings, options);
        }

        // *** Convert input data into JSON - REQUIRES Json2.js
        var json = JSON2.stringify(settings.data);

        // *** The service endpoint URL
        var url = _I.ServiceURL + settings.serviceMethod;

        $.ajax({
            url: url,
            data: json,
            type: settings.type,
            processData: settings.processData,
            contentType: settings.contentType,
            timeout: settings.timeout,
            //error: settings.error,
            dataType: settings.dataType,
            success:
                    function(res) {
                        if (!settings.callback) { return; }

                        // *** Use json library so we can fix up MS AJAX dates
                        var result = JSON2.parse(res);

                        if (result.ExceptionDetail) {
                            OnPageError(result.Message);
                            return;
                        }

                        // *** Bare message IS result
                        if (settings.bare)
                        { settings.callback(result); return; }

                        //http://encosia.com/2009/07/21/simplify-calling-asp-net-ajax-services-from-jquery/
                        if (result.hasOwnProperty('d')) {

                            //// Si se produjo un fallo y el mensaje no es vacío lo muestro
                            //if (result.d.Resultado == 0 && result.d.Mensaje != '') {

                            //   OpenDialog(result.d.Mensaje, 'Error en: ' + settings.serviceMethod);
                                
                            //    // Corto la ejecución del CallBack
                            //    return;
                            //}

                            return settings.callback(result.d);
                        }
                        else {
                            return result;
                        }


                        // *** Wrapped message contains top level object node
                        // *** strip it off
                        //                        for (var property in result) {
                        //                            settings.callback(result[property]);
                        //                            break;
                        //                        }
                    }
        });
    };
}

function OpenDialog(mensaje, titulo) {
    $.unblockUI();
    $('#jqDialog').dialog({        
        width: 400,
        modal: true,
        title: titulo,
        buttons: {
            "Ok": function() {
                $(this).dialog("close");
            }
        }
    });
    $('#jqDialogMessage').show();
    if (mensaje == "") {
        mensaje = "Sin descripción, comuniquese con el dpto. de sistemas."; 
    }
    $('#jqDialogMessage').text(mensaje);
    $('#jqDialog').dialog();
}

function OnPageError(xhr, errorMsg, thrown) {

    if (typeof xhr == "string") {
        showErrorMsg(xhr);
        return;
    }
    else if (typeof (xhr.responseText) == "string" && xhr.responseText != "") {
        var err = null;
        
        try {
            err = JSON2.parse(xhr.responseText);
        }
        catch (e) {
            showErrorMsg(xhr.responseText);
            return;
        }
        
        switch (err.ExceptionType) {

            case 'System.Exception':
                showErrorMsg(err.Message);
                return;
            default:
                showErrorMsg(xhr.responseText);
                return;
        }
    } else {
        showErrorMsg("Unknown error occurred in callback.");
    }

}

function showErrorMsg(Msg) {

    if (!AJAXError || AJAXError.length === 0) {//If the error element was added after $.Ready we need to regrab it.
        AJAXError = $("#AJAXError");
    }

    AJAXError.show();
    AJAXError.insertStatusMessage({ statusMessage: Msg });
}

//Error Handling
function postErrorAndUnBlockUI(xhr, errorMsg, thrown) {
    $.unblockUI();
    OnPageError(xhr, errorMsg, thrown);
}

$.fn.insertStatusMessage = function (options) {

    if (this.length === 0) { return };

    // Default settings
    var settings = {
        msgElement: "<div class='{1}'>{0}</div>",
        statusMessage: "[Status Message]",
        msgClass: 'Confirm-Message-Area',
        insertAfter: true,
        timeOutTime: 5000,
        fadeOutTime: 5000
    };
    if (options) {
        $.extend(settings, options);
    }

    var strMsg = settings.msgElement.replace("{0}",
        settings.statusMessage).replace("{1}", settings.msgClass);

    if (settings.insertAfter) {
        $(this).after(strMsg);
    } else {
        $(this).html(strMsg);
    }

    var msgClassSelector = "." + settings.msgClass;

    if ($(msgClassSelector).length > 0) {

        if (settings.timeOutTime > 0) {
            var t = setTimeout(
            function () {
                if (settings.fadeOutTime > 0) {
                    $(msgClassSelector).fadeOut(settings.fadeOutTime);
                } else {
                    $(msgClassSelector).hide();
                }
            }, settings.timeOutTime);
        } else {
            if (settings.fadeOutTime > 0) {
                $(msgClassSelector).fadeOut(settings.fadeOutTime);
            }
        }
    }

};


//Cargar una página como PopPup
    function PopWindow(pagina) {
        var opciones = "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=750, height=500";// top=50, left=50";
        window.open(pagina, "", opciones);
    }

//function PopWindow(pagina) {
//    var opciones = "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=750, height=500, top=50, left=50";
//    window.open(pagina, "", opciones);
    //}

    function PageInit() {
        $dialog = $('<div></div>')
       .dialog({
           autoOpen: false,
           title: 'Jerarquicos Salud',
           modal: false
       });
    }

    //Función que muestra el div flotante con el mensaje 
    function MostrarMensajeModal(mensajeTexto) {
        $dialog.text(mensajeTexto);
        $dialog.dialog('open');
    }
