var th_openWindow  = "";
var th_tooltipText = {};
var th_msgBoxCss   = {
    "open"  : {width: "280px", height: "100px", marginLeft : "-140px", marginTop : "-50px", top: "50%", left: "50%", opacity: 1},
    "close" : {width: "0px",   height: "0px",   marginLeft : "0px",    marginTop : "0px",   top: "50%", left: "50%", opacity: 0}
}

var th_cronBoxCss  = {
    "open"  : {width: "300px", height: "200px", marginLeft : "-171px", marginTop : "-121px", top: "50%", left: "50%", opacity: 1},
    "close" : {width: "0px", height: "0px", marginLeft : "0px", marginTop : "0px", top: "50%", left: "50%", opacity: 0}
}

var th_sqlBoxCss  = {
    "open"  : {width: "400px", height: "230px", marginLeft : "-221px", marginTop : "-136px", top: "50%", left: "50%", opacity: 1},
    "close" : {width: "0px", height: "0px", marginLeft : "0px", marginTop : "0px", top: "50%", left: "50%", opacity: 0}
}

$(document).ready(
    function() {
        //IMPOSTA VALORE INIZIALE SELECTEDID
        $(window).data("selectedId", false);
        $(window).data("selectedIdValue", 0);
        $(window).data("isEvaluatingKeycode" , false);
        $("#msgBox").data("isOpen", false);

        // ATTACCO LA FUNZIONE DEL CLICK ALLE RIGHE DELL'ELENCO
        th_rowListClick();

        // CONTROLLO SE SI SONO VERIFICATI ERRORI DA PHP
        if(typeof errorMsg["th_error"][0]!="undefined" && errorMsg["th_error"][0]!="") {
            th_errorHandler(errorMsg);
        }

        $("body").css("overflow", "auto");

        // FUNZIONE PER IL MENU'
        $("#nav-one li").hover(
            function() { $("ul", this).fadeIn("fast"); },
            function() { }
        );

        // LEGGE I TOOLTIP DA TITLE E LI SALVA
        $("form :input").add("form :radio").add("form :checkbox").each(
            function () {
                if($(this).attr("title")!="") {
                    th_tooltipText[$(this).attr("name")] = $.format($(this).attr("title"), "<br>");
                    $(this).attr("title", "");
                }
            }
        ).hover(
            function() {
                if(typeof th_tooltipText[$(this).attr("name")]!="undefined") {
                    var tooltip_1 = $(this).offset();
                    tooltip_1["top"] += $(this).height() + 4;
                    $("#inputTooltip").html(th_tooltipText[$(this).attr("name")]).css(tooltip_1).show();
                }
                return false;
            },
            function() {
                $("#inputTooltip").html("").hide();
            }
        );

        if (document.all) {
            $("#nav-one li").hoverClass("sfHover");
        }

        // ACTIVATE DRAG & DROP ON PHP DEBUG WINDOW
        if($("#string").length) {
            $("#string").draggable({ opacity: 0.40 , cursor: "move", handle: ".debug1"});
        }
        // ACTIVATE DRAG & DROP ON SQL DEBUG WINDOW
        if($("#sql").length) {
            $("#sql").draggable({ opacity: 0.40 , cursor: "move", handle: ".debug1"});
        }
    }
);

$.fn.hoverClass = function(c) {
    return this.each(
        function() {
            $(this).hover(
                function() { $(this).addClass(c);  },
                function() { $(this).removeClass(c); }
            );
        }
    );
};

// CREA O RIMUOVE LA SCHERMATA NERA IN TRASPARENZA
var th_blockScreen = function(action) {
    if(action=="create") {
        var blockDiv = "<div id=\"blockScreen\"></div>";
        $("html").css("overflow", "hidden");
        $("body").css("overflow", "hidden");
        $(window).data("scrollTop", $(window).scrollTop());
        $(window).scrollTop(0);
        $("body").append(blockDiv);
        $("#blockScreen").fadeTo("slow", 0.7);
    }
    else {
        $("html").css("overflow", "auto");
        $("body").css("overflow", "");
        $("#blockScreen").fadeOut("normal",
            function () {
                $(window).scrollTop($(window).data("scrollTop"));
                $(window).data("scrollTop", $(window).scrollTop());
                $(this).remove();
            }
        );
    }
}

