/**
 * Processa i dati restituiti dalle query ajax
 * @author Giovanni Mittone
 */

function ajaxToArray(data) {
    var _index = 0;
    var _data = data;

    this.toArray = function() {
        var ret = new Array();
        // Struttura: {"elemento0","elemento1",{"elemento0"}}
        // Ricerca l'inizio dell'array
        for(;(_index < _data.length) && (_data[_index] != '{'); _index++){}
        // Ricerca l'inizio dell'elemento
        var sepNeeded = false;
        for(_index++ ;_index < _data.length; _index++) {
            switch(_data[_index]) {
                case '{': // Nuovo array
                    ret.push(this.toArray());
                    break;
                case '\"': // Nuovo valore
                    if(!sepNeeded) {
                        var value = "";
                        for(_index++;(_index < _data.length); _index++) {
                            if(_data[_index] != '\"')
                                value += _data[_index];
                            else {
                                if((_index + 1 < _data.length) && (_data[_index + 1] == '\"')) {
                                    value += '\"';
                                    _index++;
                                } else
                                    break;
                            }
                        }
                        ret.push(value);
                        sepNeeded = true;
                    }
                    break;
                case ',': // Separatore di valori
                    sepNeeded = false;
                    break;
                case '}': // Termina l'array
                    return ret;
            }
        }
        return ret;
    }
}


(function($){$.fn.nsvFly = function(folder) {
    // Crea il fly aggiungendolo al documento
    if($("#flyattivita").length <= 0)
        $("body").append("<div id=\"flyattivita\"><input id=\"flyid\" name=\"flyid\" type=\"hidden\" value=\"\"><img id=\"flyimage\" alt=\"\" src=\"\"/><p id=\"flycontent\"></p></div>");

    var _fly = $("#flyattivita");
    var _flyHeight = $("#flyattivita").height();
    var _target = $(this);
    var _isVisible = false;
    var _folder = folder;
    var _flyArray = new Array();

    // Carica il contenuto dei fly come HTML in un array
    _target.each(function(){
        var t = new Array();
        t[0] = $(this).attr("id");
        jQuery.get(folder + t[0] + ".fly", function(data) {
            t[1] = data;
            t[2] = new Image();
            t[2].src = folder + t[0] + ".png";
            _flyArray.push(t);
        });
    });

    // Carica il contenuto del fly
    this.loadFly = function(item) {
        for(var cont = 0; cont < _flyArray.length; cont++) {
            if((_flyArray[cont] instanceof Array) && (_flyArray[cont][0] == item)) {
                $("#flyimage").attr("src", _flyArray[cont][2].src);
                $("#flycontent").html(_flyArray[cont][1]);
                $("#flycontent").offset({top: $("#flyattivita").offset().top + _flyHeight - $("#flycontent").height(),
                    left: $("#flyattivita").offset().left});
                return;
            }
        }
        $("#flyimage").attr("src", "");
        $("#flycontent").html("<h3>Fly non identificato!</h3>");
        $("#flycontent").offset({top: $("#flyattivita").offset().top + _flyHeight - $("#flycontent").height(),
            left: $("#flyattivita").offset().left});
    }

    // Modifica la coordinata y del fly per non allungare la pagina
    this.correctYCoord = function(y) {
        var diff = y + _flyHeight - $("body").height();
        return (diff > 0)?y - diff:y;
    }

    // Gestisce l'hover sui target
    _target.bind("mouseover", {objFly: this},
        function(event) {
            var left = $(this).offset().left + $(this).width() + 5;
            var top = event.data.objFly.correctYCoord($(this).offset().top);
            $("#flyid").val($(this).attr("id"));
            _fly.stop(true, true);
            if(_isVisible) {
                left -= _fly.offset().left;
                top -= _fly.offset().top;
                var dLeft = (left >= 0)?("+=" + left):("-=" + (-left));
                var dTop = (top >= 0)?("+=" + top):("-=" + (-top));
                _fly.animate({"left": dLeft, "top": dTop}, 500);
                event.data.objFly.loadFly($("#flyid").val());
            } else {
                _fly.fadeIn(700);
                _fly.offset({"left": left, "top": top});
                event.data.objFly.loadFly($(this).attr("id"));
            }
            _isVisible = true;
        });
    _target.bind("mouseout", {objFly: this},
        function(event) {
            _fly.delay(700).fadeOut(700, function() {
                _isVisible = false;
            });
        });

    // Gestisce l'hover sul fly
    _fly.bind("mouseover", {objFly: this},
        function(event){
            _fly.stop(true, true);
        });
    _fly.bind("mouseout", {objFly: this},
        function(event) {
            _fly.delay(700).fadeOut(700, function() {
                _isVisible = false;
            });
        });
};})( jQuery );


