﻿function shareStatus(myUsername, idGroup, idStatus) {
    $('.videoEmbed').hide();
    $('#dialogShowGroupSelectDestination').dialog({
        bgiframe: true,
        autoOpen: true,
        modal: true,
        resizable: false,
        width: 450,
        height: 0,
        title: 'Condividi il mesaggio',
        buttons: {
            'Annulla': function() {
                $(this).dialog('close');
            },
            'Mie discussioni': function() {
                shareOnOtherWall(idGroup, idStatus, myUsername);
                $(this).dialog('destroy');
            },
            'Discussioni degli Amici': function() {
                selectFriendForShareStatus(idStatus);
                $(this).dialog('destroy');
            }
        },
        close: function() {
            $('.videoEmbed').show();
            $(this).dialog('destroy');
        }
    });
}

function postEventsAsStatus(idWallToWrite) {
    //$("#flash").show("slide", { direction: "up" }, 500);
    var contacts = new Array();
    $.each($('.listContactEventPanel li'), function(i, v) {
        var contactLi = "";
        $.each($(v).children('span'), function(j, k) {
            contactLi += $(k).text() + ";";
        });
        contacts.push(contactLi);
    });
    var admins = new Array();
    $.each($('.postEvent-show-adminEvent .usernameSelectDialog'), function(i, v) {
        admins.push($(v).text())
    });
    $('#wall1 #statusArea').prepend('<img class="post-loader-gif" style="margin:80px 0px 80px 240px" src="../../Content/ajax-loader.gif" />');
    jQuery.ajaxSettings.traditional = true;
    $.post('/Calendar/setNewStatusEvent', { idWall: idWallToWrite, content: $('#TextareaEvent').val(), dateStart: $('#dateEventStart').val(), dateEnd: $('#dateEventStart').val(), hourStart: $('#selectHourEvent option:selected').val(), minutesStart: $('#selectMinutesEvent option:selected').val(), hourFinish: $('#selectMinutesEvent option:selected').val(), minuteFinish: $('#selectMinutesEvent option:selected').val(), title: $('#titleEvent').val(), nameLocal: $('#aliasLocation').val(), cityName: $('#cityEvent').val(), adress: $('#adressCity').val(), number: $('#numberAdress').val(), idPhotoLogo: $('#idPhotoLogoEvent div').text(), idPhotoPoster: $('#idPhotoPosterEvent div').text(), contacts: contacts, adminsEvent: admins, makeWall: $('.postEvent-checkWall').is(':checked'), makeAlbum: $('.postEvent-checkAlbum').is(':checked'), description: $('#TextareaEvent').val() }, function(data) {
        $('.post-loader-gif').remove();
        $('#wall1' + idWallToWrite + ' #statusArea').prepend(data);
    }, "text");
}

var idWallSelectedCorrelation = -1;
var nameWallSelectedCorrelation = "";
function showContentRelation(idContent, element) {
    element.append('<div id="dialogShowWallRelation' + idContent + '" style="display:none"></div>');
    $.post('/Wall/getWallContentRelation', { idContent: idContent }, function(data) {
        $('#dialogShowWallRelation' + idContent).html(data);
        $('#dialogShowWallRelation' + idContent).dialog({
            resizable: false,
            bgiframe: true,
            autoOpen: true,
            modal: true,
            reseizable: false,
            width: 600,
            height: 300,
            title: 'Discussioni correlate al messaggio',
            buttons: {
                'Apri': function() { openTabWallIndex(idWallSelectedCorrelation, nameWallSelectedCorrelation); $(this).dialog('close'); },
                'Annulla': function() { $(this).dialog('close'); }
            },
            close: function() {
                $(this).dialog('destroy');
                $('#dialogShowWallRelation' + idContent).remove();
            }
        });
    }, 'html');
}

function unsubscribePostPanel(element, idWall) {
    $('.unsubscribeDialogPostPanel' + idWall).html('<div></div>');
    $('.unsubscribeDialogPostPanel' + idWall + ' div').dialog({
        resizable: false,
        bgiframe: true,
        autoOpen: true,
        modal: true,
        title: 'Sei sicuro di volerti disiscrivere?',
        width: 350,
        height: 0,
        buttons: {
            'Annulla': function() {
                $(this).dialog('close');
            },
            'Disiscriviti': function() {
                $.post('/Wall/unsuscribeWall', { idWall: idWall }, function(data) { }, 'html');
                element.hide();
                $(this).dialog('close');
            }
        },
        close: function() {
            $(this).remove();
            $(this).dialog('destroy');
        }
    });
}

function subscribeWall(idWall, element) {
    $.post('/Wall/wallSubscription', { idWall: idWall }, function(data) { element.remove(); $('.subscribeButton' + idWall).show() }, 'html');
}

function selectFriendForShareStatus(idStatus) {
    $.post('/Friend/getAllFriends', { username: $.cookie('usernameActive') }, function(data) {
        tempListFriend = new Array();
        $('#dialogShowFriendArea').html(data);
        $('#friendDialog-SelectAll-checkBox').parent().remove();
        $('#dialogShowFriend').dialog({
            bgiframe: true,
            autoOpen: true,
            height: 500,
            width: 550,
            modal: true,
            resizable: false,
            buttons: {
                'Conferma': function() {
                    var stringArray = new Array();
                    var usernameFriend = "";
                    $.each(tempListFriend, function(i, v) {
                        usernameFriend = v.username;
                    });
                    shareOnOtherWall("-1", idStatus, usernameFriend);
                    $(this).dialog('close');
                },
                'Annulla': function() { $(this).dialog('close'); }
            },
            close: function() {
                selectedFriend = null;
                $(this).dialog('destroy');
            }
        });
    }, 'html');
}