// MESSAGE BOX PER SOSTITUIRE L'ALERT
var th_messageBox = function(options) {
    if(!$("#msgBox").data("isOpen")) {
        th_blockScreen("create");
        $("#msgBox").data("isOpen", true);
        var message  = (typeof options["message"]=="string") ? options["message"] : "";
        var response = (typeof options["confirm"]=="boolean") ? options["confirm"] : false;
        var callback = (typeof options["callback"]=="function") ? options["callback"] : function() { return true };

        $("#msgBox").css(th_msgBoxCss["close"]);
        $("#msgBox").animate(th_msgBoxCss["open"], 500);
        $("#msgBox #msgText").html(message);
        if(response) {
            $("#msgBox .confirm").show();
            $("#msgBox .alert").hide();
        }
        else {
            $("#msgBox .confirm").hide();
            $("#msgBox .alert").show();
        }
        $("#msgBox input[name='okButton']").bind("click",
            function (e) {
                callback();
                th_messageBox();
            }
        );
    }
    else {
        $("#msgBox").data("isOpen", false);
        $("#msgBox input[name='okButton']").unbind("click");
        $("#msgBox").animate(th_msgBoxCss["close"], 500,
            function() {
                $(this).hide();
                th_functionExec("close")
            }
        );
        th_blockScreen("delete");
    }
}

var th_checkDataSelection = function() {
    return ($(window).data("selectedId")==false) ? false : true;
}

var th_manageDataSelection = function(action, $obj) {
    if(action == "set") {
        $(window).data("selectedId", $obj.attr("id"));
        $(window).data("selectedIdValue", $obj.children("td:first").children("input[name='rowId']").val());
    }
    else {
        $(window).data("selectedId", false);
        $(window).data("selectedIdValue", "0");
    }
}

var th_toggle = function(objId) {
    if (typeof th_Windows["toggle"]!="undefined"){
        objId=th_Windows["toggle"];
    }
    $("#" + objId + "Container").toggle();
    $("#Toggle").attr("src", (($("#Toggle").attr("src")== homeDir + imgDir + "/module_toggle_closed.gif") ? homeDir + imgDir + "/module_toggle_open.gif" : homeDir + imgDir + "/module_toggle_closed.gif"));
}

var th_selectBoxPopulate = function(selectBox, url, action, params, reset) {
    $.ajax({
        type: "POST",
        url: url,
        data: "action=" + action + ((typeof params!="undefined") ? params : ""),
        async: true,
        dataType : "json",
        success:function(result) {
            if(typeof result["th_error"]!="undefined") {
                return th_errorHandler(result);
            }
            $selectElements = $("select[name='"+selectBox+"']");
            if(reset) {
                $selectElements.html("");
            }

            $selectElements.each(
                function (i) {
                    $optionElements = $(this).children();
                    if($optionElements.length<=1) {
                        $.each(result,
                            function(type, fieldName) {
                                $selectElements.eq(i).append("<option value=\"" + fieldName["id"] + "\">" + fieldName["nome"] + "</option>")
                            }
                        );
                    }
                }
            );
            return true;
        },
        error: th_errorFx
    });
}

// PULISCE IL FORM DELLA FINESTRA APERTA
var th_cleanForm = function() {
    $.each(th_Windows[th_openWindow]["input"], function(type, fieldName) {
        var $inputElements = $(th_Windows[th_openWindow]["form"] + " *[name='"+ fieldName +"']");
        var elementType = $inputElements.attr("type");

        switch(elementType) {
            case "hidden" :
            case "text":
            case "textarea":
            case "password":
                $inputElements.val("");
                break;
            case "select-one":
            case "select-multiple":
                $inputElements.attr("selectedIndex", 0);
                break;
            case "checkbox":
            case "radio":
                $inputElements.attr("checked", false);
                break;
        }
    });
}

// RIEMPIE CON I DATI IL FORM DELLA FINESTRA APERTA
var th_fillForm = function(result) {
    $.each(th_Windows[th_openWindow]["input"], function(type, fieldName) {
        $(th_Windows[th_openWindow]["form"] + " *[name='"+ fieldName +"']").val(result[fieldName]);
    });
}

