﻿/// <reference path="/progettogestionale/client_lib.js" />
/// <reference path="/progettogestionale/gASPnet/jsLib/js/jquery-1.4.1-vsdoc.js" />

// Produzione
var upload_svc_url = "/progettogestionale/gASPnet/uploadFileSvc.aspx";
var jsLib_svc_url = "/progettogestionale/gASPnet/jsLibSvc.aspx";

// Sviluppo
//var upload_svc_url = "http://localhost:56251/progettogestionale/gASPnet/uploadFileSvc.aspx";
//var jsLib_svc_url = "http://localhost:56251/progettogestionale/gASPnet/jsLibSvc.aspx";
var GDlib = {
    varType : function(obj) {
		if (!obj) return "null";
        var type = typeof obj;

        if (type == 'object') {

			try{
            	if (obj.getDate) return 'date';
			} catch(e){}

            try{
				if (obj.split) return 'string';
			} catch(e){}

            return 'object';
        } 
//            else {
//                try{
//                    var s = obj / 5;
//                    return 'Numeric;'
//                }catch(e){}
//            }
     return type;
    }
 }

// Definizione del tipo Anagrafica
function anag_type(jSonStr) {
    var obj = $.parseJSON(jSonStr);
    this.id_anagrafica = obj.id_anagrafica;
    this.cognome = obj.cognome;
    this.nome = obj.nome;
    this.indirizzo = obj.indirizzo;
    this.cap = obj.cap;
    this.citta = obj.citta;
    this.provincia = obj.provincia;
    this.email = obj.email;
    this.telefono = obj.telefono;
 }
function OpzioneComboTipo_type(jSonStr) {
    var obj = $.parseJSON(jSonStr);
    this.id_opzione_combo_tipo = obj.id_opzione_combo_tipo;
    this.codice_di_sistema = obj.codice_di_sistema;
    this.descrizione = obj.descrizione;
    this.selezione_multipla = obj.selezione_multipla;
 }
function OpzioneCombo_type(jSonStr) {
    var obj = $.parseJSON(jSonStr);
    this.id_opzione_combo = obj.id_opzione_combo;
    this.id_opzione_combo_tipo = obj.id_opzione_combo_tipo;
    this.codice_opzione = obj.codice_opzione;
    this.descrizione = obj.descrizione;
    this.ordine_vis = obj.ordine_vis;
 }
function getAnagraficaById(id_anagrafica, callBackFunction, callBackParamOpt) {
    var options = {
        type: "POST",
        url: jsLib_svc_url+"/getAnagraficaById",
        data: "{'id_anagrafica':" + id_anagrafica + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (msg) {
            //alert('Success!' + msg.d);
            var res = msg.d;
            var an = new anag_type(res);
            //alert(an.cognome);
            callBackFunction(callBackParamOpt, an);
        },
        error: function (msg) {
            alert("Errore: " + msg.responseText);
        }
    };
    $.ajax(options);
}
function ActiveWorks() {
    this.counter = 0;
    this.lockEvt = null;
    this.unlockEvt = null;
    this.setUnlockEvt = function (func) {
        this.unlockEvt = func;
    }
    this.setLockEvt = function (func) {
        this.lockEvt = func;

    }
    this.lock = function () {
        
        this.counter = this.counter + 1; 
        this.free = false;
        if (this.counter == 1 && this.lockEvt != null) this.lockEvt();
    };
    this.unlock = function () {
        if (this.counter == 1 && this.unlockEvt != null) this.unlockEvt();
        if (this.counter > 0) this.counter = this.counter-1;
        if (this.counter == 0) this.free = true;
    };
    this.reset = function () {
        this.counter = 0; 
        this.free = true; 
    };
    this.free = true;
}
var aw = new ActiveWorks();