function shareOnOtherWall(idGroup, idStatus, username) {
    $.post('/Wall/getGroupContentDialog', { idGroup: idGroup, username: username }, function(data) {
        $('#dialogShowGroup' + idStatus).html(data);
        $('#dialogShowGroup' + idStatus).dialog({
            bgiframe: true,
            autoOpen: true,
            modal: true,
            width: 850,
            resizable: false,
            buttons: {
                conferma: function() {
                    $.post('/Wall/copyStatus', { idStatus: idStatus, idWall: idWallSelected }, function(data) { }, 'json');
                    $('#dialogShowGroup' + idStatus).append("<div class='resultShare' title='Condivisione messaggio' style='display:none'>Messaggio copiato con successo.</div>")
                    var dialogToDestroy = $(this);
                    $('#dialogShowGroup' + idStatus).find('.resultShare').dialog({
                        bgiframe: true,
                        autoOpen: true,
                        modal: true,
                        width: 450,
                        resizable: false,
                        buttons: {
                            'Vai alla discussione': function() {
                                openTabWallIndex(idWallSelected, nameWallSelected);
                                $(this).dialog('destroy');
                                dialogToDestroy.dialog('destroy');
                                $('#dialogShowGroup' + idStatus + ' div').remove();
                            },
                            'Condividi Ancora': function() {
                                $(this).dialog('destroy');
                            },
                            'Esci': function() {
                                $(this).dialog('destroy');
                                dialogToDestroy.dialog('destroy');
                                $('#dialogShowGroup' + idStatus + ' div').remove();
                            }
                        },
                        close: function() {
                            $(this).dialog('destroy');
                        }
                    })

                },
                annulla: function() {
                    $(this).dialog('destroy');
                    $('#dialogShowGroup' + idStatus + ' div').remove();
                }
            },
            close: function() {
                $(this).dialog('destroy');
                $('#dialogShowGroup' + idStatus + ' div').remove();
            }
        });
    }, 'html');
}

function hidePreviewStatus(elementTohide, elementIconButton) {
    if (elementTohide.is(':hidden')) {
        elementTohide.show();
        elementIconButton.switchClass('ui-icon-plusthick', 'ui-icon-closethick', 0);
    } else {
        elementTohide.hide();
        elementIconButton.switchClass('ui-icon-closethick', 'ui-icon-plusthick', 0);
    }
}

function responsePost(idStatus, idWall, idContent) {
    $('.responsePostArea' + idWall).html($("#content" + idContent).html());
    $('.divResponsePostArea' + idWall).show();
    $('.divResponsePostArea' + idWall + '-idStatus').html(idStatus);
    $.scrollTo('#tabWall', 800);
    $('#t1' + idWall).focus()
}

function getEvet(idEvent) {
    $.post('/Calendar/getEvent', { idEvent: idEvent }, function(data) { $('#event' + idEvent).append(data); }, 'html');
}

function showContentGroup(idGroup) {
    $.post('/Wall/getGroupContent', { idGroup: idGroup }, function(data) { var idz = $('.ui-tabs-selected a').attr('href'); $(idz).html(data); }, 'html');
}



function extendAreaStatusInfoWall(textArea, text, div) {
    if (textArea.text() == text) {
        textArea.text('');
    }
    div.css({ 'height': '80px', 'padding': '6px 12px 10px 5px' });
    textArea.css({ 'height': '80px' });
}

function setILikeITResume(id, iLike, idStatus, idWall) {
    var idEl = id;
    var typeBool = iLike;
    $.post('/Wall/setILikeItWall', { idContent: id, iLike: iLike, idWall: idWall }, function(data) {
        if (data != "" && data != null) {
            $('#wall1' + idWallToWrite + ' #statusArea').html('<img class="post-loader-gif" style="margin:80px 0px 80px 240px" src="../../Content/ajax-loader.gif" />');
            $.post('/Wall/writeOnWallILikeIt', { idWall: idWall, idCitation: idStatus, selectedTextCitation: -1, iLikeIt: iLike, idContent: id }, function(data) {
                $.post('/Wall/resumeStatus', { idWall: idWallBase, numberPage: 0, text: true, photo: true, events: true, tagPhoto: true }, function(data) { $('#wall1' + idWallToWrite).html(data); }, 'html');
            }, "text");
        }
    }, 'text');
}

function setILikeITWall(id, iLike, idStatus, idContent, idWall) {
    var idEl = id;
    $.post('/Wall/setILikeItWall', { idContent: id, iLike: iLike, idWall: idWall }, function(data) {
        if (data != "" && data != null) {
            $('#wall1' + idWallToWrite + ' #statusArea').prepend('<img class="post-loader-gif" style="margin:80px 0px 80px 240px" src="../../Content/ajax-loader.gif" />');
            $.post('/Wall/writeOnWallILikeIt', { idWall: idWallToWrite, idCitation: idStatus, selectedTextCitation: -1, iLikeIt: iLike, idContent: idContent }, function(data) {
                $(".post-loader-gif").remove();
                $('#wall1' + idWallToWrite + ' #statusArea').prepend(data);
            }, "text");
            if (iLike == true) {
                $('#good' + idEl).html(data);
            } else {
                $('#bad' + idEl).html(data);
            }
        }
    }, 'text');
}

function setILikeIT(id, iLike, idStatus, idContent) {
    var idEl = id;
    $.post('/Wall/setILikeIt', { idContent: id, iLike: iLike }, function(data) {
        if (data != "" && data != null) {
            $('#wall1' + idWallToWrite + ' #statusArea').prepend('<img class="post-loader-gif" style="margin:80px 0px 80px 240px" src="../../Content/ajax-loader.gif" />');
            $.post('/Wall/writeOnWallILikeIt', { idWall: idWallToWrite, idCitation: idStatus, selectedTextCitation: -1, iLikeIt: iLike, idContent: idContent }, function(data) {
                $(".post-loader-gif").remove();
                $('#wall1' + idWallToWrite + ' #statusArea').prepend(data);
            }, "text");
            if (iLike == true) {
                $('#good' + idEl).html(data);
            } else {
                $('#bad' + idEl).html(data);
            }
        }
    }, 'text');
}