function nsvUploadifyRemoveFile(obj,filename) {
    var _get = $(obj).parent().parent().parent().parent().attr("get");
    var _id = $(obj).parent().parent().parent().parent().attr("itemID");
    jQuery.post(_get, jQuery.param({action:'remove',id:_id,file:filename}),
        function(){
            $(obj).parent().parent().remove();
        });
    return false;
}
function nsvUploadifyFilesRowFormat(row) {
    return "<tr><td>" + row[0] + "</td>" +
        "<td><a target=\"_blank\" nohelp href=\"" + (row[2]).replace(/\\/g,'/') + "\" title=\"Apri file\"><img src=\"templates/nuotosanvito/images/mostra.png\"/></a>&nbsp;" +
        "<a href=\"#\" onclick=\"nsvUploadifyRemoveFile(this,'" + (row[2]).replace(/\\/g,'\\\\') + "');\" title=\"Cancella file\"><img src=\"templates/nuotosanvito/images/cancella.png\"/></a>" +
        "</td></tr>";
}
(function($){$.fn.nsvUploadify = function(get,baseFolder,_fileTypeDesc,_fileTypeExts) {
        $(this).parent().append("<table id=\"" + $(this).attr("id") + "Files\" get=\"" + get + "\" baseFolder=\"" + baseFolder + "\" itemID=\"\"><thead><tr><th>File</th><th>Azioni</th></tr></thead><tbody></tbody></table>");
        $(this).uploadify({auto: true, multi: true, sizeLimit: 32000000, removeCompleted: true, removeTimeout: 0,
            buttonText: 'Seleziona files',
            swf: 'templates/nuotosanvito/scripts/uploadify.swf',
            cancelImage: 'templates/nuotosanvito/images/cancella.png',
            uploader: get,
            checkExisting: get + '&action=check',
            fileTypeDesc: (!_fileTypeDesc?"Tutti i files":_fileTypeDesc),
            fileTypeExts: (!_fileTypeExts?"*.*":_fileTypeExts),
            onUploadComplete: function(event) {
                var bFolder = $("#" + $(this).attr("id") + "Files").attr("baseFolder") + $("#" + $(this).attr("id") + "Files").attr("itemID") + "\\";
                $("#" + $(this).attr("id") + "Files").append(nsvUploadifyFilesRowFormat(new Array(event.name, event.size, bFolder + event.name)));
            }
        });
};})( jQuery );


(function($){$.fn.nsvMessage = function(_width, _height, _title, _message) {
        $(this).dialog({width: _width, height: _height, title: _title});
        $(this).html(_message);
        $(this).dialog("open");
};})( jQuery );