function GDcombo(cb_input_id) {
    this.curr_cb_id = cb_input_id;
    this.onLoadFn = null;
    this.onLoadPar = null;
    this.getParam = function (param_name) {
        var param_str = $("#" + this.curr_cb_id).attr("params");
         params = param_str.split(";");
         for (var p in params) {
             param = params[p];
             keys = param.split("=");
             //alert(param.split("="));
             if (keys[0] == "@" + param_name) {
                 return keys[1];
             } else {
                 return null;
             }
         }
     }
     this.setParam = function (param_name, param_value) {
         var param_str = $("#" + this.curr_cb_id).attr("params");
		 if (param_str == null){
			 $("#" + this.curr_cb_id).attr("params","");
			 param_str = "";
		 }
         if (param_str.charAt(param_str.length - 1) != ";") param_str += ";";
         params = param_str.split(";");
         for (var p in params) {
             param = params[p];
             keys = param.split("=");
             if (keys[0] == "@" + param_name) {
                 param_str = param_str.replace(keys[0] + "=" + keys[1] + ";", "@" + param_name + "=" + param_value + ";");
                 $("#" + this.curr_cb_id).attr("params", param_str);
                 return true;
             } else {
                 param_str += "@" + param_name + "=" + param_value + ";";
                 $("#" + this.curr_cb_id).attr("params", param_str);
                 return true;
             }
         }

     }
     this.onLoad = function (callBackFunction, callBackParamOpt) {
         this.onLoadFn = callBackFunction;
         this.onLoadPar = callBackParamOpt;
     };
     this.svc_url = jsLib_svc_url + '/getJsonRs';
     this.setSvcUrl = function (svcUrl) {
         this.svc_url = svcUrl;
     }
     this.insertOption = function (str_value, str_descrizione, str_attributi, idx) {
         if (str_attributi.replace(/ /g, "").toLowerCase().search("value=") == -1) {
             //se non già presente aggiunge campo value 
             str_attributi = "value=\"" + str_value + "\" " + str_attributi;
         }
         var new_opt = "<option $att>$desc</option>";
         if (idx != null) {
             $("#" + this.curr_cb_id + " option:eq(" + idx + ")").before(new_opt
                .replace("$att", str_attributi)
                .replace("$desc", str_descrizione)
            )
         } else {
             $("#" + this.curr_cb_id).append(new_opt
                .replace("$att", str_attributi)
                .replace("$desc", str_descrizione)
            )
         }
     }
     this.appendOption = function (str_value, str_descrizione, str_attributi) {
         this.insertOption(str_value, str_descrizione, str_attributi, null);
     }
     this.deleteOption = function (idx) {
         $("#" + this.curr_cb_id + " option:eq(" + idx + ")").remove();
     }
     this.replaceOption = function (str_value, str_descrizione, str_attributi, idx) {
         var new_opt = "<option $att>$desc</option>";
         if (idx != null) {
             $("#" + this.curr_cb_id + " option:eq(" + idx + ")").replaceWith(new_opt
                .replace("$att", str_attributi)
                .replace("$desc", str_descrizione)
            )
         }
     }
     this.idxByVal = function (str_value) {
         // da completare
     }
     this.idxByAttr = function (attr_name, attr_val) {
         // da completare
     }
     this.fillByJson = function (jSonStr) {
         var cbID = this.curr_cb_id;
         var obj = $.parseJSON(jSonStr);
         var selected_index = 0;
         var default_option_exists = false;
         var curr_sel_val = null;

         //Se esiste memorizza il valore attuale o predefienito della combo
         if ($("#" + cbID).val() != null) {
             curr_sel_val = $("#" + cbID).val();
         }

         if ($("#" + cbID).attr("default_val") != null) {
             default_selected_opt_str = $("#" + cbID).attr("default_val");
         } else {
             default_selected_opt_str = "";
         }
         $("#" + cbID).html("");
         this.appendOption("", "", "");
         for (i = 0; i < obj.length; i++) {
             var field_idx = 0;
             var str_value = "";
             var str_attributi = "";
             var str_selected = "";
             var str_descrizione = "";
             for (var field_name in obj[i]) {
                 str_attributi += field_name + "=\"" + eval("obj[i]." + field_name) + "\" ";
                 if (field_idx == 0) {
                     //Usa la prima colonna come valore della combo
                     str_value = eval("obj[i]." + field_name);
                 }
                 if (field_idx == 1) {
                     // Usa la seconda colonna come testo per la combo
                     var lsRegExp = /\+/g;
                     str_descrizione = decodeURIComponent(String(eval("obj[i]." + field_name)).replace(lsRegExp, " "));
                    
                 }
                 field_idx++;
             }
             // Negli attributi è specificato un campo di default diverso dal "value" della combo
             if ($("#" + cbID).attr("val_field") != null) {
                 str_value = eval("obj[i]." + $("#" + cbID).attr("val_field"));
             }
             // Se trova nella combo il valore di default imposta a TRUE
             if ("" + str_value == "" + default_selected_opt_str) default_option_exists = true;
             this.appendOption(str_value, str_descrizione, str_attributi);
         }

         // Se non esiste aggiunge opzione default
         if ("" + default_selected_opt_str != "" && !default_option_exists) {
             this.insertOption(default_selected_opt_str, default_selected_opt_str, "", 0);
         }
         //Reimposta il valore precedente o di default
         //if (curr_sel_val != null) {
         //    $("#" + cbID).val(curr_sel_val);
         //} else {
             $("#" + cbID).val(default_selected_opt_str);
         //}

     }
     this.load = function () {
         $("#" + this.curr_cb_id).blur();
         var disabilita_temporanemente = (!$("#" + this.curr_cb_id).is(':disabled'));
         if (disabilita_temporanemente) {
             $("#" + this.curr_cb_id).attr('disabled', 'disabled');
         }
         aw.lock();
         var cb = this;
         var cpar = '{"rnd":"' + Math.random() + '","svc_type":"opzioni_combo","codice_combo_tipo":"' + $("#" + cb.curr_cb_id).attr("codice_combo_tipo") + '","params":"@sel_id=' + $("#" + cb.curr_cb_id).attr("default_val") + ';' + $("#" + cb.curr_cb_id).attr("params") + '"}';
         var options = {
             type: "POST",
             url: cb.svc_url,
             data: "{'parametri':'" + cpar + "'}",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             async: true,
             success: function (msg) {
                 var res = msg.d;
                 if (res.search("-Err") == -1) {
                     cb.fillByJson(res);
                     if (cb.onLoadFn != null) {
                         cb.onLoadFn(cb.onLoadPar, res);
                     }
                     if (disabilita_temporanemente) $("#" + cb.curr_cb_id).removeAttr('disabled');
                     aw.unlock();
                 } else alert(res);
             },
             error: function (msg) {
                 if (disabilita_temporanemente) $("#" + cb.curr_cb_id).removeAttr('disabled');
                 alert("Errore: " + msg.responseText);
             }
         };
         $.ajax(options);

     }
     this.selectedIdx = function (){
         return $("#" + this.curr_cb_id + " option:selected").index($("#" + this.curr_cb_id + " option:selected"));
     }
     this.selectedText = function(){
        return $("#"+this.curr_cb_id+" option:selected").text();
     }
     this.selectedValue = function(){
        return $("#"+this.curr_cb_id+" option:selected").val();
     }
     this.selectedAttr = function (attribute){
         return $("#" + this.curr_cb_id + " option:selected").attr(attribute);
     }
     this.selectByAttr = function (attr_name,attr_val){
        $("#"+this.curr_cb_id+" option["+attr_name+"=\""+attr_val+"\"]").attr("selected", "selected");
     };
     this.selectByText = function (attr_name, attr_val){
        $("#" + this.curr_cb_id + " option[" + attr_name + "=\"" + attr_val + "\"]").attr("selected", "selected");
     };
 }
 var combo = {
     // Cottiene il contenuto dell'attributo richiesto sull'opzione selezionata
     GDselectedAttr: function (cb_input_id, attribute_name) {
         var res = "";
         s = "res= document.getElementById(cb_input_id).options[document.getElementById(cb_input_id).selectedIndex]." + attribute_name;
         eval(s);
         return res;
     },
     // Aggiorna il contenuto della combo con l'ID specificato
     GDcaricaComboOpzioni: function (cb_input_id, callBackFunction, callBackParamOpt) {
         parametri = '{"svc_type":"opzioni_combo","codice_combo_tipo":"' + $("#" + cb_input_id).attr("codice_combo_tipo") + '","params":"@sel_id=' + $("#" + cb_input_id).attr("default_val") + ';' + $("#" + cb_input_id).attr("params") + '"}';
         //alert(parametri);
         combo.GDfillbySvc(cb_input_id, jsLib_svc_url + '/getJsonRs', parametri, callBackFunction, callBackParamOpt);

     },
     GDgetOpzioneComboTipoByCode: function (codice_di_sistema, callBackFunction, callBackParamOpt) {
         var options = {
             type: "POST",
             url: jsLib_svc_url + "/getOpzioneComboTipoByCode",
             data: "{'codice_di_sistema':'" + codice_di_sistema + "'}",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             async: true,
             success: function (msg) {
                 //alert('Success!' + msg.d);
                 var res = msg.d;
                 if (res.search("-Err") != 0) {
                     var op = new OpzioneComboTipo_type(res);

                     if (GDlib.varType(callBackFunction) == "string") {
                         eval(callBackFunction);
                     } else {
                         callBackFunction(callBackParamOpt, op);
                     }
                 } else {
                     if (GDlib.varType(callBackFunction) == "string") {
                         eval(callBackFunction);
                     } else {
                         callBackFunction(callBackParamOpt, null);
                     }
                 }
             },
             error: function (msg) {
                 alert("Errore: " + msg.responseText);
             }
         };
         $.ajax(options);
     },
     GDinsertOption: function (cb_input_id, pos_idx__opt_int, jSonStr) {
         //Cambiare in Jquery Append option
         //Prevedere possibilità di caricare più di due campi dal servizio.
         var selectObj = document.getElementById(cb_input_id);
         if (pos_idx__opt_int == null) pos_idx__opt_int = selectObj.selectedIndex;
         var obj = $.parseJSON(jSonStr);
         for (i = 0; i < obj.length; i++) {
             var field_idx = 0;
             var descrizione = "";
             var valore = "";
             for (var field_name in obj[i]) {
                 if (field_idx == 0) valore = eval("obj[i]." + field_name); else
                     if (field_idx == 1) descrizione = eval("obj[i]." + field_name); else
                         if (field_idx > 1) break;

                 //if (field_idx == 0 && eval("obj[i]." + field_name) == default_selected_opt_str) {
                 //    selected_index = i;
                 //}
                 field_idx++;
             }

             if (pos_idx__opt_int >= 0) {
                 var elOptNew = document.createElement('option');
                 elOptNew.text = descrizione;
                 elOptNew.value = valore;
                 for (var field_name in obj[i]) {
                     var s = "elOptNew." + field_name + " = obj[i]." + field_name;
                     eval(s);
                 }

                 var elOptOld = selectObj.options[pos_idx__opt_int];
                 try {
                     selectObj.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
                 }
                 catch (ex) {
                     selectObj.add(elOptNew, pos_idx__opt_int); // IE only
                 }
             }
         }
     },
     GDfillByJson: function (cb_input_id, jSonStr) {
         //Cambiare in Jquery Append option
         //Prevedere possibilità di caricare più di due campi dal servizio.
         selectObj = document.getElementById(cb_input_id);
         var obj = $.parseJSON(jSonStr);

         if ($("#" + cb_input_id).val() != null) {
             default_selected_opt_str = $("#" + cb_input_id).val();
         } else
             if ($("#" + cb_input_id).attr("default_val") != null) {
                 default_selected_opt_str = $("#" + cb_input_id).attr("default_val");
             } else {
                 default_selected_opt_str = "";
             }

         nome_primo_campo = "value";
         nome_secondo_campo = "descrizione";
         selectObj.options.length = obj.length;
         var selected_index = 0;
         var default_option_exists = false;
         for (i = 0; i < obj.length; i++) {

             var field_idx = 0;
             var descrizione = "";
             var valore = "";

             if ($("#" + cb_input_id).attr("val_field") != null) {
                 // Negli attributi è specificato un campo di default per il "value" della combo
                 valore = eval("obj[i]." + $("#" + cb_input_id).attr("val_field"));
             }

             // Se trova nella combo il valore di default imposta a TRUE
             if ("" + valore == "" + default_selected_opt_str) default_option_exists = true;

             //Scorre le prime due colonne e conserva i due nomi di campo per recperarli successivamente
             for (var field_name in obj[i]) {
                 if (field_idx == 0) { nome_primo_campo = field_name; valore = eval("obj[i]." + field_name); } else
                     if (field_idx == 1) { nome_secondo_campo = field_name; descrizione = eval("obj[i]." + field_name); } else
                         if (field_idx > 1) break;

                 //  if (field_idx == 0 && eval("obj[i]." + field_name) == default_selected_opt_str) {
                 //     selected_index = i;
                 //  }
                 field_idx++;
             }



             selectObj.options[i] = new Option(descrizione, valore);
             selectObj.selectedIndex = selected_index;

             for (var field_name in obj[i]) {
                 var s = "selectObj.options[i]." + field_name + " = obj[i]." + field_name;
                 eval(s);
             }
             //selectObj.options[i].descrizione = "ciao";
         }

         // Aggiunge opzione vuota
         combo.GDinsertOption(cb_input_id, 0, '[{"' + nome_primo_campo + '":"","' + nome_secondo_campo + '":""}]');

         // Imposta ed eventualmente aggiunge opzione default
         if (default_selected_opt_str != "" && !default_option_exists) {
             combo.GDinsertOption(cb_input_id, 1, '[{"' + nome_primo_campo + '":"' + default_selected_opt_str + '","' + nome_secondo_campo + '":"' + default_selected_opt_str + '"}]');
         }
         $("#" + cb_input_id).val(default_selected_opt_str);


     },
     GDfillbySvc: function (cb_input_id, svc_url, parametri, callBackFunction, callBackParamOpt) {
         var options = {
             type: "POST",
             url: svc_url,
             data: "{'parametri':'" + parametri + "'}",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             async: true,
             success: function (msg) {
                 //alert('Success!' + msg.d);
                 var res = msg.d;
                 //var o = new opzione_combo_type(res);
                 //alert(o);
                 if (res.search("-Err") == -1) {
                     combo.GDfillByJson(cb_input_id, res);
                     if (callBackFunction != null) {
                         callBackFunction(callBackParamOpt, res);
                     }
                 } else alert(res);
             },
             error: function (msg) {
                 //document.write(msg.responseText);
                 alert("Errore: " + msg.responseText);
             }
         };
         $.ajax(options);
     },
     getParam: function (cb_input_id, param_name) {
         var param_str = $("#" + cb_input_id).attr("params");
         params = param_str.split(";");
         for (var p in params) {
             param = params[p];
             keys = param.split("=");
             //alert(param.split("="));
             if (keys[0] == "@" + param_name) {
                 return keys[1];
             } else {
                 return null;
             }
         }

     },
     setParam: function (cb_input_id, param_name, param_value) {

         var param_str = $("#" + cb_input_id).attr("params");
         if (param_str.charAt(param_str.length - 1) != ";") param_str += ";";
         params = param_str.split(";");
         for (var p in params) {
             param = params[p];
             keys = param.split("=");
             //alert(param.split("="));
             if (keys[0] == "@" + param_name) {

                 param_str = param_str.replace(keys[0] + "=" + keys[1] + ";", "@" + param_name + "=" + param_value + ";");
                 //alert(keys[0] + "=" + keys[1] + ";");
                 //alert("@" + param_name + "=" + param_value + ";");
                 $("#" + cb_input_id).attr("params", param_str);
                 return true;
             } else {
                 param_str += "@" + param_name + "=" + param_value + ";";
                 $("#" + cb_input_id).attr("params", param_str);
                 return true;
             }
         }

     }
 }
 