function setILikeITContent(idContent, iLike) {
    $.post('/Wall/setILikeIt', { idContent: idContent, iLike: iLike }, function(data) {
        if (data != "" && data != null) {
            if (iLike == true) {
                $('#good' + idContent).html(data);
            } else {
                $('#bad' + idContent).html(data);
            }
        }
    }, 'text');
}

function openDialogModifyWall(idWall, elementDialog, imgElement, nameElementDiv) {
    $.post('/Wall/getDialogEditWall', { idWall: idWall }, function(data) {
        elementDialog.html(data);
        $('.dialogEditWall').dialog({
            bgiframe: true,
            autoOpen: true,
            modal: true,
            buttons: {
                'Salva': function() {
                    nameElementDiv.html($('.dialogEditWall-nameWall').val());
                    $('.dialogEditWall-nameWall-idLogo img').css({ 'height': '46px', 'width': '46px' });
                    imgElement.parent().html($('.dialogEditWall-nameWall-idLogo img'));
                    $.post('/Wall/editWall', { idWall: idWall, nameWall: $('.dialogEditWall-nameWall').val(), idLogo: $('.dialogEditWall-nameWall-idLogo div:last').html() }, function(info) {
                    }, 'json');
                    $('.dialogEditWall').remove(); $(this).dialog('destroy');
                },
                'annulla': function() { $('.dialogEditWall').remove(); $(this).dialog('destroy'); }
            },
            close: function() {
                $('.dialogEditWall').remove(); $(this).dialog('destroy');
            }
        });
    }, 'html');
}

function openDialogModifyGroup(idGroup, elementDialog, imgElement, nameElementDiv) {
    $.post('/Wall/getDialogEditGroup', { idGroup: idGroup }, function(data) {
        elementDialog.html(data);
        $('.dialogEditGroup').dialog({
            bgiframe: true,
            autoOpen: true,
            modal: true,
            buttons: {
                'Salva': function() {
                    nameElementDiv.html($('.dialogEditGroup-nameGroup').val());
                    $('.dialogEditGroup-nameGroup-idLogo img').css({ 'height': '46px', 'width': '46px' });
                    imgElement.parent().html($('.dialogEditGroup-nameGroup-idLogo img'));
                    $.post('/Wall/editGroup', { idGroup: idGroup, nameGroup: $('.dialogEditGroup-nameGroup').val(), idLogo: $('.dialogEditGroup-nameGroup-idLogo div:last').html() }, function(info) {
                    }, 'json');
                    $('.dialogEditGroup').remove(); $(this).dialog('destroy');
                },
                'annulla': function() { $('.dialogEditGroup').remove(); $(this).dialog('destroy'); }
            },
            close: function() {
                $('.dialogEditGroup').remove(); $(this).dialog('destroy');
            }
        });
    }, 'html');
}

function expandEvent(idEvent) {
    $.post('/Calendar/getEvent', { idEvent: idEvent }, function(data) { var idz = $('.ui-tabs-selected a').attr('href'); $(idz).html(data); }, 'html');
}

function changeWallPerm(idWall, inheritPerm, elementDialog, elementDialogExtern) {
    var wallModify = new Array();
    $.each($("#adminWall-perm-wall-modify .clickCheckBox"), function(i, v) {
        wallModify.push($(v).is(":checked"));
    });
    var wallRead = new Array();
    $.each($("#adminWall-perm-wall-read .clickCheckBox"), function(i, v) {
        wallRead.push($(v).is(":checked"));
    });
    var wallWrite = new Array();
    $.each($("#adminWall-perm-wall-write .clickCheckBox"), function(i, v) {
        wallWrite.push($(v).is(":checked"));
    });
    var admins = new Array();
    $.each($('.usernameSelectDialog'), function(i, v) {
        admins.push($(v).text());
    });
    var excluded = new Array();
    $.each($('.usernameExceptionWallSelectDialog'), function(i, v) {
        excluded.push($(v).text());
    });
    jQuery.ajaxSettings.traditional = true;
    $.post('/Wall/changePermWall', { idWall: idWall, admins: admins, pAM: wallModify[0], pFM: wallModify[1], pNM: wallModify[2], pAR: wallRead[0], pFR: wallRead[1], pNR: wallRead[2], pAW: wallWrite[0], pFW: wallWrite[1], pNW: wallWrite[2], inheritPerm: inheritPerm, userExcluded: excluded }, function(data) {
        elementDialog.dialog('destroy');
        $("#dialogWallPermission div").remove();
        elementDialogExtern.dialog('destroy');
    }, "json");
}

function dialogPWPortlet(idWall) {
    $.post('/Wall/loadAdminWallPanel', { idWall: idWall }, function(data) {
        $("#dialogWallPermission").html(data);
        $("#dialogWallPermission").dialog({
            bgiframe: true,
            autoOpen: true,
            height: 400,
            width: 350,
            modal: true,
            buttons: {
                'Salva': function() {
                    var elementDialogExtern = $(this);
                    $("#dialogWallPermission-inherit").dialog({
                        bgiframe: true,
                        autoOpen: true,
                        modal: true,
                        buttons: {
                            'Si': function() {
                                changeWallPerm(idWall, true, $(this), elementDialogExtern);
                            },
                            'No': function() {
                                changeWallPerm(idWall, false, $(this), elementDialogExtern);
                            }
                        }
                    });
                },
                'annulla': function() { $("#dialogWallPermission div").remove(); $(this).dialog('destroy'); }
            }
        });
    }, 'html');
}

function changePermGroupDialog(idGroup) {
    $.post('/Wall/loadAdminGroupPanel', { idGroup: idGroup }, function(data) {
        $("#dialogGroupPermission").html(data);
        $("#dialogGroupPermission").dialog({
            bgiframe: true,
            autoOpen: true,
            height: 400,
            width: 350,
            modal: true,
            buttons: {
                'Salva': function() { sendUpdatePrivacyGroup(idGroup); $(this).dialog('close'); },
                'annulla': function() { $(this).dialog('close'); }
            },
            close: function() { $("#dialogGroupPermission div").remove(); }
        });
    }, 'html');
}