(function($){$.fn.nsvTime = function() {
        var __point = false;
        // Add event for value restriction
        $(this).keypress(function(event) {
            if(((event.which < 48) || (event.which > 57)) && (event.which > 24) && (event.which < 65536)) {
                if(event.which == 58) {
                    if(__point)
                        event.preventDefault();
                    else
                        __point = true;
                    return;
                }
            }
        });
        // Add event for value validation
        var _validation = function(event) {
            var text = $(this).val();
            var result = '';
            // Validate characters
            for(var cont = 0; cont < text.length; cont++) {
                var cc = text.charCodeAt(cont);
                if((cc >= 48) && (cc <= 57))
                    result += text.charAt(cont);
            }
            if(text.length > 0) {
                for(cont = result.length; cont < 4; cont++) {
                    result = '0' + result;
                }
                $(this).val(result.slice(0, 2) + ':' + result.slice(2, 4));
                __point = true;
            } else
                $(this).val('');
        };
        $(this).focusin(_validation);
        $(this).focusout(_validation);
};})( jQuery );


function nsvMessage(_width, _height, _title, _message) {
    $("#dMessage-form").nsvMessage(_width, _height, _title, _message);
}


function stringToHex(string) {
    out = "";
    for(cont = 0; cont < string.length; cont++) {
        temp = string.charCodeAt(cont).toString(16).toUpperCase();
        switch(temp.length) {
            case 0:out += '00';break;
            case 1:out += '0' + temp;break;
            default:out += temp.substr(0, 2);
        }
    }
    return out;
}

function hexToString(string) {
    out = "";
    for(cont = 0; cont < string.length; cont += 2) {
        out += String.fromCharCode(parseInt(string.substr(cont, 2), 16));
    }
    return out;
}


$(function() {
    /* GESTIONE MENU A LIVELLI */
    // Espande il sottomenu nella posizione corretta
    $("li.submenu").bind("mouseenter click", function(){
        if($(this).children("ul.submenu").css("display") == "none") {
            var x = $(this).offset().left, y = $(this).offset().top;
            // Imposta la posizione del figlio se il menu è orizzontale
            if($(this).parent("ul").hasClass("horz")) {
                x += 1;
                y += $(this).height() - 1;
            }
            // Imposta la posizione del figlio se il menu è verticale
            if($(this).parent("ul").hasClass("vert")) {
                x += $(this).width() - 1;
                y += 1;
            }
            // Chiude altri menu aperti
            $(this).parent().children("li").children("ul.submenu").stop(true, true).hide(250);
            // Imposta la posizione e mostra il sottomenu
            $(this).children("ul.submenu").stop(true, true).show(250).delay(5000).hide(250);
            $(this).children("ul.submenu").offset({"left": x, "top": y});
        } else {
            // Blocca un'eventuale chiusura
            $(this).children("ul.submenu").stop(true, true);
        }
    });
    // Blocca il nascondimento del menu se ci si entra col mouce
    $("ul.submenu").mouseenter(function(){
        $(this).stop(true, true).show();
    });
    // Nasconde il menu se il mouse non è più al suo interno
    $("ul.submenu").mouseleave(function(){
        if(($(this).children("ul.submenu").length <= 0 ) || ($(this).children("ul.submenu").css("display") == "none"))
            $(this).delay(1500).hide(250)
    });
    // Se viene cliccato un elemento, nasconde il suo menu
    $("ul.submenu li a").click(function() {
        $(this).parent().parent("ul.submenu").hide(250);
    });
    // Simula il click dell'elemento a figlio
    $("ul.submenu li").click(function(){
        document.location = $(this).children("a").attr("href");
        $(this).parent().parent("ul.submenu").hide(250);
    });
    
    
    /* GESTIONE SELEZIONE TAB */
    
    $("ul.tab li.default").addClass("selected");
    $("ul.tab li").each(function(){
        if(location.search.search($(this).attr("tabid")) > 0) {
            $("ul.tab li.default").removeClass("selected");
            $(this).addClass("selected");
        }
    });
    $("ul.tab li").click(function(){
        if($(this).attr("tabid").length > 0) {
            window.location.href = $(this).parent().attr("href") + "&menu=" + $(this).attr("tabid");
        }
    });
});