function classAnagrafica() {

    this.setLabelRS = function(lbl_id, an_obj) {
        document.getElementById(lbl_id).innerHTML = an_obj.cognome + " " + an_obj.nome;
    }

    this.selAnagrafica = function (stile_anagrafica__opt_str,
									stili_anagrafica_abilitati__opt_strArr,
									cod_tipo_attivita_def_opt_str,
									cod_tipo_attivita_ab_opt_str,
									auto_search_bool,
									input_id_val__opt_str,
									label_innerHTML__opt_str,
									callBackFunction,
									callBackParamOpt) {
        //alert("/progettogestionale/Anagrafica/frame_selezione_anagrafica_V3.asp?tipo_anagrafica=" + stile_anagrafica__opt_str +"  "+stile_anagrafica__opt_str + " " + stili_anagrafica_abilitati__opt_strArr + " " + input_id_val__opt_str + " " + label_innerHTML__opt_str);
        // stile : privati, aziende, ditteaffiliate, vettori, vettorigt, fornitori, assicurazioni, gruppi, societa_gruppo, 
        if (stile_anagrafica__opt_str == null || stile_anagrafica__opt_str + "" == "undefined") stile_anagrafica__opt_str = "aziende";
        var tWindowProp = "dialogWidth:870px;dialogHeight:510px;center=yes;";
        var url = "/progettogestionale/Anagrafica/scelta_anagrafica.asp?";
        url += "stile=" + stile_anagrafica__opt_str;
        if (auto_search_bool != null) url += "&auto_search=" + auto_search_bool;
        if (stili_anagrafica_abilitati__opt_strArr != null) url += "&stili_anagrafica_abilitati=" + stili_anagrafica_abilitati__opt_strArr;
        if (cod_tipo_attivita_def_opt_str != null) url += "&cod_tipo_attivita=" + cod_tipo_attivita_def_opt_str;
        if (cod_tipo_attivita_ab_opt_str != null) url += "&cod_tipo_attivita_abilitati=" + cod_tipo_attivita_ab_opt_str;


        var printWindow = window.showModalDialog(url, "", tWindowProp);
        var tReturnValue = printWindow;
        //tReturnValue = 4045;
        if (tReturnValue != null) {

            if (input_id_val__opt_str != null && input_id_val__opt_str != "" && document.getElementById(input_id_val__opt_str)) {
                document.getElementById(input_id_val__opt_str).value = tReturnValue;
            }
            if (callBackFunction != null) {
                eval(callBackFunction)(tReturnValue, callBackParamOpt);
            } else
                if (label_innerHTML__opt_str != null && label_innerHTML__opt_str != "" && document.getElementById(label_innerHTML__opt_str)) {
                    getAnagraficaById(tReturnValue, this.setLabelRS, label_innerHTML__opt_str);
                }

            return tReturnValue;
        }
        else return -1;
    }

    this.editAnagrafica = function (stile_anagrafica__opt_str,
                                    input_id_val__opt_str,
                                    label_innerHTML__opt_str,
									callBackFunction,
									callBackParamOpt) {
		//if (stile == null || stile+"" == "undefined") stile = "aziende";
		//var tWindowProp		=	"dialogWidth:930px;dialogHeight:710px;center=yes;"; 
		//var printWindow		=	window.showModalDialog("/progettogestionale/Anagrafica/DettaglioAnagrafica.asp?stile="+stile+"&id_anagrafica="+id_anagrafica+"&intestazione=0","",tWindowProp); 
		//var tReturnValue 		= 	printWindow; 
		//return tReturnValue;
												
        var numInput = (GDlib.varType(input_id_val__opt_str) == "number" || "" + input_id_val__opt_str == "" + parseInt(input_id_val__opt_str));

        if (numInput) { id_anagrafica = input_id_val__opt_str; } else
            if (input_id_val__opt_str != null) id_anagrafica = document.getElementById(input_id_val__opt_str).value;

        //alert("/progettogestionale/Anagrafica/frame_modifica_anagrafica_V3.asp?stile=" + input_id_val__str);
        if (stile_anagrafica__opt_str == null || stile_anagrafica__opt_str + "" == "undefined") stile_anagrafica__opt_str = "aziende";
        var tWindowProp = "dialogWidth:930px;dialogHeight:710px;center=yes;";
        var url = "/progettogestionale/Anagrafica/DettaglioAnagrafica.asp?stile=" + stile_anagrafica__opt_str + "&id_anagrafica=" + id_anagrafica + "&intestazione=0";

        //modalPopup("Selezione anagrafica...", url, null, null, callBackSelAnagrafica, null);

        var printWindow = window.showModalDialog(url, "", tWindowProp);
        var tReturnValue = printWindow;
        //tReturnValue = 4045;
        if (tReturnValue != null) {

            if (!numInput && input_id_val__opt_str != null && input_id_val__opt_str != "" && document.getElementById(input_id_val__opt_str)) {
                document.getElementById(input_id_val__opt_str).value = tReturnValue;
            }
            if (callBackFunction != null) {
                eval(callBackFunction)(tReturnValue, callBackParamOpt);
            } else
                if (label_innerHTML__opt_str != null && label_innerHTML__opt_str != "" && document.getElementById(label_innerHTML__opt_str)) {
                    getAnagraficaById(tReturnValue, this.setLabelRS, label_innerHTML__opt_str);
                }
            return tReturnValue;
        }
        else return -1;
    }
    
}