function sendUpdatePrivacyGroup(idGroup) {
    var wallModify = new Array();
    $.each($("#groupAdmin-perm-group-modify .clickCheckBox"), function(i, v) {
        wallModify.push($(v).is(":checked"));
    });
    var wallRead = new Array();
    $.each($("#groupAdmin-perm-group-read .clickCheckBox"), function(i, v) {
        wallRead.push($(v).is(":checked"));
    });
    var wallWrite = new Array();
    $.each($("#groupAdmin-perm-group-write .clickCheckBox"), function(i, v) {
        wallWrite.push($(v).is(":checked"));
    });
    var admins = new Array();
    $.each($('.usernameSelectDialog'), function(i, v) {
        admins.push($(v).text());
    });
    jQuery.ajaxSettings.traditional = true;
    $.post('/Wall/changePermGroup', { idGroup: idGroup, admins: admins, aW: wallWrite[0], fW: wallWrite[1], nW: wallWrite[2], aR: wallRead[0], fR: wallRead[1], nR: wallRead[2], aM: wallModify[0], fM: wallModify[1], nM: wallModify[2] }, function(data) {
        //TODO far tornare le immagini degli utenti diventati admin
        //$('#privacy' + idDivAdminAppend).append()
    }, 'json');
}

function modifyContentDialog(idContent) {
    $('#textAreaModify').val($('#content' + idContent + ' div').html());
    $('#modifyContent').dialog('open');
}

function postFromInfoWallPreview(idWall, elementText) {
    $.post('/Wall/writeOnWall', { idWall: idWall, content: elementText.val(), idCitation: -1, selectedTextCitation: -1, idPhotoAllegato: -1 }, function(data) {
    }, "text");
}

function postContent(idWallToWrite) {
    var boxval = $("#t1" + idWallToWrite).val();
    var idPhoto = $(".postPanel-IncludePhoto" + idWallToWrite + " div").text();
    if (idPhoto == null || idPhoto == "") {
        idPhoto = -1;
    }
    var dataString = 'content=' + boxval;

    var idCitation = -1;
    if ($('.divResponsePostArea' + idWallToWrite).is(':visible')) {
        idCitation = $('.divResponsePostArea' + idWallToWrite + '-idStatus').text();
    }
    var testo = "gip";
    if (window.getSelection) {
        testo = window.getSelection();
    }
    else if (document.getSelection) {
        testo = document.getSelection();
    }
    else if (document.selection) {
        testo = document.selection.createRange().text;
    }
    testo = testo.toString();
    if (boxval == '' && idPhoto == -1) {
        alert("Inserire del testo o una foto");
    } else {
        // $("#flash").show("slide", { direction: "up" }, 500);
        //var cookieTabs = $.cookie("pageNumber");
        //var idWallToWrite = cookieTabs.split(';')[0].split('#')[0].substr(1);
        $('#wall1' + idWallToWrite + ' #statusArea').prepend('<img class="post-loader-gif" style="margin:80px 0px 80px 240px" src="../../Content/ajax-loader.gif" />');
        $.post('/Wall/writeOnWall', { idWall: idWallToWrite, content: boxval, idCitation: idCitation, selectedTextCitation: -1, idPhotoAllegato: idPhoto }, function(data) {
            $(".post-loader-gif").remove();
            $('#wall1' + idWallToWrite + ' #statusArea').prepend(data);
        }, "text");
    }
    return false;
}

var idW = new Array(new Array());
var tabOpen = new Array();
var indexTabOpen = 0;
var indexToRemove = 0;
var dataGroups;
var lastIdGroupSelection = -1;
var tempIdTab;
var lastGSelection = -1;

function setCookieOpenTab() {
    $.cookie("tabsWall", "", { expires: 14, path: "/" });
}

function getOpenTab() {
    if ($.cookie("tabsWall") != null) {
        var cookieTabs = $.cookie("tabsWall").split(';');
        for (var i = 0; i < 999; i++) {
            if (cookieTabs[i] == null) {
                break;
            }
            idW[i] = cookieTabs[i].split("#");
        }
    }
}

var indexTabAdd = 0;
$(document).ready(function() {
    //nel Page Number viene memorizzato il nel wall attuale a che pagina si e' arrivati e in un eventuale wal precedente
    $.cookie("pageNumber", "", { expires: 14, path: "/" });

    /* $('#tabWall').tabs({
    load: function(event, ui) {
    },
    tabTemplate: '<li class="tab"><span style="float:left"><a href="#{href}"><span style="float:left" >#{label}</span></a></span><span style="float:left;margin-left:5px;margin-top:6px;" class="ui-icon ui-icon-closethick" onclick="elimina($(this))"></span></li>',
    add: function(event, ui) {
    $(ui.tab).attr('id', tempIdTab);
    indexTabAdd = ui.index;
    tabOpen[indexTabOpen] = ui.index;
    alert('ciao');
    $("#tabWall").tabs('select', '#' + ui.panel.id);
    indexTabOpen++;
    }
    });*/

    getOpenTab();
    if (idW != null) {
        for (var i = 0; i < idW.length; i++) {
            if (idW[i][0] == null) {
                break;
            }
            if (idW[i][0].search('W') != -1)
                aggiungi("/Wall/getStatusWallTabParam?idWall=" + idW[i][0].substr(1), idW[i][0], idW[i][2]);
            if (idW[i][0].search('C') != -1)
                aggiungi("/Wall/getStatusWallTabParam?idWall=" + idW[i][0].substr(1), idW[i][0], idW[i][2]);
        }
    }

    $("#tabWall").tabs().find(".ui-tabs-nav").sortable({ axis: 'x' });

    $('#tabWall').bind('tabsremove', function(event, ui) {
    });

    $('#tabWall').bind('tabsselect', function(event, ui) {
        //$(ui.tab).addClass('selectedClass', 0);
        indexToRemove = ui.index;
        $.cookie("selectedTab", $(ui.tab).attr('id'), { expires: 20, path: "/" });
        var pageNumber;

        if ($.cookie("pageNumber") != null) {
            pageNumber = $.cookie("pageNumber").split(';');
        }

        $.cookie("pageNumber", $(ui.tab).attr('id') + "#" + "0;", { expires: 14, path: "/" });
        $("#postAdminPanel").remove();
        if ($.cookie("selectedTab") != "") {
            $("#wallAdminRightArea").show();
        }
        else {
            $("#wallAdminRightArea").hide();
        }
    });
});