// LEGGE IL FORM DELLA FINESTRA APERTA E SCRIVE I DATI DA POSTARE
var th_getFormValues = function() {
    data2Send="";
    $.each(th_Windows[th_openWindow]["input"], function(type, fieldName) {
        var $inputElements = $(th_Windows[th_openWindow]["form"] + " *[name='"+ fieldName +"']");
        var elementType = $inputElements.attr("type");

        switch(elementType) {
            case "hidden" :
                data2Send += "&" + fieldName + "=" + ((type=="id") ? $(window).data("selectedIdValue") : $inputElements.val());
                break;
            case "text":
            case "textarea":
            case "select-one":
                data2Send += "&" + fieldName + "=" + $inputElements.val();
                break;
            case "password":
                data2Send += "&" + fieldName + "=" + $inputElements.val();
                break;
            case "select-multiple":
            case "checkbox":
                $inputElements.each(
                    function() {
                        data2Send += "&" + $(this).attr("name") + "=" + ($(this).is(":checked") ? 1 : 0);
                    }
                );
                break;
            case "radio":
                if(typeof $inputElements.filter(":checked").val()!="undefined") {
                    data2Send += "&" + fieldName + "=" + $inputElements.filter(":checked").val();
                }
                break;
        }
    });
    return data2Send;
}

// FUNZIONI DI CLICK E DOPPIO CLICK SULLA TABELLA DEI RISULTATI.
var th_rowListClick = function() {
    $("tr.odd[id]").click(
        function() {
            if($(this).hasClass("active")) {
                $(this).removeClass("active");
                th_manageDataSelection("reset");
            }
            else {
                if($(window).data("selectedId")!=false) {
                    $("tr.odd#"+$(window).data("selectedId")).removeClass("active");
                }
                $(this).addClass("active");
                th_manageDataSelection("set", $(this));
            }
        }
    ).dblclick(
        function() {
            if($(window).data("selectedId")!=false) {
                $("tr.odd#"+$(window).data("selectedId")).removeClass("active");
            }
            $(this).addClass("active");
            th_manageDataSelection("set", $(this));
            if(typeof th_Windows['dblclick']=="string") { th_functionExec(th_Windows['dblclick']); }
            else { th_functionExec("edit"); }
        }
    );
}

/* PHP EXCEPTION VALUE */
var DB_CONNECTION      = 1;  /**< database connection failed. */
var DB_SELECTION       = 2;  /**< database selection failed. */
var DB_ERROR_RESULT    = 3;  /**< query execution failed. */
var DB_NO_RESULT       = 4;  /**< query returns empty result. */
var DB_ERROR_DUPLICATE = 5;  /**< query execution failed. */

/* CALL EXCEPTION*/
var INVALID_CALL       = 10; /**< missing action to execute. */
var INVALID_FUNCTION   = 11; /**< missing function to execute. */
var INVALID_DATA       = 12; /**< wrong data in post. */
var REQUIRED_DATA      = 13; /**< missing required data in post. */

/*EXECUTION EXCEPTION*/
var NO_INSERT          = 20; /**< no record inserted in db. */
var NO_UPDATE          = 21; /**< no record updated in db. */
var NO_DELETE          = 22; /**< no record deleted in db. */

/*AUTHORIZATION EXCEPTION*/
var LOGIN_ERROR        = 30; /**< user not logged. */
var AUTH_ERROR         = 31; /**< user not authorized to see the page. */

/*TEMPLATE EXCEPTION*/
var TEMPLATE_ERROR     = 40; /**< error loading template. */
var TAG_ERROR          = 41; /**< tag error in loaded template */

var th_errorFx = function(request, error, obj) {
    th_errorHandler(error);
    return false;
}

var th_errorHandler = function(dato) {
    if(typeof dato=="string") {
        alert(dato);
    }
    else if(typeof dato=="object") {
        for(var errorObj in dato["th_error"]) {
            switch(parseInt(errorObj)) {
                case LOGIN_ERROR:
                    alert(dato["th_error"][LOGIN_ERROR]);
                    location.href="logout.php";
                    break;
                default :
                    alert(dato["th_error"][errorObj]);
                    break;
            }
        }
    }
    //th_functionExec("close");
}