var GDfileUpload = {
    GDsetUploadIco: function() {
        $(".upload_form").each(function() {
            // per ogni form
            hdivId = $(this).attr("progress_lbl");
			progrLbl = $(this).attr("progress_lbl");
            //$("#" + progrLbl).append("<div style='position:absolute; right:5px; top:-15px; border:'><img name='history_image' progress_lbl='" + hdivId + "' width='30px' heigth='21px' src='http://www.etransfer.it/progettogestionale/images/folder-add.png' /></div>");
        });

        $("img[name='history_image']").click(function() {
            //alert($(this).attr("name"));
            img_x = $(this).offset().left - 252;
            img_y = $(this).offset().top + 1;
            hl = $(this).attr("upload_form_name");
			ImgOnComplete = $(this).attr("oncomplete");
			ImgPath = $(this).attr("path");
			ImgArchive = $(this).attr("archive");
			//alert(hl+" "+img_y);

            $("form[name='" + hl + "']").each(function() {
				//alert(hl+" "+img_y);
				//$(this).attr("on");
				if (ImgOnComplete != "" && ImgOnComplete != null){
					$(this).children("input[name='oncomplete']").attr("value",ImgOnComplete);
				}
				if (ImgPath != "" && ImgPath != null){
					$(this).children("input[name='path']").attr("value",ImgPath);
				}
				if (ImgArchive != "" && ImgArchive != null){
					$(this).children("input[name='archive']").attr("value",ImgArchive);
				}
                $(this).css({ 'top': img_y, 'left': img_x });
                if ($(this).css('display') == "block") {
                    $(this).css({ 'display': 'none' });
                } else {
                    $(this).css({ 'display': 'block' });
                }
            });

        });
    },
    GDloadAttachByFolder: function(destDivId, relFolderPath, archive, callBackFunction, callBackParamOpt) {
		if (destDivId == null || destDivId == "" || destDivId == "null") return;
        svc_url = jsLib_svc_url + "/getJsonRs";
        parametri = '{"svc_type":"get_allegati","path":"' + relFolderPath + '","archive":"' + archive + '"}';
        var options = {
            type: "POST",
            url: svc_url,
            data: "{'parametri':'" + parametri + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            success: function(msg) {
                var jSonStr = msg.d;
                if (destDivId != null) {
                    $("#" + destDivId).empty();
                    var obj = $.parseJSON(jSonStr);
                    for (i = 0; i < obj.length; i++) {
                        var newDiv = "<div>" +
                                            "<span>" +
                                            "<a href=\"" + upload_svc_url + "?archive=" + archive + "&f=" + obj[i].file_name + "&path=" + relFolderPath + "\" target=\"_blank\"> " +
                                            "<img src=\"http://www.etransfer.it/progettogestionale/images/ext_ico/" + obj[i].file_ext.substr(1) + ".gif\" alt=\"Clicca aprire il file\" width=\"21\" height=\"17\" border=\"0\">" +
                                            "</a>" +
                                            "</span>&nbsp;" +
                                            "<span>" +
                                            "<img src=\"http://www.etransfer.it/progettogestionale/images/cestino.gif\" width=\"14\" height=\"14\" style=\"cursor:pointer\" onClick=\"delAttachment('" + relFolderPath + "','" + archive + "','" + obj[i].file_name + "','" + destDivId + "',null,null);\">" +
                                            "</span>&nbsp;" +
                                            "<span>" + obj[i].file_date + "</span>&nbsp;" +
                                            "<span>" + obj[i].orig_file_name + "</span>" +
                                         "</div>";
                        $("#" + destDivId).append(newDiv);
                    }
                }
                if (callBackFunction != null) {
                    callBackFunction(callBackParamOpt, jSonStr);
                }
            },
            error: function(msg) {
                //document.write(msg.responseText);
                alert("Errore: " + msg.responseText);
            }
        };
        $.ajax(options);
    }
}