function elimina(element) {
    //Attenzione che lastGSelection classe state hover potrebbe essere riusata dataGroups qualche parte per sbaglio element creare casino
    var idHoverTab = $('.tab.ui-state-hover a').attr('id');
    var elToRemove = $('.tab.ui-state-hover');
    //$('#search').focus();
    $('#tabWall').tabs('select', 0);
    elToRemove.remove();
    var cookieTabs = $.cookie("tabsWall");
    var strRemove = $.cookie("tabsWall").split(';');
    var newStrForcookie = "";

    for (var i = 0; ; i++) {
        if (strRemove[i].indexOf(idHoverTab) != -1) {
            if (indexTabOpen == 1) {
                newStrForcookie = cookieTabs.replace(strRemove[i], "");
            } else {
                if (i == 0) {
                    newStrForcookie = cookieTabs.replace(strRemove[i] + ';', "");
                }
                else {
                    newStrForcookie = cookieTabs.replace(';' + strRemove[i], "");
                }
            }
            break;
        }
        if (i > 100) {
            break;
        }
    }
    if (newStrForcookie == "") {
        $.cookie("tabsWall", newStrForcookie, { expires: -1, path: "/" });
    }
    else {
        $.cookie("tabsWall", newStrForcookie, { expires: 14, path: "/" });
    }
    indexTabOpen--;
}

function aggiungi(url, id, nameTab) {
    var cookieTabs = $.cookie("tabsWall");
    if (cookieTabs == null || cookieTabs == "") {
        cookieTabs = "";
        tempIdTab = id;
        $("#tabWall").tabs("add", url, nameTab);

        //TODO bug su index tab add quando viene rimossa una tab l'index tab add non va bene come punto di rifermineto
        cookieTabs += id + '#' + indexTabAdd + '#' + nameTab;
        $.cookie("tabsWall", cookieTabs, { expires: 14, path: "/" });
        getOpenTab();
    }
    else {
        if (cookieTabs.search((id + '#')) == -1) {
            tempIdTab = id;
            $("#tabWall").tabs("add", url, nameTab);
            cookieTabs += ';' + id + '#' + indexTabAdd + '#' + nameTab;
            $.cookie("tabsWall", cookieTabs, { expires: 14, path: "/" });
            getOpenTab();
        }
        else {
            for (var i = 0; i < 999; i++) {
                if (tabOpen[i] == null) {
                    break;
                }
                var tabs = cookieTabs.split(';');

                if (tabOpen[i] == (tabs[i + 1].split('#'))[1]) {
                    var util = cookieTabs.split(';');
                    for (var j = 0; j < 999; i++) {
                        if (util[j] == null) {
                            break;
                        }
                        if (util[j].search(('id' + '#') != -1)) {
                            $('#tabWall').tabs('select', j + 1);
                            break;
                        }
                    }
                    return false;
                }
            }
            tempIdTab = id;
            $("#tabWall").tabs("add", url, nameTab);
        }
    }
}

function deleteWallOpenDialog(idWall) {
    $.post('/Wall/deleteWallDialogContent', { idWall: idWall }, function(data) {
        $('#deleteWallDialogContent').html(data);
        $('#deleteWallDialog').dialog({
            bgiframe: true,
            autoOpen: true,
            modal: true,
            buttons: {
                'Continua': function() { $.post('/Wall/deleteWall', { idWall: $.cookie('selectedTab').substr(1) }, function(data) { elimina(); }, 'html'); $(this).dialog('close'); },
                'Annulla': function() { $(this).dialog('close'); }
            },
            close: function(event, ui) { }
        });
    }, 'html');
}

function deleteGroupDialog(idGroup, element) {
    var idGroupToDelete = idGroup;
    var elementPortlet = element;
    $('#deleteGroupDialog').dialog({
        bgiframe: true,
        autoOpen: true,
        modal: true,
        buttons: {
            'Continua': function() { $.post('/Wall/deleteGroup', { idGroup: idGroupToDelete }, function(data) { elementPortlet.remove(); }, 'html'); $(this).dialog('close'); },
            'Annulla': function() { $(this).dialog('close'); }
        },
        close: function(event, ui) { }
    });
}

function deleteWallPortletOpenDialog(idWallToDelete, element) {
    var idWallDelete = idWallToDelete;
    var elementPortlet = element;
    $.post('/Wall/deleteWallDialogContent', { idWall: idWallToDelete }, function(data) {
        $('#deleteWallDialogContent').html(data);
        $('#deleteWallDialog').dialog({
            bgiframe: true,
            autoOpen: true,
            modal: true,
            width: 400,
            buttons: {
                'Continua': function() { $.post('/Wall/deleteWall', { idWall: idWallDelete }, function(data) { elementPortlet.remove(); }, 'html'); $(this).dialog('close'); },
                'Annulla': function() { $(this).dialog('destroy'); }
            },
            close: function(event, ui) { }
        });
    }, 'html');
}

function oldStatus() {
    var pageNumber = $.cookie("pageNumber").split(';');
    var separePageEid = pageNumber[0].split('#');
    var idW = separePageEid[0].substr(1);
    var pageVisited = separePageEid[1];
    if ($('#showTypeText').is(':checked')) {
        typeText = true;
    } else {
        typeText = false;
    }
    if ($('#showTypePhoto').is(':checked')) {
        typePhoto = true;
    } else {
        typePhoto = false;
    }
    if ($('#showTypeEvent').is(':checked')) {
        typeEvent = true;
    }
    else {
        typeEvent = false;
    }
    if ($('#showTypeTagPhoto').is(':checked')) {
        typeTagPhoto = true;
    }
    else {
        typeTagPhoto = false;
    }
    $.cookie("pageNumber", separePageEid[0] + "#" + (Number(separePageEid[1]) + 1) + ";" + pageNumber[1], { expires: 14, path: "/" });
    $.post('/Wall/getStatusWall', { idWall: idW, numberPage: Number(separePageEid[1]) + 1, text: typeText, photo: typePhoto, events: typeEvent, tagPhoto: typeTagPhoto }, function(data) { $('#wall1').html(data); }, 'html');
}