/*SOLO PER VOCI MENU KEYPASSWORD*/
var initGestKp=function () {
    setTimeout("setDsnAs400()",500);
}

var setDsnAs400=function () {
    var dsnAs400=$("#dsnAs400").val();
    if (!dsnAs400) {
        $("#annullaChange").addClass("no_display");
        $("#annullaChange2").removeClass("no_display");
        th_functionExec("change_As400");
    }
    var descDsnAs400=$("#descDsnAs400").val();
    if (descDsnAs400) {
        var title=th_Windows['title']+' - '+descDsnAs400;
        $('#headerLista').html(title);
    }
}

var th_resetChangeBox = function () {
    $("#annullaChange").removeClass("no_display");
    $("#annullaChange2").addClass("no_display");
}

var onChangeTipoData = function(elementTipoData) {
    ($(elementTipoData).val()==1) ? tipoDataDisabled=false : tipoDataDisabled=true;
    $(elementTipoData).parents("li:first").find(' :text[name="config_data_attivazione"]').attr('disabled', tipoDataDisabled);
}

var postSearchBox=function () {
    if(th_checkDataSelection()) {
        th_manageDataSelection("reset");
    }
}

var th_explodeDettagli=function(element) {
    var elementHeight=$(element).height();
    if ($(element).find(' .dettagli').hasClass('no_display')) {
        $(element).height(elementHeight*2);
    } else {
        $(element).height(elementHeight/2);
    }
    var divDettagli=$(element).find(' .dettagli').toggleClass('no_display');
}

var cronHandler   = "";
var cronSettings  = {
                        activation : {url : "activation.php", text : "Funzione per l'importazione delle keypassword create da As/400 a Mysql"},
                        clear_tokens : {url : "clear_tokens.php", text : "Funzione per la pulizia dei tokens rimasti associati alle keypassword (NB estromette chi è loggato)"},
                        contract_checker : {url : "contract_checker.php", text : "Funzione per l'accertamento dei nuovi contratti inseriti"},
                        email_export : {url : "email_export.php", text : "Funzione per l'esportazione su As/400 delle email degli utenti profilati"},
                        sgancio : {url : "sgancio.php", text : "Funzione per sganciare le chiavette USB ritornate indietro dall'utente associato"},
                        state : {url : "state.php", text : "Funzione per il cambio di stato degli utenti"}
                    }

var th_functionExecCron = function(action, handler) {
    if(!$(window).data("dnsList")) {
        th_selectBoxPopulate("dsnAs400", "gestione_keypassword.php", "ListDsnAs400");
        $(window).data("dnsList", true);
    }

    switch(action) {
        case "open":
            th_blockScreen("create");
            $("#cron").draggable({ opacity: 0.40 , cursor: "move", handle: ".makeMeDraggable"});
            //reset position
            $("#cron").css(th_cronBoxCss["close"]);
            $("#cron").animate(th_cronBoxCss["open"], 1000,
                function () {
                    // SET DIV OVERFLOW (FIREFOX LAYOUT PROBLEM)
                    $("#cron div#cronResult").css("overflow", "auto");
                }
            );
            cronHandler = handler;
            $("#cronDescription").html(cronSettings[handler].text);
            $("#cron input[name='okButton']").one("click",
                function() {
                    $(this).hide();
                    $("#cron input[name='resetButton']").attr("value", "   Chiudi");
                    // loading gif
                    $("#cron table").hide();
                    $("#cron .animation").show();

                    th_functionExecCron(cronHandler);
                }
            );
            return false;

            break;
        case "activation":
        case "clear_tokens":
        case "contract_checker":
        case "email_export":
        case "sgancio":
        case "state":
            data2Send = "&dsnAs400=" + $("#cron *[name='dsnAs400']").val();

            $.ajax({
                type: "POST",
                url: cronSettings[action].url,
                data: "ajax=1&command=" + action + data2Send,
                async: false,
                dataType : "html",
                success:
                    function(result) {
                        if(result.indexOf("th_error")!=-1) {
                            eval("result = " + result + ";");
                        }
                        if(typeof result["th_error"]!="undefined") {
                            th_errorHandler(result);
                            return th_functionExecCron("close");
                        }

                        $("#cron").find("table").show();
                        $("#cron").find(".animation").hide();
                        $("#cron").animate({height: "470px", marginTop:"-256px"});
                        $("#cron div#cronResult").animate({height: "320px"}).css("overflow", "scroll").html(result.replace(/\n/g, "<br/>"));
                        return false;
                    },
                error:
                    function(request, error, obj) {
                        th_errorHandler(error);
                        th_functionExecCron("close");
                    }
            });
            break;

        case "close":
            $("#cron div#cronResult").css("overflow", "hidden");
            $("#cron").animate(th_cronBoxCss["close"], 1000,
                function () {
                    $(this).draggable("destroy");
                    $(this).find("#cronResult").css("height", 50).html("");
                    $(this).find("table").show();
                    $(this).find(".animation").hide();
                    $(this).hide();
                    $(this).find("input[name='okButton']").show();
                    $("#cron input[name='resetButton']").attr("value", "   Annulla");
                    th_blockScreen("delete");
                }
            );
            break;
    }
}