function uploadComplete(risultato, callBackToken, relFolderPath, file_name) {
    if (risultato != "+Ok") {
        alert(risultato);
    } else {
        $("input[name='path']").each(function () {
            if ($(this).val() == relFolderPath) {
                var r = $(this).parent(".upload_form").children("input[name='path']").attr("value");
                var a = $(this).parent(".upload_form").children("input[name='archive']").attr("value");
                var d = $(this).parent(".upload_form").attr("history_div");
                if (d != "" && d != "null" && d != null) {
                    GDfileUpload.GDloadAttachByFolder(d, escape(r), escape(a), null, null);
                }
            }
        });

        $("#progressDiv" + callBackToken).remove();

    }
}
function delAttachment(relFolderPath, archive, file_name, destDivId, callBackFunction, callBackParamOpt) {
    if (confirm("Eliminare il file " + file_name + "? l'operazione è irreversibile...")) {
        svc_url = jsLib_svc_url + "/getJsonRs";
        parametri = '{"svc_type":"del_attachment","path":"' + relFolderPath + '","archive":"' + archive + '","file_name":"' + file_name + '"}';
        var options = {
            type: "POST",
            url: svc_url,
            data: "{'parametri':'" + parametri + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (msg) {
                var jSonStr = msg.d;
                if (callBackFunction != null) {
                    callBackFunction(callBackParamOpt, jSonStr);
                }

				if (destDivId != "" && destDivId != "null" && destDivId != null){
                	GDfileUpload.GDloadAttachByFolder(destDivId, relFolderPath, archive, null, null);
				}
            },
            error: function (msg) {
                //document.write(msg.responseText);
                alert("Errore: " + msg.responseText);
            }
        };
        $.ajax(options);
    }
 }

 $(document).ready(function () {
     // A documento caricato imposta gli eventi dei pulsanti cerca e modifica in agrafica
     // /progettogestionale/gASPnet/images/calendar_small.png
     $.chainclude({
         '/progettogestionale/gASPnet/jsLib/themes/cupertino/jquery-ui-1.8.2.custom.css': function () { },
         '/progettogestionale/gASPnet/jsLib/js/jquery-ui-1.8.2.min.js': function () {
             // Attivazione DatePicket
             $(function ($) {
                 $.datepicker.regional['it'] = {
                     clearText: 'Svuota', clearStatus: '',
                     clearStatus: 'Cancella la data corrente',
                     closeText: 'Chiudi', closeStatus: '',
                     closeStatus: 'Chiudi senza cambiamenti',
                     prevText: '&lt;Prec', prevStatus: '',
                     prevStatus: 'Mostra il mese precedente',
                     nextText: 'Succ&gt;', nextStatus: '',
                     nextStatus: 'Mostra il mese successivo',
                     currentText: 'Oggi', currentStatus: '',
                     currentStatus: 'Mostra il mese corrente',
                     monthNames: ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'],
                     monthNamesShort: ['Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'],
                     monthStatus: 'Mostra un altro mese',
                     yearStatus: 'Mostra un altro anno',
                     weekHeader: 'Sm', weekStatus: '',
                     weekStatus: 'Settimana dell\'anno',
                     dayNames: ['Domenica', 'Luned&#236', 'Marted&#236', 'Mercoled&#236', 'Gioved&#236', 'Vener­d&#236', 'Sabato'],
                     dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab'],
                     dayNamesMin: ['Do', 'Lu', 'Ma', 'Me', 'Gio', 'Ve', 'Sa'],
                     dayStatus: 'Imposta DD come primo giorno della settimana',
                     dateStatus: 'Seleziona DD, M d',
                     dateFormat: 'dd/mm/yy', firstDay: 1,
                     initStatus: 'Seleziona una data',
                     isRTL: false
                 };
                 $.datepicker.setDefaults($.datepicker.regional['it']);
                 $.datepicker.setDefaults({
                     buttonText: 'Calendar'
                 });
             });
             $('.ui-datepicker-trigger').css({ 'cursor': 'pointer', "vertical-align": 'bottom' });
             $(".datepicker").datepicker();

         },
         '/progettogestionale/gASPnet/jsLib/js/jquery.json-2.2.js': function () { },
         '/progettogestionale/gASPnet/jsLib/js/jquery.validate.js': function () {

             $("form.GDvalidate").validate({
                 highlight: function (element, errorClass, validClass) {
                     $(element).addClass("vError");
                 },

                 unhighlight: function (element, errorClass, validClass) {
                     $(element).removeClass("vError");
                 },

                 errorPlacement: function (error, element) {
                 }

             });


             groupValid = function (formName, groupName) {
                 var valid = true;
                 var curValid;
                 $("input[group=" + groupName + "]").each(function () {
                     curValid = $("#" + formName).validate().element("#" + $(this).attr("id"));
                     curReq = $(this).is('.required');
                     cur = $(this).val();
                     //alert("cur:"+cur+" curReq:"+curReq+" curValid:"+curValid);
                     if (!curReq && cur != "" && !curValid) { valid = false; };
                     if (curReq && !curValid) { valid = false };
                     //alert($(this).attr("id")+" --> "+valid);
                 });
                 //alert(valid);
                 return valid;
             }
         }
     });

     var objAnagrafica = new classAnagrafica();

     $('.btn_sel').click(function () {
         if ($(this).hasClass('readonly')) { alert("Impossibile modificare, il campo è di sola lettura"); return false };
         objAnagrafica.selAnagrafica($(this).attr("stile_def"),
                                    $(this).attr("stili_ab"),
                                    $(this).attr("cod_tipo_attivita_def"),
                                    $(this).attr("cod_tipo_attivita_ab"),
                                    $(this).attr("auto_search"),
                                    $(this).attr("input_id"),
                                    $(this).attr("lbl_id"),
                                    $(this).attr("callBackFunction"),
                                    $(this).attr("callBackParamOpt"));
         if ($(this).attr("afterclick") + "" != "undefined" && $(this).attr("afterclick") + "" != "") {
             eval($(this).attr("afterclick"));
         }
     });
     $('.btn_edit').click(function () {
         if ($(this).hasClass('readonly')) { alert("Impossibile modificare, il campo è di sola lettura"); return false };
         if ($("#" + $(this).attr("input_id")).val() != "") {
             objAnagrafica.editAnagrafica($(this).attr("stile_def"),
                                         $(this).attr("input_id"),
                                         $(this).attr("lbl_id"),
                                         $(this).attr("callBackFunction"),
                                         $(this).attr("callBackParamOpt"));
             if ($(this).attr("afterclick") + "" != "undefined" && $(this).attr("afterclick") + "" != "") {
                 eval($(this).attr("afterclick"));
             }
         }
     });
     $('.btn_clear').click(function () {
         if ($(this).hasClass('readonly')) { alert("Impossibile modificare, il campo è di sola lettura"); return false };
         if ($(this).attr("lbl_id") + "" != "" && $(this).attr("lbl_id") + "undefined" != "") {
             $("#" + $(this).attr("lbl_id")).html("");
         }
         if ($(this).attr("input_id") + "" != "" && $(this).attr("input_id") + "" != "undefined") {
             //alert($(this).attr("lbl_id")+ "");
             $("#" + $(this).attr("input_id")).val("");
         }

         if ($(this).attr("afterclick") + "" != "undefined" && $(this).attr("afterclick") + "" != "") {
             eval($(this).attr("afterclick"));
         }
     });
     $('.btn_sel').css('cursor', 'pointer');
     $('.btn_edit').css('cursor', 'pointer');
     $('.btn_clear').css('cursor', 'pointer');
     $('.cb_opzione_combo').each(function () {
         if ($(this).attr("autoload") != "false") {
             var cb = new GDcombo($(this).attr("id"));
             cb.load();
             //combo.GDcaricaComboOpzioni($(this).attr("id"), null, null);
         }
         if ($(this).attr("editable") == "true") {
             $('<img class="edit_combo_ico" src=\"/progettogestionale/gASPnet/images/edit_combo.gif\" combo_id="' + $(this).attr("id") + '" />').insertAfter($(this));
         }
     });
     $(".edit_combo_ico").click(function () {
         var call_back_combo_opzioni_caricato = function (combo_id, oc) {
             if ($('#' + combo_id).attr("edit_table_stile") != "" && $('#' + combo_id).attr("edit_table_stile") != null) {
                 url = "/progettogestionale/anagrafica/table_editor.asp?intestazione=0&modal=true&stile=" + $('#' + combo_id).attr("edit_table_stile");
             } else {
                 url = "/progettogestionale/anagrafica/table_editor.asp?intestazione=0&modal=true&stile=opzione_combo&id_opzione_combo_tipo=" + oc.id_opzione_combo_tipo;
             }
             var callBack = function () {
                 var cb = new GDcombo(combo_id);
                 cb.load();
             }
             //cb = 'combo.GDcaricaComboOpzioni("' + combo_id + '", null, null)';
             popup.GDajaxModalPopup("Personalizzazione opzioni...", url, null, null, callBack, null);
         }
         combo_id = $(this).attr("combo_id");
         combo.GDgetOpzioneComboTipoByCode($("#" + $(this).attr("combo_id")).attr("codice_combo_tipo"), call_back_combo_opzioni_caricato, $(this).attr("combo_id"));
     });
     $("input[name='btn_carica']").click(function () {
         var token = Math.floor(Math.random() * 10000);
         var prog_lbl_id = $(this).parent(".upload_form").attr("progress_lbl");
         $('body').append('<iframe id="postFrame' + token + '" name="postFrame' + token + '" height="0" width="0" src=""></iframe>');
         if (prog_lbl_id != "" && prog_lbl_id != null && prog_lbl_id != "null") {
             $('#' + prog_lbl_id).append('<div id="progressDiv' + token + '" name="progressDiv' + token + '">Caricamento in corso...</div>');
         }
         $(this).parent(".upload_form").children("input[name='callBackToken']").val(token);
         $(this).parent(".upload_form").attr("target", "postFrame" + token);
         //$(this).parent(".upload_form").attr("target", "_blank");
         $(this).parent(".upload_form").attr("action", upload_svc_url);
         $(this).parent(".upload_form").submit();
         //$('#form_upload').append('<div id="progressDiv' + token + '" name="progressDiv' + token + '">Caricamento in corso...</div>');
     });
     $('.upload_form').each(function () {
         // Per ogni form trovato
         var r = $(this).children("input[name='path']").attr("value");
         var a = $(this).children("input[name='archive']").attr("value");
         var d = $(this).attr("history_div");
         var p = $(this).attr("progress_lbl");

         $(this).css("border-width", "1px")
				   .css("border-color", "#F2F2F2")
				   .css("border-style", "solid");

         // Stili attachment box
         if (p != "" && p != "null" && p != null) {
             $("#" + p).css("position", "relative");
         }
         if (d != "" && d != "null" && d != null) {
             $("#" + d).css("position", "relative")
						  .css("border-width", "1px")
						  .css("border-color", "#F2F2F2")
						  .css("border-style", "solid");
             GDfileUpload.GDloadAttachByFolder(d, escape(r), escape(a), null, null);

             //Carica gli allegati esistenti
             //alert(r + " " + d);
         }
         GDfileUpload.GDsetUploadIco();
     });
     $('.readonly').click(function () {
         //alert("Attenzione, il campo è di sola lettura...");
         $(this).blur();
         return false;
     });
 });

function setBtnSecret(btnID, id_anagrafica) {
    if (!document.getElementById('secure_dialog')) 
        if (location.pathname.substr(0, 9) == "/gASPnet/") {
                $.include({
                    'jsLib/templ_secret.htm': function(data) {
                        $('body').append(data);
                        $.chainclude({
                            'jsLib/js/aes.js': function() { },
                            'jsLib/js/aes-ctr.js': function() { },
                            'jsLib/js/base64.js': function() { },
                            'jsLib/js/utf8.js': function() { },
                            'jsLib/AESform.js': function() { },
                            'jsLib/AESform.css': function() { }

                        },
				             function() {
				                 $('#secure_dialog').dialog('option', 'id_anagrafica', id_anagrafica);
								// $('#secure_dialog').dialog('option', 'height', 290);
				             }
			            );

                    }
                });
            
         } else {
                $.include({
                '/progettogestionale/gASPnet/jsLib/templ_secret.htm': function(data) {
                        $('body').append(data);
                        $.chainclude({
                            '/progettogestionale/gASPnet/jsLib/js/aes.js': function() { },
                            '/progettogestionale/gASPnet/jsLib/js/aes-ctr.js': function() { },
                            '/progettogestionale/gASPnet/jsLib/js/base64.js': function() { },
                            '/progettogestionale/gASPnet/jsLib/js/utf8.js': function() { },
                            '/progettogestionale/gASPnet/jsLib/AESform.js': function() { },
                            '/progettogestionale/gASPnet/jsLib/AESform.css': function() { }

                        },
				             function() {
				                 $('#secure_dialog').dialog('option', 'id_anagrafica', id_anagrafica);
								// $('#secure_dialog').dialog('option', 'height', 290);
				             }
			            );

                    }
                });
         }
    
    
    
    $(btnID).click(
	        function() {
				
	            $('#secure_dialog').dialog('open');
	        }
        )

 }