function recentStatus() {
    var pageNumber = $.cookie("pageNumber").split(';');
    var separePageEid = pageNumber[0].split('#');
    var idW = separePageEid[0].substr(1);
    var pageVisited = separePageEid[1];
    var typeText;
    var typePhoto;
    var typeEvent;
    if ($('#showTypeText').is(':checked')) {
        typeText = true;
    } else {
        typeText = false;
    }
    if ($('#showTypePhoto').is(':checked')) {
        typePhoto = true;
    } else {
        typePhoto = false;
    }
    if ($('#showTypeEvent').is(':checked')) {
        typeEvent = true;
    }
    else {
        typeEvent = false;
    }
    if (Number(separePageEid[1]) > 0) {
        $.cookie("pageNumber", separePageEid[0] + "#" + (Number(separePageEid[1]) - 1) + ";" + pageNumber[1], { expires: 14, path: "/" });
        $.post('/Wall/getStatusWall', { idWall: idW, numberPage: Number(separePageEid[1]) - 1, text: typeText, photo: typePhoto, events: typeEvent }, function(data) { $('#wall1').html(data); }, 'html');
    }
}

function changePageStatus(pageNumber, idW) {
    var typeText;
    var typePhoto;
    var typeEvent;
    var typeTagPhoto;
    pageSelected = pageNumber;
    if ($('.showTypeText' + idW).is(':checked')) {
        typeText = true;
    } else {
        typeText = false;
    }
    if ($('.showTypePhoto' + idW).is(':checked')) {
        typePhoto = true;
    } else {
        typePhoto = false;
    }
    if ($('.showTypeEvent' + idW).is(':checked')) {
        typeEvent = true;
    }
    else {
        typeEvent = false;
    }
    if ($('.showTypeTagPhoto' + idW).is(':checked')) {
        typeTagPhoto = true;
    }
    else {
        typeTagPhoto = false;
    }
    $.post('/Wall/getStatusWall', { idWall: idW, numberPage: pageNumber, text: typeText, photo: typePhoto, events: typeEvent, tagPhoto: typeTagPhoto }, function(data) { $('#wall1' + idW).html(data); }, 'html');
}

function loadStatus(indei, user) {
    $("insertStatus").show();
    var inde = indei;
    $('#wallContainer').html("");
    $.post("/Wall/getStatusWall", { idWall: idW[inde - 1][0].substr(1), numberPage: '0' }, function(data) { $("#wallContainer").html(data); }, "html");
}

function postNewStatus() {
    $.post("/Wall/writeOnWall", { idWall: wallActive, usernameTarget: userTarget, content: $('#textAreaStatus').val() }, function(data) { $("#insertStatus").load(data); }, "text");
}


function showPermission() {
    $.post('/Wall/loadDefaultPermissionWall', {}, function(data) { $('.permissionAreaPanel').html(data); $('.permissionAreaPanel').show('slide', {}, '1000'); }, 'html');

}

function selectGroups(idDialog) {
    $.post('/Wall/getGroupsFromBase', {}, function(data) { $('.areaSelectGroup-result').html(data); $('.areaSelectGroup-result').show('slide', {}, 1000); }, 'html');
}

function associateWall(idGroupInner, idContent) {
    tempListFriend = new Array();
    $.post('/Wall/getDialogNewWall', {}, function(data) {
        $('#dialogNewWall-externDiv').html(data)
        $('#selecetdUserToAdmin').html("");
        $('#permissionAreaPanel').html("");
        var idGroupInnerSave = idGroupInner;
        $('.dialogNewWall').dialog({
            bgiframe: true,
            autoOpen: true,
            width: 500,
            height: 450,
            modal: true,
            buttons: {
                'Crea un Wall': function() { associateNewWall(idGroupInnerSave, $(this), idContent); },
                'Annulla': function() {
                    tempListFriend = new Array();
                    $(this).dialog('destroy');
                    $('.dialogNewWall').remove();

                }
            },
            close: function() {
                tempListFriend = new Array();
                $(this).dialog('destroy');
                $('.dialogNewWall').remove();
            }
        });
        $('#TextGroup').val("");
    }, 'html');
}

function associateNewWall(idGroupInner, element, idContent) {

    var stringArray = new Array();
    $.each(tempListFriend, function(i, v) {
        stringArray.push(v.username);
    });

    var wallModify = new Array();
    $.each($("#adminWall-perm-wall-modify .clickCheckBox"), function(i, v) {
        wallModify.push($(v).is(":checked"));
    });
    var wallRead = new Array();
    $.each($("#adminWall-perm-wall-read .clickCheckBox"), function(i, v) {
        wallRead.push($(v).is(":checked"));
    });
    var wallWrite = new Array();
    $.each($("#adminWall-perm-wall-write .clickCheckBox"), function(i, v) {
        wallWrite.push($(v).is(":checked"));
    });
    var admins = new Array();
    $.each($('.usernameSelectDialog'), function(i, v) {
        admins.push($(v).text());
    });
    var idPhoto = $('.idPhotoLogoWall div:last').text();
    jQuery.ajaxSettings.traditional = true;
    if (wallModify.length == 0) {
        $.post('/Wall/associateNewWallDefault', { name: $('.dialogNewWall-nameWall').val(), idPhoto: idPhoto, idGroup: idGroupInner, idContent: idContent }, function(data) {
            tempListFriend = new Array();
            element.dialog('destroy');
            $('.dialogNewWall').remove();
        }, 'json');
    } else {
        $.post('/Wall/associateNewWall', { name: $('.dialogNewWall-nameWall').val(), idGroup: idGroupInner, admins: admins, aW: wallWrite[0], fW: wallWrite[1], nW: wallWrite[2], aR: wallRead[0], fR: wallRead[1], nR: wallRead[2], aM: wallModify[0], fM: wallModify[1], nM: wallModify[2], idLogo: idPhoto }, function(data) {
            tempListFriend = new Array();
            element.dialog('destroy');
            $('.dialogNewWall').remove();
        }, 'json');
    }
}