var th_functionExecSql = function(action, handler){

    if (!$(window).data("dnsList")) {
        th_selectBoxPopulate("dsnAs400", "gestione_keypassword.php", "ListDsnAs400");
        $(window).data("dnsList", true);
    }

    switch (action) {
        case "open":
            th_blockScreen("create");
            $("#sqlBox").draggable({
                opacity: 0.40,
                cursor: "move",
                handle: ".makeMeDraggable"
            });
            //reset position
            $("#sqlBox").css(th_sqlBoxCss["close"]);
            $("#sqlBox").animate(th_sqlBoxCss["open"], 1000);
            $("#sqlBox .sql").val("");
            $("#sqlBox input[name='okButton']").one("click",
                function() {
                    $(this).hide();
                    $("#sqlBox table").hide();

                    var query = $("#sqlBox .sql").val();
                    if(query.indexOf("UPDATE")!=-1 || query.indexOf("update")!=-1) {
                        $("#sqlBox .confirmMsg").show();
                        $("#sqlBox .confirmMsg input[name='okButton']").one("click",
                            function() {
                                $("#sqlBox .confirmMsg").hide();
                                $("#sqlBox .animation").show();
                                th_functionExecSql("executeSql");
                            }
                        );
                        return false;
                    }
                    else {
                        $("#sqlBox .animation").show();
                    }
                    // loading gif
                    th_functionExecSql("executeSql");
                    return true;
                }
            );
            //return false;

            break;
        case "executeSql":
            data2Send = "&dsnAs400=" + $("#sqlBox *[name='dsnAs400']").val() + "&sql=" + $("#sqlBox .sql").val();
            $.ajax({
                type: "POST",
                url: "sql.php",
                data: "ajax=1" + data2Send,
                async: false,
                dataType: "html",
                success: function(result){
                    if (result.indexOf("th_error") != -1) {
                        eval("result = " + result + ";");
                    }
                    if (typeof result["th_error"] != "undefined") {
                        th_errorHandler(result);
                        return th_functionExecSql("close");
                    }

                    $("#slqBox table").show();
                    $("#slqBox .confirmMsg").hide();
                    $("#slqBox .animation").hide();

                    $("#content").html(result);
                    th_functionExecSql("close");
                    return false;
                },
                error: function(request, error, obj){
                    th_errorHandler(error);
                    th_functionExecSql("close");
                }
            });
            break;

        case "close":
            $("#sqlBox").animate(th_sqlBoxCss["close"], 1000, function(){
                $(this).draggable("destroy");
                $(this).find("table").show();
                $(this).find(".animation").hide();
                $(this).find(".confirmMsg").hide();
                $(this).hide();
                $(this).find("input[name='okButton']").show();
                $("#sqlBox input[name='resetButton']").attr("value", "   Annulla");
                th_blockScreen("delete");
            });
            break;
    }
}