function showLog(tbl, id, azione) {

    if (azione == null) {
        var rnd = Math.random();
        window.open("/progettogestionale/Gestionale_LogManager/LogManager.aspx?rnd=" + rnd + "&tabella=" + tbl + "&ID=" + id, "mywindow", "status=0,toolbar=0,width=825,height=600,scrollbars=yes");
    } else {
        var rnd = Math.random();
        window.open("/progettogestionale/Gestionale_LogManager/LogManager.aspx?rnd=" + rnd + "&tabella=" + tbl + "&ID=" + id + "&azione=" + azione, "mywindow", "status=0,toolbar=0,width=825,height=600,scrollbars=yes");
    }
 }
function dispW() {
    var myWidth = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
    }
    return myWidth;
 }
function dispH() {
    var myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myHeight = document.body.clientHeight;
    }
    return myHeight;
 }

var modalReturnValue = null;
var popup = {
    dialogDivTemplate: function () {
        html = '<div id="dialog_div" class="dialog_div">';
        html += ' <div id="dialog_frame" class="dialog_frame">';
        html += ' <img id="dialog_img" src="" />';
        html += ' <span id="dialog_txt"></span>';
        html += ' <span id="yes_btn"></span>';
        html += ' <span id="no_btn"></span>';
        html += ' </div>';
        html += '</div>';
        return html;
    },
    queryMsg: function (s, yesEvt, noEvt, img) {
        if ($("#dialog_div").attr("id") != "dialog_div") {
            $('body').append(popup.dialogDivTemplate());
        }

        if (img == null) img = "qmark.png";
        $("#dialog_txt").html(s);
        $("#dialog_img").attr("src", "/progettogestionale/images/" + img);
        $("#dialog_div").css("display", "block");
        $("#dialog_div").unbind('mousedown');
        $("#yes_btn").html("Si").css("display", "block").unbind('mousedown').mousedown(function () {
            $("#yes_btn").css("display", "none");
            $("#dialog_div").css("display", "none");
            if (yesEvt != null) yesEvt();
        }); ;
        $("#no_btn").htmlContent("No").css("display", "block").unbind('mousedown').mousedown(function () {
            $("#no_btn").css("display", "none");
            $("#dialog_div").css("display", "none");
            if (noEvt != null) noEvt();
        });

    },
    alertMsg: function (s, onClose, img) {
        if ($("#dialog_div").attr("id") != "dialog_div") {
            $('body').append(popup.dialogDivTemplate());
        }
        if (img == null) img = "info.png";
        $("#yes_btn").css("display", "none");
        $("#no_btn").css("display", "none");
        $("#dialog_txt").html(s);
        $("#dialog_img").attr("src", "/progettogestionale/images/" + img);
        $("#dialog_div").css("display", "block");
        $("#dialog_div").unbind('mousedown');
        $("#dialog_div").mousedown(function () {
            $("#dialog_div").css("display", "none");
            if (onClose != null) onClose();
        });
    },
    waitingMsg: function (s, img) {
        if ($("#dialog_div").attr("id") != "dialog_div") {
            $('body').append(popup.dialogDivTemplate());
        }

        if (img == null) img = "info.png";
        $("#yes_btn").css("display", "none");
        $("#no_btn").css("display", "none");
        $("#dialog_div").unbind('mousedown');
        $("#dialog_txt").html(s);
        $("#dialog_img").attr("src", "/progettogestionale/images/" + img);
        $("#dialog_div").css("display", "block");
    },
    closeMsg: function () {
        $("#dialog_div").css("display", "none");
    },
    GDbasicModalPopup: function (url, tWindowProp) {
        var printWindow = window.showModalDialog(url, "", tWindowProp);
        var tReturnValue = printWindow;
        if (tReturnValue != null) {
            modalReturnValue = "" + tReturnValue;
        }
        return modalReturnValue;
    },
    GDbasicModalReturn: function (result) {
        //alert(">>"+result);
        try {
            parent.opener.modalReturnValue = result;
        } catch (e) { }

        try {
            window.returnValue = result;
        } catch (e) { }
        //alert(result);
        window.close();

    },
    GDajaxChiudiPopup: function (token) {
        $("#dialog-" + token).dialog("close");
    },
    GDajaxModalPopup: function (title, url, width, height, callBackFunction, callBackParOpt) {
        var token = Math.floor(Math.random() * 10000);

        var myRegExp1 = /\?/;
        var qmPos = url.search(myRegExp1);

        if (qmPos == -1) {
            url += "?closeFunction=popup.GDajaxChiudiPopup(" + token + ");";
        } else
            if (qmPos == url.length - 1) {
                url += "closeFunction=popup.GDajaxChiudiPopup(" + token + ");";
            } else
                if (qmPos < url.length) {
                    if (url.charAt(url.length - 1) == "&") {
                        url += "closeFunction=popup.GDajaxChiudiPopup(" + token + ");";
                    } else {
                        url += "&closeFunction=popup.GDajaxChiudiPopup(" + token + ");";
                    }
                }

        if (width == null) width = 1600;
        if (height == null) height = 1400;
        maxH = dispH() - 36;
        if (maxH > height) maxH = height;
        maxW = dispW() - 36;
        if (maxW > width) maxW = width;

        divHTML = "<div id=\"dialog-" + token + "\" title=\"" + title + "\">" +
                    "<iframe src=\"" + url + "\" width=\"100%\" height=\"100%\" frameborder=\"0\" ></iframe>" +
                    "</div>";

        $(document.body).append(divHTML);
        $("#dialog-" + token).dialog({
            height: maxH,
            width: maxW,
            modal: true,
            resizable: false,
            close: function (event, ui) {
                if (GDlib.varType(callBackFunction) == "string") {
                    eval(callBackFunction);
                } else
                    if (callBackFunction) {
                        callBackFunction(callBackParOpt);
                    }
            }
        });
        return $("#dialog-" + token);
    }

}

 var GDfattSvc = {
     GDincassaFatture: function (fatt_IDs___str, data__str_opt, cassa_dest_ID__str_opt, causale_ID__str_opt, callBackFunction, callBackParOpt) {
         //    if (data__str_opt == null) data__str_opt = "";
         //    if (cassa_dest_ID__str_opt == null) cassa_dest_ID__str_opt = "";
         //    if (causale_ID__str_opt == null) causale_ID__str_opt = "";

         var options = {
             type: "POST",
             url: jsLib_svc_url + "/GDincassaFatture",
             data: "{'fatt_IDs___str':'" + fatt_IDs___str + "','data__str_opt':'" + data__str_opt + "','cassa_dest_ID__str_opt':'" + cassa_dest_ID__str_opt + "','causale_ID__str_opt':'" + causale_ID__str_opt + "'}",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             async: true,
             success: function (msg) {
                 var res = msg.d;
                 if (res != "+Ok") {
                     alert(res);
                 } else {
                     if (GDlib.varType(callBackFunction) == "string") {
                         eval(callBackFunction);
                     } else {
                         callBackFunction(callBackParOpt);
                     }
                 }

             },
             error: function (msg) {
                 alert("Errore: " + msg.responseText);
             }
         };
         $.ajax(options);
     },
     GDrigeneraFatture: function (fatt_IDs___str, callBackFunction, callBackParOpt) {
         //    if (data__str_opt == null) data__str_opt = "";
         //    if (cassa_dest_ID__str_opt == null) cassa_dest_ID__str_opt = "";
         //    if (causale_ID__str_opt == null) causale_ID__str_opt = "";
         //s = jsLib_svc_url + "/GDrigeneraFatture?" + "{'fatt_IDs___str':'" + fatt_IDs___str + "','data__str_opt':'" + data__str_opt + "','cassa_dest_ID__str_opt':'" + cassa_dest_ID__str_opt + "','causale_ID__str_opt':'" + causale_ID__str_opt + "'}";
         //window.open(s);

         var options = {
             type: "POST",
             url: jsLib_svc_url + "/GDrigeneraFatture",
             data: "{'fatt_IDs___str':'" + fatt_IDs___str + "'}",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             async: true,
             success: function (msg) {
                 var res = msg.d;
                 if (res != "+Ok") {
                     alert(res);
                 } else {
                     if (GDlib.varType(callBackFunction) == "string") {
                         eval(callBackFunction);
                     } else {
                         if (callBackFunction != null) callBackFunction(callBackParOpt);
                     }
                 }

             },
             error: function (msg) {
                 alert("Errore: " + msg.responseText);
             }
         };
         $.ajax(options);
     },
     GDristampaFatture: function (fatt_IDs___str, callBackFunction, callBackParOpt) {
         //    if (data__str_opt == null) data__str_opt = "";
         //    if (cassa_dest_ID__str_opt == null) cassa_dest_ID__str_opt = "";
         //    if (causale_ID__str_opt == null) causale_ID__str_opt = "";

         var options = {
             type: "POST",
             url: jsLib_svc_url + "/GDristampaFatture",
             data: "{'fatt_IDs___str':'" + fatt_IDs___str + "'}",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             async: true,
             success: function (msg) {
                 var res = msg.d;
                 if (res.search("-Err") == -1) {
                     if (GDlib.varType(callBackFunction) == "string") {
                         eval(callBackFunction);
                     } else {
                         if (callBackFunction != null) callBackFunction(callBackParOpt, res);
                     }
                 } else alert(res);
             },
             error: function (msg) {
                 alert("Errore: " + msg.responseText);
             }
         };
         $.ajax(options);
     },
     GDesportaFatture: function (fatt_IDs___str, callBackFunction, callBackParOpt) {
         //    if (data__str_opt == null) data__str_opt = "";
         //    if (cassa_dest_ID__str_opt == null) cassa_dest_ID__str_opt = "";
         //    if (causale_ID__str_opt == null) causale_ID__str_opt = "";

         var options = {
             type: "POST",
             url: jsLib_svc_url + "/GDesportaFatture",
             data: "{'fatt_IDs___str':'" + fatt_IDs___str + "'}",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             async: true,
             success: function (msg) {
                 var res = msg.d;
                 if (res.search("-Err") == -1) {
                     if (GDlib.varType(callBackFunction) == "string") {
                         eval(callBackFunction);
                     } else {
                         if (callBackFunction != null) callBackFunction(callBackParOpt, res);
                     }
                 } else alert(res);
             },
             error: function (msg) {
                 alert("Errore: " + msg.responseText);
             }
         };
         $.ajax(options);
     }

 }

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
 }
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
 }
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
 }
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
 }
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
 }