function newWall(idGroupInner) {
    tempListFriend = new Array();
    $.post('/Wall/getDialogNewWall', {}, function(data) {
        $('#dialogNewWall-externDiv').html(data)
        $('#selecetdUserToAdmin').html("");
        $('#permissionAreaPanel').html("");
        var idGroupInnerSave = idGroupInner;
        $('.dialogNewWall').dialog({
            bgiframe: true,
            autoOpen: true,
            width: 500,
            height: 450,
            modal: true,
            buttons: {
                'Crea un Wall': function() { createNewWall(idGroupInnerSave, $(this)); },
                'Annulla': function() {
                    tempListFriend = new Array();
                    $(this).dialog('destroy');
                    $('.dialogNewWall').remove();

                }
            },
            close: function() {
                tempListFriend = new Array();
                $(this).dialog('destroy');
                $('.dialogNewWall').remove();
            }
        });
        $('#TextGroup').val("");
    }, 'html');
}

function createNewWall(idGroupInner, element) {

    if (idGroupInner == "-1") {
        idGroupInner = lastGSelection;
    }
    var stringArray = new Array();
    $.each(tempListFriend, function(i, v) {
        stringArray.push(v.username);
    });

    var wallModify = new Array();
    $.each($("#adminWall-perm-wall-modify .clickCheckBox"), function(i, v) {
        wallModify.push($(v).is(":checked"));
    });
    var wallRead = new Array();
    $.each($("#adminWall-perm-wall-read .clickCheckBox"), function(i, v) {
        wallRead.push($(v).is(":checked"));
    });
    var wallWrite = new Array();
    $.each($("#adminWall-perm-wall-write .clickCheckBox"), function(i, v) {
        wallWrite.push($(v).is(":checked"));
    });
    var admins = new Array();
    $.each($('.usernameSelectDialog'), function(i, v) {
        admins.push($(v).text());
    });
    var idPhoto = $('.idPhotoLogoWall div:last').text();
    jQuery.ajaxSettings.traditional = true;
    if (wallModify.length == 0) {
        $.post('/Wall/setNewWallDefault', { name: $('.dialogNewWall-nameWall').val(), idPhoto: idPhoto, idGroup: idGroupInner }, function(data) {
            $.post('/Wall/makeAnInfoWall', { idWall: data.idWall }, function(result) {
                var removeInfo = 0;
                $.each($('.portlet-wall-container-wallDiv'), function(i, v) {
                    removeInfo++;
                });
                if (removeInfo >= 4) {
                    $('.portlet-wall-container-wallDiv:last').remove();
                    $('.portlet-wall-container-wallDiv:last').parent().prepend(result);
                } else {
                    $('.portlet-wall-container-mainDiv:last').append(result);
                }
            }, 'html');
            tempListFriend = new Array();
            element.dialog('destroy');
            $('.dialogNewWall').remove();
        }, 'json');
    } else {
        $.post('/Wall/setNewWall', { name: $('.dialogNewWall-nameWall').val(), idGroup: idGroupInner, admins: admins, aW: wallWrite[0], fW: wallWrite[1], nW: wallWrite[2], aR: wallRead[0], fR: wallRead[1], nR: wallRead[2], aM: wallModify[0], fM: wallModify[1], nM: wallModify[2], idLogo: idPhoto }, function(data) {
            $.post('/Wall/makeAnInfoWall', { idWall: data.idWall }, function(result) {
                var removeInfo = 0;
                $.each($('.portlet-wall-container-wallDiv'), function(i, v) {
                    removeInfo++;
                });
                if (removeInfo >= 4) {
                    $('.portlet-wall-container-wallDiv:last').remove();
                    $('.portlet-wall-container-wallDiv:last').parent().prepend(result);
                } else {
                    $('.portlet-wall-container-mainDiv:last').append(result);
                }
            }, 'html');
            tempListFriend = new Array();
            element.dialog('destroy');
            $('.dialogNewWall').remove();
        }, 'json');
    }

    /*if (idGroupInner == "-1") {
    idGroupInner = lastGSelection;
    }
    var stringArray = new Array();
    $.each(tempListFriend, function(i, v) {
    alert(v.username);
    stringArray.push(v.username);
    });
    jQuery.ajaxSettings.traditional = true;
    $.post('/Wall/setNewWall', { name: $('#nameWall').val(), idGroup: idGroupInner, admins: stringArray, aW: $('#wA').is(':checked'), fW: $('#wF').is(':checked'), nW: $('#wN').is(':checked'), aR: $('#rA').is(':checked'), fR: $('#rF').is(':checked'), nR: $('#rN').is(':checked'), aM: $('#mA').is(':checked'), fM: $('#mF').is(':checked'), nM: $('#mN').is(':checked') }, function(data) { 
    //TODO creare il wall nella barra delle tab e selezionarlo
    }, "text");*/
}

var lastIdGroupSelect = -1;
var lastLetter = "";

function searchGroup(data) {
    // if ($('#resultGroup').is(':visible') && data.val() != lastLetter) {
    //   alert('ciao');
    // }
    //else {
    if ($('#resultGroup').is(':visible')) {
    } else {
        $('#resultGroup').css({ 'display': 'block' });
        if (data.val() != "")
            $.post('/Wall/searchGroups', { letters: data.val(), parent: lastIdGroupSelect }, function(data) {
                var elm = '<div id="resultSearchG">'
                $.each(data, function(index, d) {
                    elm += '<div id="' + d.value + '"onclick="pickGroup($(this))" title="' + d.caption + '">' + d.caption + '</div>';
                });
                elm += '</div>';
                $('#resultGroup').prepend(elm);
                $('#resultGroup').show("slide", { direction: "up" }, 400);
            }, "json");
        lastLetter = data.val();
        $('#resultSearchG div:first').focus();
    }
    //  }
}