function getSessionVar(var_name, callBackFunction, callBackParamOpt) {
    var options = {
        type: "POST",
        url: jsLib_svc_url + "/getSessionVar",
        data: "{'var_name':'" + var_name + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (msg) {
            var res = msg.d;
            //alert(an.cognome);
            if (GDlib.varType(callBackFunction) == "string") {
                eval(callBackFunction);
            } else {
                callBackFunction(callBackParamOpt, res);
            }
        },
        error: function (msg) {
            alert("Errore: " + msg.responseText);
        }
    };
    $.ajax(options);
 }
function setSessionVar(var_name, var_value, callBackFunction, callBackParamOpt) {
    var options = {
        type: "POST",
        url: jsLib_svc_url + "/setSessionVar",
        data: "{'var_name':'" + var_name + "','var_value':'" + var_value + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (msg) {
            var res = msg.d;
            //alert(an.cognome);
            if (GDlib.varType(callBackFunction) == "string") {
                eval(callBackFunction);
            } else {
                callBackFunction(callBackParamOpt);
            }
        },
        error: function (msg) {
            alert("Errore: " + msg.responseText);
        }
    };
    $.ajax(options);
 }

var GDate = {
		 partStrToDate: function (s) {
			 s = "" + s;
			 if (s.search(/\./i) > -1) {
				 var a = s.split(".")
				 d = 1;
				 m = 0;
				 y = 1970;
				 h = parseFloat(a[0]);
				 if (a.length > 1) n = parseFloat(a[1]);
				 else n = 0;
				 if (a.length > 2) s = parseFloat(a[2]);
				 else s = 0;
			 } else
				 if (s.search(/\//i) > -1) {
					 var a = s.split("/")
					 d = parseFloat(a[0]);
					 m = parseFloat(a[1]) - 1;
					 y = parseFloat(a[2]);
					 if (y < 1900) y += 2000;
					 h = 0;
					 n = 0;
				 } else return 0
		 },
		 strToDate: function (str) {
			 str = str.replace(/-/g, "/");
			 str = str.replace(/:/g, ".");
			 
			 h = 0;
			 n = 0;
			 s = 0;
			 d = 1;
			 m = 0;
			 y = 1970;
			 
			 var isDateTime = (str.search(" ") >= 0);
			 var hasDate = (str.search(/\//i) > -1);
			 var hasTime = (str.search(/\./i) > -1);
			 var data = null;
			 if(isDateTime){
				var parts = str.split(" ");
				
				var a = parts[0].split("/")
				d = parseFloat(a[0]);
				m = parseFloat(a[1]) - 1;
				y = parseFloat(a[2]);
				if (y < 1900) y += 2000;
				
				var a = parts[1].split(".")
				h = parseFloat(a[0]);
				if (a.length > 1) n = parseFloat(a[1]);
				else n = 0;
				if (a.length > 2) s = parseFloat(a[2]);
				else s = 0;
				
			 } else {
				 if (hasDate){
					var a = str.split("/")
					d = parseFloat(a[0]);
					m = parseFloat(a[1]) - 1;
					y = parseFloat(a[2]);
					if (y < 1900) y += 2000;
				 }
				 if (hasTime){
					var a = str.split(".")
					h = parseFloat(a[0]);
					if (a.length > 1) n = parseFloat(a[1]);
					else n = 0;
					if (a.length > 2) s = parseFloat(a[2]);
					else s = 0;
				 }
			 }
			 var data = new Date(y, m, d, h, n, s, 0);
			 return data;
		 },
		 
         toStrDate: function (td) {
             var d = (td.getDate());
             if (("" + d).length == 1) d = "0" + d;
             var m = (td.getMonth() + 1);
             if (("" + m).length == 1) m = "0" + m;
             var y = (td.getFullYear());

             return d + "/" + m + "/" + y;
         },
         toLongStrTime: function (td) {
             var h = (td.getHours());
             var n = (td.getMinutes());
             var s = (td.getSeconds());
             if (h >= 0 || n >= 0 || s >=0) {
                 if (("" + h).length == 1) h = "0" + h;
                 if (("" + n).length == 1) n = "0" + n;
                 if (("" + s).length == 1) s = "0" + s;
             }
             return h + ":" + n + ":" + s;
         },
         toStrTime: function (td) {
             var h = (td.getHours());
             var n = (td.getMinutes());
             if (h >= 0 || n >= 0) {
                 if (("" + h).length == 1) h = "0" + h;
                 if (("" + n).length == 1) n = "0" + n;
             }
             return h + ":" + n;
         },
         toStrDateTime: function (td) {
             return GDate.toStrDate(td) + " " + GDate.toStrTime(td);
         },

		 partStrToUTC: function (s) {
			 return GDate.strToDate(s).getTime();
			 /*
			 s = "" + s;
			 if (s.search(/\./i) > -1) {
				 var a = s.split(".")
				 d = 1;
				 m = 0;
				 y = 1970;
				 h = parseInt(a[0]);
				 if (a.length > 1) n = parseInt(a[1]);
				 else n = 0;
				 if (a.length > 2) s = parseInt(a[2]);
				 else s = 0;
				 // -3600000 differenza dovuta all'ora legale rimuovere urg
				 var data = Date.UTC(y, m, d, h, n, s, 0) - 3600000;
				 return data;
			 }
			 else if (s.search(/\//i) > -1) 
			 {
				 var a = s.split("/")
				 d = parseInt(a[0]);
				 m = parseInt(a[1]) - 1;
				 y = parseInt(a[2]);
				 if (y < 1900) y += 2000;
				 h = 0;
				 n = 0;
				 // -3600000 differenza dovuta all'ora legale rimuovere urg
				 var data = Date.UTC(y, m, d, h, n, 0, 0) - 3600000;
				 return data;
			 } else return 0*/
		 },
		 strToUTC: function (s) {
			 return GDate.strToDate(s).getTime();
			 /*
             s = s.replace(/-/g, "/");
             s = s.replace(/:/g, ".");
             var a = s.split(" ");
             var utc = 0;
             sdate = a[0];
             utc += GDate.partStrToUTC(sdate);
             if (a.length > 1) {
                 stime = a[1];
                 utc += GDate.partStrToUTC(stime);
             }
             return utc;*/
         },
         UTCtoDate: function (u) {
             return new Date(u);
         },
         UTCsec: function (s) {
             if (s == null) s = 1;
             var durata_milli = s * 1000;
             return Date.UTC(1970, 0, 1, 0, 0, 0, durata_milli)
         },
         UTCmin: function (m) {
             if (m == null) m = 1;
             var durata_sec = m * 60;
             return Date.UTC(1970, 0, 1, 0, 0, durata_sec, 0)
         },
         UTChour: function (h) {
             if (h == null) h = 1;
             var durata_minuti = h * 60;
             return Date.UTC(1970, 0, 1, 0, durata_minuti, 0, 0)
         },
         UTCday: function (d) {
             if (d == null) d = 1;
             var durata_minuti = d * 60 * 24;
             return Date.UTC(1970, 0, 1, 0, durata_minuti, 0, 0)
         }
 }

 var postIT = {
    load_data: function (id_image, id_text_area, compFunc) {

        // Carica icona e titoli immagine
        var parametri = '{  "svc_type":"get_field", "stile":"' + $("#" + id_image).attr("stile") + '", "recId":"' + $("#" + id_image).attr("recId") + '"}';


        var onComplete = function (msg) {
            res = unescape(msg.d);
            if (res.search("-Err") == -1) {
                if (msg.d != "") {
                    // Colore icona marcato se c'è qualche nota
                    $("#" + id_image).attr("src", "/progettogestionale/images/postit.gif");
                }

                // Comunque imposto titolo e evento di modifica
                $("#" + id_image).attr("title", res)
                             .attr("alt", res)
            } else {
                alert(res);
            }
        };

        var options = {
            type: "POST",
            url: jsLib_svc_url + "/getJsonRs",
            data: "{'parametri':'" + parametri + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            success: onComplete,
            error: function (msg) {
                alert("Errore: " + msg.responseText);
            }
        };
        $.ajax(options);

        if (id_text_area != null) {
            // Carica icona e titoli immagine
            var parametri = '{  "svc_type":"get_field", "stile":"' + $("#" + id_image).attr("stile") + '", "recId":"' + $("#" + id_image).attr("recId") + '"}';


            var onComplete = function (msg) {
                res = unescape(msg.d);
                $("#" + id_text_area).val(res);
                compFunc();
            };

            var options = {
                type: "POST",
                url: jsLib_svc_url + "/getJsonRs",
                data: "{'parametri':'" + parametri + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                success: onComplete,
                error: function (msg) {
                    alert("Errore: " + msg.responseText);
                }
            };
            $.ajax(options);
        }


    },
    init: function () {
        $('.postIT').each(function () {
            postIT.load_data($(this).attr("id"));
        });

        $('.postIT').click(function () {
            //$(".postITarea").remove();
            var id_obj = $(this).attr("id");
            var divID = "postITarea" + id_obj;

            var onComplete = function () {
                var testo = "<textarea id='" + divID + "' class='postITarea'>" + $("#" + id_obj).attr("title") + "</textarea>";
                $(testo).appendTo("body");
                var offset = $("#" + id_obj).offset();
                $("#" + divID).css("top", offset.top - 2).css("left", offset.left + 12);

                $("#" + divID).focus();
                $("#" + divID).blur(function () {

                    var parametri = '{  "svc_type":"set_field", "stile":"' + $("#" + id_obj).attr("stile") + '", "recId":"' + $("#" + id_obj).attr("recId") + '", "value":"' + $("#" + divID).attr("value") + '"}';
                    var onComplete = function (msg) {
                        // Salvataggio completato
                        if (msg.d == "+Ok") {
                            if ($("#" + divID).val() != "") {
                                $("#" + id_obj).attr("src", "/progettogestionale/images/postit.gif");
                            }
                            else {
                                $("#" + id_obj).attr("src", "/progettogestionale/images/postit_light.gif");
                            }
                            $("#" + id_obj).attr("title", $("#" + divID).val());
                        }
                        else {
                            $("#" + id_obj).attr("src", "/progettogestionale/images/postit_error.gif");
                        }
                        $("#" + divID).remove();
                    }
                    // Avvia salvataggio
                    var options = {
                        type: "POST",
                        url: jsLib_svc_url + "/getJsonRs",
                        data: "{'parametri':'" + parametri + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        async: true,
                        success: onComplete,
                        error: function (msg) {
                            alert("Errore: " + msg.responseText);
                        }
                    };
                    $.ajax(options);
                });
            }
            postIT.load_data($(this).attr("id"), divID, onComplete);
        });
    }
 }


 var callTo = {
     init: function () {
         /*$('.callTo').each(function () {
         postIT.load_data($(this).attr("id"));
         });        */
         $(".call_to").attr("title", "Chiama ora sull'interno");
         $(".call_to").css("cursor", "pointer");
         $(".call_to").click(function () {
             if ($(this).attr("edit_obj_id") != null && $(this).attr("edit_obj_id") != "" && $(this).attr("edit_obj_id") != "undefined") {
                 callTo.call($("#" + $(this).attr("edit_obj_id")).val());
             } else {
                 callTo.call($(this).attr("number"));
             }
         });
     },
     call: function (dest_cid) {
         
         if (dest_cid.charAt(0) == "+") {
             dest_cid = dest_cid.substring(3);
         }
         var url = "/progettogestionale/Anagrafica/AsteriskWS.asp?action=callTo&dest_cid=" + dest_cid;
          //window.open(url);
          var jqxhr = $.get(url, function () {
             //alert("success");
         })
         //.success(function() {  })
         //.error(function () { alert("error"); })
         //.complete(function() {  });

     }
 }
 
 var fileSelection = {
     hash: "",
     destId: "",
	 lblId: "",
     init: function () {
        $('.fileSelection').click(function () {
			fileSelection.destId = $(this).attr("input_id");
			fileSelection.lblId = $(this).attr("lbl_id");
			var finder = new CKFinder();
			finder.selectActionFunction = function( fileUrl ){
				
				$("#"+fileSelection.destId).val(fileUrl);
				var ts=fileUrl.split("/");
				$("#"+fileSelection.lblId).html(ts[ts.length-1]);
			};
			finder.SelectFunction = 'ShowFileInfo';
			finder.popup();
         });
     }
 }
 
 var htmlContent = {
     hash: "",
     destId: "",
     timeout: null,
     init: function () {

         $('.htmlContent').click(function () {
             htmlContent.destId = $(this).attr("input_id");
             htmlContent.hash = "TABEDITOR" + htmlContent.destId;

             //setSessionVar(htmlContent.hash, $("#" + htmlContent.destId).val().replace("'","\\'"), function (s) {
             setSessionVar(htmlContent.hash, $("#" + htmlContent.destId).val().replace(/\'/g, "&#39;"), function (s) {
             
                 var tWindowProp = "dialogWidth:" + screen.width + "px;dialogHeight:" + screen.height + "px;center=yes;scroll:off;";
                 var printWindow = window.showModalDialog("/progettogestionale/gASPnet/html_editor.aspx?hash=" + htmlContent.hash, "", tWindowProp);
                 var tReturnValue = printWindow;
                 getSessionVar(htmlContent.hash, function (s, res) {
                     $("#" + htmlContent.destId).val(res);
                 }, null)
                 return printWindow;
             }, null);
         });

         $('.htmlContent').mouseover(function (e) {
             htmlContent.destId = $(this).attr("input_id");
             $(".html_tooltip").remove();
             $(this).after("<div class='html_tooltip' id='tooltip" + htmlContent.destId + "'>" + $("#" + htmlContent.destId).val() + "</div>");
             $(".html_tooltip")
                 .css("top", 5)
                 .css("left", e.pageX + 15)
                 .click(function () {
                     $(".html_tooltip").remove()
                 })
                 .mouseover(function () {
                     clearTimeout(htmlContent.timeout);
                 })
                 .mouseout(function () {
                     htmlContent.timeout = window.setTimeout('$(".html_tooltip").remove()', 1000);
                 });
         });

         $('.htmlContent').mouseout(function () {
             htmlContent.timeout = window.setTimeout('$(".html_tooltip").remove()', 2000);
         });
     }
 }
 $(document).ready(function () {
     postIT.init();
     callTo.init();
     htmlContent.init();
     fileSelection.init();
 });