function removeSearchSugget() {
    //   $('#resultSearchG').css({ 'display': 'none' });
    //$('#resultSearchG').remove();
}

function displaySearchSugget() {
    $('#resultSearchG').css({ 'display': 'block' });
    //$('#resultSearchG').remove();
}

function pickGroup(data) {
    $('#pathGroup').append('<span>' + data.attr('title') + '<span>');
    $('#resultSearchG').remove();
    $('#resultGroup').css({ 'display': 'none' });
    lastIdGroupSelect = data.attr('id');
}

var idGrandFather = -1;
var goBackParent = new Array();

function selectThisGroup(idGrandFParameters, parent, grName) {
    lastGSelection = parent;
    goBackParent.push(idGrandFParameters);
    $('.showSGroup-GroupDialog').append('<span class="showGrNameSelect"><span class="ui-icon ui-icon-arrowthick-1-e" style="float:left;"></span><span class="dialogSelectGroup-groupSelect" style="float:left;" name="' + lastGSelection + '">' + grName + '</span></span>');
    $.post('/Wall/getGroupsSimple', { user: $.cookie('userVisited'), idParent: parent }, function(data) { $('.showGroup').html(data); }, 'html');
}

function goBackSelectGroups() {
    $('.showGrNameSelect').last().remove();
    $.post('/Wall/getGroupsSimple', { user: $.cookie('userVisited'), idParent: goBackParent.pop() }, function(data) { $('.showGroup').html(data); }, 'html');
}

function showAdminSetup(element) {
    element.show('slow');
}

function openDialogNewGroup(idGroupInner) {
    tempListFriend = new Array();
    $.post('/Wall/getDialogNewGroup', {}, function(data) {
        $(".dialogNewGroup-externDiv").html(data);
        $('#selecetdUserToAdmin-GroupDialog').html("");
        $('#groupAdmin-permissionAreaPanel').html("");
        var idGroupInnerSave = idGroupInner;
        $(".dialogNewGroup").dialog({
            bgiframe: true,
            autoOpen: true,
            width: 500,
            height: 450,
            modal: true,
            buttons: {
                'Crea un Gruppo': function() { createNewGroup(idGroupInnerSave, $(this)); },
                'Annulla': function() { $(this).dialog('destroy'); $(".dialogNewGroup").remove(); }
            },
            close: function() {
                $(this).dialog('destroy');
                $(".dialogNewGroup").remove();
            }
        });
    }, 'html');
}

function showPermissionGroup() {
    $.post('/Wall/loadDefaultPermissionGroup', {}, function(data) { $('.groupAdmin-permissionAreaPanel').html(data); /*$("#dialogNewGroup").dialog("option", "height", $("#dialogNewGroup").dialog("option", "height") + 200);*/$('.groupAdmin-permissionAreaPanel').show('slide', {}, '1000'); }, 'html');
}

function createNewGroup(idGroupInnerSave, element) {
    if (idGroupInnerSave == "-1") {
        idGroupInnerSave = lastGSelection;
    }
    var wallModify = new Array();
    $.each($("#groupAdmin-perm-group-modify .clickCheckBox"), function(i, v) {
        wallModify.push($(v).is(":checked"));
    });
    var wallRead = new Array();
    $.each($("#groupAdmin-perm-group-read .clickCheckBox"), function(i, v) {
        wallRead.push($(v).is(":checked"));
    });
    var wallWrite = new Array();
    $.each($("#groupAdmin-perm-group-write .clickCheckBox"), function(i, v) {
        wallWrite.push($(v).is(":checked"));
    });
    var admins = new Array();
    $.each($('.usernameSelectDialog'), function(i, v) {
        admins.push($(v).text());
    });
    var idPhoto = $('.dialogNewGroup-idPhotoLogoGroup div:last').text();
    jQuery.ajaxSettings.traditional = true;
    if (wallModify.length == 0) {
        $.post('/Wall/setNewGroupDefault', { name: $('#nameGroup-GroupDialog').val(), idPhoto: idPhoto, admins: admins, idParentGroup: idGroupInnerSave }, function(data) {
            $.post('/Wall/makeAnInfoGroup', { idGroup: data.idGroup }, function(result) {
                var removeInfo = 0;
                $.each($('.portlet-group-container-groupDiv'), function(i, v) {
                    removeInfo++;
                });
                if (removeInfo >= 4) {
                    $('.portlet-group-container-groupDiv:last').remove();
                    $('.portlet-group-container-groupDiv:last').parent().prepend(result);
                } else {
                    $('.portlet-group-container-groupDiv:last').parent().prepend(result);
                }
            }, 'html');

            element.dialog('destroy');
            $(".dialogNewGroup").remove();
        }, 'json');
    }
    else {
        $.post('/Wall/newGroup', { idParent: idGroupInnerSave, nameNewGroup: $('#nameGroup-GroupDialog').val(), admins: admins, aW: wallWrite[0], fW: wallWrite[1], nW: wallWrite[2], aR: wallRead[0], fR: wallRead[1], nR: wallRead[2], aM: wallModify[0], fM: wallModify[1], nM: wallModify[2], idPhoto: idPhoto }, function(data) {
            $.post('/Wall/makeAnInfoGroup', { idGroup: data.idGroup }, function(result) {
                var removeInfo = 0;
                $.each($('.portlet-group-container-groupDiv'), function(i, v) {
                    removeInfo++;
                });
                if (removeInfo >= 4) {
                    $('.portlet-group-container-groupDiv:last').remove();
                    $('.portlet-group-container-groupDiv:last').parent().prepend(result);
                } else {
                    $('.portlet-group-container-groupDiv:last').parent().prepend(result);
                }
            }, 'html');

            element.dialog('destroy');
            $(".dialogNewGroup").remove();
        }, 'json');
    }
}
