var dashboard = {
    currentCourse:{},
    currentUser:{},
    userProfile:{},
    employeeInformation:{},
    currentOrganization:{},
    employeeList:{},
    organizationRoles:{},
    organizationAreas:{},
    employeeAutoCompleteList:{},
    usersListAux:{},
    colaboratorList:{},
    employeesByAreaList:{},
    employeesByRolList:{},
    employeeRequestList:[],
    needVersion:{},
    currentVersionList:{},
    organizationVersions:{},
    currentVersion:{},
    currentEmployeeStatus:"all",
    isOnlyEmployee:0,
    rowIdListAux:[],
    courseIdListAux:[],
    idECListAux:[],
    whiteLabelFolder:"default",
    loadOrganization:function(){
        showGenericLoading();
        $.when(profile.loadCurrentUser(),organization.loadOrganizationAreas(),organization.loadOrganizationRoles()).then(function(){
            hideGenericLoading();
        },function(){
            hideGenericLoading();
        
            redirectToGenericError("organization.loadOrganization()",null,false);
        });
    },
    getOrgAreas:function(param){
        return requestService(PATH_SERVICE_GET_ALL_ORGANIZATION_AREAS(), param, "GET", true,
        function(data) {
            hideGenericLoading();
        }, function() {
            return false;
        });
    },
    loadOrganizationAreas : function() {
        var param={};
        param.organizationId=organization.currentOrganization.organizationId;
        showGenericLoading();
        $.when(organization.getOrgAreas(param)).then(function(data){
            hideGenericLoading();
            organization.organizationAreas=data.area;
        },function(){
            redirectToGenericError("organization.loadOrganizationAreas()","We are sorry, an error occurred charging organization structure.",true);
        });
    },
    getOrgRoles:function(param){
        return requestService(PATH_SERVICE_GET_ALL_ORGANIZATION_ROL(), param, "GET", true,
        function(data) {
        }, function() {
            return false;
        });
    },
    loadOrganizationRoles: function() {
        var param={};
        param.organizationId=organization.currentOrganization.organizationId;
        showGenericLoading();
        $.when(organization.getOrgRoles(param)).then(function(data){
            hideGenericLoading();
            organization.organizationRoles=data.employeeRol;
        },function(){
            redirectToGenericError("organization.loadOrganizationRoles()","We are sorry, an error occurred charging roles.",false);
        });
    },
    loadEmployeeInformation:function(){
        return requestService(PATH_SERVICE_GET_EMPLOYEE_INFORMATION(), null, "GET", true,
        function(data) {
            organization.currentUser.employeeInformationList=data.employeeJSON;
        },
        function() {
        });
    },
    includeMenuEmployeeComponent:function(){
        var hash = generateHash();
        includeComponent("#menuOrg",PATH_HTML_ORG_EMPLOYEE_MENU()+"?organizationId="+organization.currentOrganization.organizationId,function(){
        });
    },
    includeCatalog2:function(organizationId){
        var hash = generateHash();
        organization.evtChageMenuTab('CATALOG');
    },
    includeDashboardComponents:function(param,callback){
        var hash = generateHash();
        includeComponent("#content",PATH_HTML_DASHBOARD()+"?option="+param,function(){
            if(callback!=null){
                callback();
            }else{
                dashboard.initDashboard(param);
            }
        });
    },
    includeCatalogComponent:function(){
        hideGenericLoading();
        var hash = generateHash();
        organization.cleanContent();
        includeComponent("#orgCatalog",PATH_HTML_ORG_CATALOG()+"?organizationId="+organization.currentOrganization.organizationId,function(){
            organization.setActiveStep('catalogTab');
            $("#orgCatalog").show();
        });
    },
    includeCatalogComponentUnPublish:function(){
        hideGenericLoading();
        var hash = generateHash();
        organization.cleanContent();
        includeComponent("#orgCatalog",PATH_HTML_ORG_CATALOG_UNPUBLISH()+"?organizationId="+organization.currentOrganization.organizationId,function(){
            organization.setActiveStep('catalogTab');
            $("#orgCatalog").show();
        });
    },
    evtSelectedCatalogStatus:function(statusSelected){
        var hash = generateHash();
        showGenericLoading();
        if(statusSelected==1){
            organization.includeCatalogComponent();
        }else{
            if(statusSelected==2){
                organization.includeCatalogComponentUnPublish();
            }
        }
    },
    includeCatalogEmployeeComponent:function(){
        organization.cleanContent();
        var hash = generateHash();
        includeComponent("#orgCatalog",PATH_HTML_ORG_CATALOG_EMPLOYEE()+"?organizationId="+organization.currentOrganization.organizationId,function(){
            organization.setActiveStep('catalogTab');
            $("#orgCatalog").show();
        });
    },
    getFinalVersion:function(){
        return requestService(PATH_SERVICE_GET_NEED_FINAL_VERSION(), null, "GET", true,
        function(result){
        });
    },
    includeNeedsComponent:function(){
        var hash = generateHash();
        showGenericLoading();
        $.when(organization.getFinalVersion()).then(function(result){
            hideGenericLoading();
            organization.currentVersionList=result.sourceNeedJSON;
            if(hash == currentHash){
            includeComponent("#orgNeeds",PATH_HTML_NEED_ADMIN(),function(){
                organization.setActiveStep('needsTab');
                organization.showNeedsEmployeeTable();
            });
        }
        },function(){
            if(hash == currentHash){
                redirectToGenericError("organization.includeNeedsComponent()","We are sorry, an error occurred charging needs.",false);
            }
        });
    },
    includeAddApprenticesComponent:function(courseId,organizationId){
        $("#orgCatalog").hide()
        includeComponent("#orgAddApprentices",PATH_HTML_ORG_ADDAPRENTICES()+"?courseId="+courseId+"&organizationId="+organizationId,function(){
        });
    },
    includeAddApprenticesSpecializationComponent:function(specializationId,organizationId){
        $("#orgCatalog").hide()
            includeComponent("#orgAddApprentices",PATH_HTML_ORG_ADDAPRENTICESSPECIALIZATION()+"?specializationId="+specializationId+"&organizationId="+organizationId,function(){
        });
    },
    includeMenuComponent:function(){
        var hash = generateHash();
        includeComponent("#menuOrg",PATH_HTML_ORG_MENU()+"?organizationId="+organization.currentOrganization.organizationId,function(){
        });
    },
    includeDefineStructure:function(){
        var hash = generateHash();
        organization.cleanSetUpContent();
        includeComponent("#defineStructure",PATH_HTML_ORG_DEFINE_STRUCTURE(),function(){
        });
    },
    includeSetUpPeople:function(callback){
        var hash = generateHash();
        organization.cleanContent();
        includeComponent("#orgSetUp",PATH_HTML_ORG_SET_UP(),function(){
            organization.evtChageMenuSetup('DEFINEPEOPLE');
            if(callback!=null){
                callback();
            }
        });
    },
    includeSetUpPeopleNeeds:function(callback){
        var hash = generateHash();
        organization.cleanContent();
        includeComponent("#orgSetUp",PATH_HTML_ORG_SET_UP(),function(){
            organization.evtChageMenuSetup('NEEDS');
            if(callback!=null){
                callback();
            }
        });
    },
    includeSetUpGeneric:function(callback){
        var hash = generateHash();
        organization.cleanContent();
        includeComponent("#orgSetUp",PATH_HTML_ORG_SET_UP(),function(){
            if(callback!=null){
                callback();
            }
        });
    },
    includeSetUpMetrics:function(callback){
        var hash = generateHash();
        organization.cleanContent();
        includeComponent("#orgSetUp",PATH_HTML_ORG_SET_UP(),function(){
            organization.evtChageMenuSetup('METRICS');
            if(callback!=null){
                callback();
            }
        });
    },
    includeSetUpCertificates:function(callback){
        var hash = generateHash();
        organization.cleanContent();
        includeComponent("#orgSetUp",PATH_HTML_ORGANIZATIONCERTIFICATES(),function(){
            organization.evtChageMenuSetup('CERTIFICATES');
            if(callback!=null){
                callback();
            }
        });
    },
    includeDefineRol:function(){
        var hash = generateHash();
        organization.cleanSetUpContent();
        includeComponent("#defineRol",PATH_HTML_DEFINE_ROL()+"?organizationId="+organization.currentOrganization.organizationId,function(){
        });
    },
    includeDefinePrivileges:function(){
        var hash = generateHash();
        organization.cleanSetUpContent();
        includeComponent("#definePrivileges",PATH_HTML_DEFINE_PRIVILEGES()+"?organizationId="+organization.currentOrganization.organizationId,function(){
        });
    },
    includeDefineInstructors:function(){
        var hash = generateHash();
        organization.cleanSetUpContent();
        includeComponent("#defineInstructors",PATH_HTML_DEFINE_INSTRUCTORS()+"?organizationId="+organization.currentOrganization.organizationId,function(){
        });
    },
    includeDefineSkins:function(){
        var hash = generateHash();
        showGenericLoading();
        organization.cleanSetUpContent();
        includeComponent("#defineSkins",PATH_HTML_DEFINE_SKINS(),function(){
            hideGenericLoading();
        });
    },
    includeDefineTemplates:function(){
        var hash = generateHash();
        showGenericLoading();
        organization.cleanSetUpContent();
        includeComponent("#defineTemplate",PATH_HTML_DEFINE_TEMPLATE(),function(){
            hideGenericLoading();
        });
    },
    includeDefineProcess:function(){
        var hash = generateHash();
        showGenericLoading();
        organization.cleanSetUpContent();
        includeComponent("#defineProcesses",PATH_HTML_DEFINE_PROCESS(),function(){
            hideGenericLoading();
        });
    },
    includeSetUpProcesses:function(callback){
        var hash = generateHash();
        organization.cleanContent();
        includeComponent("#orgSetUp",PATH_HTML_DEFINE_PROCESS(),function(){
            organization.evtChageMenuSetup('PROCESSES');
            if(callback!=null){
                callback();
            }
        });
    },
    includeSetUpResults:function(callback){
        var hash = generateHash();
        organization.cleanContent();
        includeComponent("#orgSetUp",PATH_HTML_DEFINE_RESULTS_PROCESS(),function(){
            organization.evtChageMenuSetup('RESULTS');
            if(callback!=null){
                callback();
            }
        });
    },
    includeDefineEdition:function(){
        var hash = generateHash();
        showGenericLoading();
        organization.cleanSetUpContent();
        includeComponent("#defineEditOrgPopup",PATH_JSP_EDIT_ORG()+"?organizationId="+organization.currentOrganization.organizationId,function(){
            hideGenericLoading();
        });
    },
    includeDefineCategories:function(){
        var hash = generateHash();
        showGenericLoading();
        organization.cleanSetUpContent();
        includeComponent("#defineCategories",PATH_JSP_CATEGORIES_ORG()+"?organizationId="+organization.currentOrganization.organizationId,function(){
            $("#formNewCategory #orgCategory").removeClass("error");
            hideGenericLoading();
        });
    },
    includeDefineContact:function(){
        var hash = generateHash();
        showGenericLoading();
        organization.cleanSetUpContent();
        includeComponent("#defineContact",PATH_JSP_ORGANIZATION_CONTACT(),function(){
            hideGenericLoading();
        });
    },
    includeDefineImages:function(){
        var hash = generateHash();
        organization.cleanSetUpContent();
        includeComponent("#defineImages",PATH_HTML_DEFINE_IMAGES(),function(){
        });
    },
    showPaymentOptions:function(){
        profile.hideLoginPopup();
        $("#payOptsOrgPopup").remove();
        $("#payOptsOrgPopupLink").remove();
        $("#content").append("
");
        $("#content").append("");
        excludeComponent("#payOptsOrgPopup");
        includeComponent("#payOptsOrgPopup",getContextPath()+'/money/payOptsOrganization.jsp?orgId='+organization.currentOrganization.organizationId,function(){
            showFancyPopup("#payOptsOrgPopupLink",function(){});
        });
    },
    includeAddApprenticesManageComponent:function(organizationId){
        $("#content").html("");
        includeComponent("#content",PATH_HTML_ORG_APRENTICESMANAGE()+"?organizationId="+organizationId,function(){
        });
    },
    includePeople:function(){
        organization.cleanSetUpContent();
        organization.showEmployeeTable();
    },
    includeOrganizationActualRole:function(organizationId){
        if(organization.currentOrganization.roleType==null){
            organization.includeMenuComponent(organization.currentOrganization.organizationId);
        }else if(organization.currentOrganization.roleType=="ADMIN"){
            organization.includeMenuComponent(organization.currentOrganization.organizationId);
        }else if(organization.currentOrganization.roleType=="EMPLOYEE"){
            organization.includeMenuEmployeeComponent(organization.currentOrganization.organizationId);
        }
    },
    includeRequestEmployee:function(){
        var hash = generateHash();
        includeComponent("#orgRequest",PATH_HTML_REQUEST_EMPLOYEE(),function(){
        });
    },
    includeOrganizationUsersReport:function(page,rows,statusReport,organizationId,areaFilter,rolFilter){
        var hash = generateHash();
        var orgId = organization.currentOrganization.organizationId;
        var rowsReport = rows;
        organization.includeEmmployeesTable();
        if(rows=='undefined' || rows==''){
            rowsReport=10;
        }
        organization.cleanSetUpContent();
        includeComponent("#orgRequest",PATH_HTML_ORGANIZATION_USERS_REPORT()+"?page="+page+"&rows="+rowsReport+"&status="+statusReport+"&areaFilter="+areaFilter+"&rolFilter="+rolFilter+"&organizationId="+orgId,function(){
            organization.setActiveStep('reportTab');
            organization.setActiveStep('managementTab');
        });
    },
    downloadProgressExcel:function(url){
        showMessage("The download of your file is getting ready. Please wait a moment...",52000);
        window.location.href = url;
    },
    includeRequestAdmin:function(numPage,itemsPerPages,statusValue){
        var hash = generateHash();
        var iPP = itemsPerPages;
        if(itemsPerPages=='undefined' || itemsPerPages==''){
            iPP=10;
        }
        organization.cleanSetUpContent();
        includeComponent("#orgRequest",PATH_HTML_REQUEST_ADMIN()+"?numPage="+numPage+"&itemsPerPages="+iPP+"&statusValue="+statusValue,function(){
            organization.setActiveStep('requestTab');
            organization.setActiveStep('managementTab');
        });
    },
    includeOrganizationAccount:function(){
        var hash = generateHash();
        showGenericLoading();
        organization.cleanSetUpContent();
        includeComponent("#account",PATH_JSP_ORGANIZATION_ACCOUNT()+"?organizationId="+organization.currentOrganization.organizationId,function(){
             hideGenericLoading();
        });
    },
    includeOrganizationMetrics:function(){
        var hash = generateHash();
        showGenericLoading();
        organization.cleanSetUpContent();
        includeComponent("#account",PATH_JSP_ORGANIZATION_METRICS()+"?organizationId="+organization.currentOrganization.organizationId,function(){
            hideGenericLoading();
        });
    },
    loadRoleType:function(roleType){
        organization.currentOrganization.roleType=roleType;
    },
    evtSendRoleType:function(){
        if($('#emp').is(":checked") || $('#adm').is(":checked") ){
            organization.includeOrganizationActualRole();
            $.fancybox.close();
        }else{
            $("#messageT").val("Debe elegir una opcion");
        }
    },
    deleteRole:function(param){
        return requestService(PATH_SERVICE_DELETE_ROL(), param, "GET", true,
        function(data) {
        },
        function() {
        });
    },
    evtDeleteRol:function(rolId){
        var param={};
        param.employeeRolId=rolId;
        showGenericSaving();
        $.when(organization.deleteRole(param)).then(function(data){
            hideGenericLoading();
            organization.loadOrganizationRoles();
            organization.evtChageMenuSetup('DEFINEROLES');
        },function(){
            redirectToGenericError("organization.evtDeleteRol("+rolId+")","We are sorry, an error occurred and failed to save your changes.",true);
        });
    },
    evtChageEmployeeTab:function(step){
        if(step=='CATALOG'){
            organization.includeCatalogComponent();
            organization.setActiveStep('catalogTab');
        }else if (step=='SETUP'){
            organization.setActiveStep('setupTab');
            organization.includeSetupEmployee();
        }else if (step=='REPORT'){
            organization.includeSetUpGeneric(function(){
                organization.setActiveStep('requestTab');
                organization.includeOrganizationUsersReport(page,rows,statusReport,organizationId,areaFilter,rolFilter);
            });
        }else if (step=='REQUEST'){
            organization.includeSetUpGeneric(function(){
                organization.setActiveStep('requestTab');
                organization.includeRequestEmployee();
            });
        }else if (step=='PLANNING'){
            organization.setActiveStep('planningTab');
            $.when(planning.loadEmployeePlan()).then(function(){
            if (typeof planning.planningEmployeeList[0].planes !== 'undefined'){
                planning.currentPlan.currentVersion = planning.planningEmployeeList[0].planes[0].versionId;
            }
            planning.includePlanningEmployeeComponent();
            },function(){
            });
        }else if (step=='NEEDS'){
            organization.includeSetUpGeneric(function(){
                organization.setActiveStep('needsTab');
                organization.includeNeedsComponent();
            });
        }
    },
    evtChageMenuTab:function(step){
        $("#learnProgress").empty();
        $("#badgeReport").empty();
        $("#pathsReport").empty();
        $("#scheduledClasses").empty();
        $(".innerMenu").hide();
        if(step=='CATALOG'){
            $("#menuE").hide();
            organization.includeCatalogComponent();
        }else if (step=='PLANNING'){
            $("#menuE").hide();
            organization.setActiveStep('planningTab');
            planning.includePlanningComponent();
        }else if (step=='MANAGEMENT'){
            $("#menuE").show();
            $("#managementMenu").show();
            organization.includeSetUpGeneric(function(){
                organization.setActiveStep('managementTab');
                organization.evtChageMenuSetup("METRICS");
            });
        }else if (step=='UNIVERSITY'){
            $("#menuE").show();
            $("#universityMenu").show();
            organization.includeSetUpGeneric(function(){
                organization.setActiveStep('universityTab');
                organization.evtChageMenuSetup("NEEDS");
            });
        }else if (step=='SETUP'){
            $("#menuE").show();
            $("#configurationMenu").show();
            organization.includeSetUpGeneric(function(){
                organization.setActiveStep('setupTab');
                organization.evtChageMenuSetup("ACCOUNT");
            });
        }else if (step=='ENGAGEMENT'){
            $("#menuE").show();
            $("#engagementMenu").show();
            organization.includeSetUpGeneric(function(){
                organization.setActiveStep('engagementTab');
                organization.evtChageMenuSetup("TEMPLATE");
            });
        }
    },
    evtChageMenuSetup:function(step){
        $("#learnProgress").empty();
        $("#badgeReport").empty();
        $("#pathsReport").empty();
        if(step=='DEFINEPEOPLE'){
            //organization.includePeople();
            organization.setSetupActiveStep('definePeopleTab');
        }else if (step=='DEFINEROLES'){
            organization.setSetupActiveStep('defineRolesTab');
            organization.includeDefineRol();
        }else if (step=='DEFINESTRUCTURE'){
            organization.setSetupActiveStep('definestructureTab');
            organization.organizationStructure();
        }else if (step=='PRIVILEGES'){
            organization.setSetupActiveStep('privilegeTab');
            organization.includeDefinePrivileges();
        }else if (step=='INSTRUCTORS'){
            organization.setSetupActiveStep('instructorsTab');
            organization.includeDefineInstructors();
        }else if (step=='EDITION'){
            organization.setSetupActiveStep('editTab');
            organization.includeDefineEdition();
        }else if (step=='CATEGORIES'){
            organization.setSetupActiveStep('categoryTab');
            organization.includeDefineCategories();
        }else if (step=='CONTACT'){
            organization.setSetupActiveStep('contactTab');
            organization.includeDefineContact();
        }else if (step=='IMAGES'){
            organization.setSetupActiveStep('imageTab');
            organization.includeDefineSkins();
        }else if (step=='TEMPLATE'){
            organization.setSetupActiveStep('templateTab');
            organization.includeDefineTemplates();
        }else if (step=='PROCESSES'){
            organization.setSetupActiveStep('processTab');
            organization.includeDefineProcess();
        }else if (step=='ACCOUNT'){
            organization.setSetupActiveStep('accountTab');
            organization.includeOrganizationAccount();
        }else if (step=='NEEDS'){
            organization.setSetupActiveStep('needsTab');
            organization.includeNeedsAdminComponent();
        }else if (step=='REPORT'){
            organization.setSetupActiveStep('reportTab');
            organization.includeOrganizationUsersReport(1,10,"active",0);
        }else if (step=='REQUEST'){
            organization.setSetupActiveStep('requestTab');
            organization.includeRequestAdmin(1,10,0);//por defecto carga la primera pagina de solicitudes de 10 filas y pendientes por revisar
        }else if (step=='METRICS'){
            organization.setSetupActiveStep('metricsTab');
            organization.includeOrganizationMetrics();
        }else if (step=='CERTIFICATES'){
            organization.setSetupActiveStep('certificatesTab');
        }else if (step=='TEMPLATE'){
            organization.setSetupActiveStep('templateTab');
        }else if (step=='RESULTS'){
            organization.setSetupActiveStep('resultsTab');
        }
    },
    sendAppInvitationEmail:function(param){
        return requestService(PATH_SERVICE_SEND_EMAIL_COURSE_ENROLL(), param, "GET", true,
        function(data) {
        }, function() {
        });
    },
    evtSenInvApp:function(param){
        $("#requestPayPopup").remove();
        $("#requestPayPopupLink").remove();
        $("#content").append("
");
        $("#content").append("");
        excludeComponent("#requestPayPopup");
        includeComponent("#requestPayPopup",getContextPath()+'/learn/enrollPaymentApprentices.jsp?courseId='+param.courseId+'&organizationId='+param.organizationId+'&apprentice='+param.profileLogin+'&comment='+param.message,function(){
        });
    },
    evtSenInvAppspecialization:function(param){
        $("#requestPayPopup").remove();
        $("#requestPayPopupLink").remove();
        $("#content").append("
");
        $("#content").append("");
        excludeComponent("#requestPayPopup");
        includeComponent("#requestPayPopup",getContextPath()+'/learn/enrollPaymentApprenticesSpecializations.jsp?specializationId='+param.specializationId+'&organizationId='+param.organizationId+'&apprentice='+param.profileLogin+'&comment='+param.message,function(){
        });
    },
    loadPaymentCompForMultipleApprentices:function(profileList,courseId,organizationId,profileLogin,message){
        $("#requestPayPopup").remove();
        $("#requestPayPopupLink").remove();
        $("#content").append("
");
        $("#content").append("");
        excludeComponent("#requestPayPopup");
        includeComponent("#requestPayPopup",getContextPath()+'/learn/enrollPaymentApprentices.jsp?courseId='+courseId+'&organizationId='+organizationId+'&apprentice='+profileLogin+'&comment='+message,function(){
        var profileList2 = profileList.split(",");
        $.each(profileList2,function(id,value){
            if(profileLogin!=value)
            organization.addPerson(value);
            });
        });
    },
    showInvitationsComponent:function(dataResponse,courseId,organizationId,message){
        var callbackBeforeLoad = function(){
            if(dataResponse.payInvitations!=null && dataResponse.payInvitations.length > 0){
                $("#invitationsList").append("");
                var profileList = [];
                $.each(dataResponse.payInvitations,function(id,value){
                    $("#accordion-inner2").append(""+value+"
");
                    profileList.push(value);
                });
                var profileLogin = profileList[0];
                $("#accordion-inner2").append("
");
                atLeastOne = true;
            }
            if(dataResponse.sentInvitations!=null && dataResponse.sentInvitations.length > 0){
                $("#invitationsList").append("");
                $.each(dataResponse.sentInvitations,function(id,value){
                    $("#accordion-inner1").append(""+value+"
");
                });
                atLeastOne = true;
                organization.includeAddApprenticesComponent(courseId,organizationId);
            }
             if(dataResponse.invalidInvitations!=null && dataResponse.invalidInvitations.length > 0){
                $("#invitationsList").append("");
                $.each(dataResponse.invalidInvitations,function(id,value){
                    $("#accordion-inner3").append(""+value+"
");
                });
                atLeastOne = true;
            }
            if(dataResponse.failedInvitations!=null && dataResponse.failedInvitations.length > 0){
                $("#invitationsList").append("");
                $.each(dataResponse.failedInvitations,function(id,value){
                    $("#accordion-inner4").append(""+value+"
");
                });
                atLeastOne = true;
            }
            $(".accordion-body:first").addClass("in");
        };
        var callbackAfterLoad = function(){
        };
        var atLeastOne = false;
        if(dataResponse.sentInvitations==null && dataResponse.failedInvitations==null && dataResponse.invalidInvitations==null && dataResponse.payInvitations==null )
            showMessage("The csv file does not contain any valid email");
        else
            generatePopup("invitationsPopup",PATH_HTML_INVITATIONS(),callbackBeforeLoad,callbackAfterLoad);
    },
    showInvitationsSpecializationsComponent:function(dataResponse,specializationId,organizationId,message){
        var callbackBeforeLoad = function(){
            if(dataResponse.payInvitations!=null && dataResponse.payInvitations.length > 0){
                $("#invitationsList").append("");
                var profileList = [];
                $.each(dataResponse.payInvitations,function(id,value){
                    $("#accordion-inner2").append(""+value+"
");
                    profileList.push(value);
                });
                var profileLogin = profileList[0];
                $("#accordion-inner2").append("
");
                atLeastOne = true;
            }
            if(dataResponse.sentInvitations!=null && dataResponse.sentInvitations.length > 0){
                $("#invitationsList").append("");
                $.each(dataResponse.sentInvitations,function(id,value){
                    $("#accordion-inner1").append(""+value+"
");
                });
                atLeastOne = true;
                organization.includeAddApprenticesSpecializationComponent(specializationId,organizationId);
            }
            if(dataResponse.invalidInvitations!=null && dataResponse.invalidInvitations.length > 0){
                $("#invitationsList").append("");
                $.each(dataResponse.invalidInvitations,function(id,value){
                    $("#accordion-inner3").append(""+value+"
");
                });
                atLeastOne = true;
            }
            if(dataResponse.failedInvitations!=null && dataResponse.failedInvitations.length > 0){
                $("#invitationsList").append("");
                $.each(dataResponse.failedInvitations,function(id,value){
                    $("#accordion-inner4").append(""+value+"
");
                });
                atLeastOne = true;
            }
            $(".accordion-body:first").addClass("in");
        };
        var callbackAfterLoad = function(){
        };
        var atLeastOne = false;
        if(dataResponse.sentInvitations==null && dataResponse.failedInvitations==null && dataResponse.invalidInvitations==null && dataResponse.payInvitations==null )
            showMessage("The csv file does not contain any valid email");
        else
            generatePopup("invitationsPopup",PATH_HTML_INVITATIONS(),callbackBeforeLoad,callbackAfterLoad);
    },
    evtSendAppInvitationEmail:function(courseId,organizationId){
        var emailInvLower = $("#emailInvEmployee").val().toLowerCase();
        var emailUserExt = $("#email").val().toLowerCase();
        $("#emailInvEmployee").removeClass('errorBox');
        var param={};
        param.courseId=courseId;
        param.organizationId=organizationId;
            if($('#emailEmployee').is(":checked")){
                $("#emailInvEmployee").addClass("required");
                if($("#hiddenIDApp").val()!=null && $("#hiddenIDApp").val()!=""){
                    param.profileLogin=$("#hiddenIDApp").val();
                    param.message=$("#comment").val();
                    organization.evtSenInvApp(param);
                }else{
                    $("#emailInvEmployee").addClass('errorBox');
                    showMessage("You must select a valid employee.");
                }
            }else if($('#emailExt').is(":checked")){
                $("#emailInvEmployee").removeClass("required");
                if($("#formAddApprentices").validate()){
                    if($("#formAddApprentices").valid()){
                        $("#email").val(emailUserExt);
                        param.profileLogin=$("#email").val();
                        param.message=$("#comment").val();
                        organization.evtSenInvApp(param);
                    }
                }
            }else if($("#emailF").is(":checked")){
                var param={};
                param.token = $("#csvToken").val();
                param.message = $("#comment").val();
                param.organizationId = organizationId;
                param.courseId = courseId;
                if(param.token != null){
                    showGenericSaving();
                    $.when(organization.evtSentInvCsv(param)).then(function(data){
                        hideGenericLoading();
                        var dataResponse = data.apprenticeInvitationsResponse;
                        organization.showInvitationsComponent(dataResponse,courseId,organizationId,param.message);
                    },function(){
                        redirectToGenericError("organization.evtSendAppInvitationEmail("+courseId+","+organizationId+")",null,true);
                    });
                }else{
                    showMessage("Invalid file type, allowed only csv files and txt");
                }
            }
    },
    evtSendAppSpecializationInvitationEmail:function(specializationId,organizationId){
        var emailInvLower = $("#emailInvEmployee").val().toLowerCase();
        var emailUserExt = $("#email").val().toLowerCase();
        $("#emailInvEmployee").removeClass('errorBox');
        var param={};
        param.specializationId=specializationId;
        param.organizationId=organizationId;
        if($('#emailEmployee').is(":checked")){
            $("#emailInvEmployee").addClass("required");
            if($("#hiddenIDApp").val()!=null && $("#hiddenIDApp").val()!=""){
                param.profileLogin=$("#hiddenIDApp").val();
                param.message=$("#comment").val();
                organization.evtSenInvAppspecialization(param);
            }else{
                $("#emailInvEmployee").addClass('errorBox');
                showMessage("You must select a valid employee.");
            }
        }else if($('#emailExt').is(":checked")){
            $("#emailInvEmployee").removeClass("required");
            if($("#formAddApprentices").validate()){
                if($("#formAddApprentices").valid()){
                    $("#email").val(emailUserExt);
                    param.profileLogin=$("#email").val();
                    param.message=$("#comment").val();
                    organization.evtSenInvAppspecialization(param);
                }
            }
        }else if($("#emailF").is(":checked")){
            var param={};
            param.token = $("#csvToken").val();
            param.message = $("#comment").val();
            param.organizationId = organizationId;
            param.specializationId = specializationId;
            if(param.token != null){
                showGenericSaving();
                $.when(organization.evtSentInvCsv(param)).then(function(data){
                    hideGenericLoading();
                    var dataResponse = data.apprenticeInvitationsResponse;
                    organization.showInvitationsComponent(dataResponse,courseId,organizationId,param.message);
                },function(){
                    redirectToGenericError("organization.evtSendAppSpecializationInvitationEmail("+courseId+","+organizationId+")",null,true);
                });
            }else{
                showMessage("Invalid file type, allowed only csv files and txt");
            }
        }
    },
    evtSentInvCsv:function(param){
        return requestService(PATH_SERVICE_SEND_APPRENTICES_INVITATION_CSV(), param, "GET", true,
        function(data) {}, function() {});
    },
    closeAddEmployee:function(){
        if(organization.currentUser.currentFile!="" && organization.currentUser.currentFile!=null){
            organization.deleteContentCsv(organization.currentUser.currentFile);
        }
        $.fancybox.close();
        $("#orgEmployeePopUp").remove();
        organization.includeEmmployeesTable();
    },
    showEmailProcess:function(processedList,unProcessedList,alreadyExistsList){
        var html="";
        html+='';
        if(unProcessedList!=null){
            $.each(unProcessedList, function(id, value) {
                var up = value.replace("null","");
                html+=''+up+'
'+value+'
'+value+'
';
        return html;
    },
    createEmployeeAccount:function(param){
        return requestService(PATH_SERVICE_CREATE_EMPLOYEE_ACCOUNT(), param, "GET", true,
        function(data) {}, function() {});
    },
    sendEmployeeInvitationCSV:function(param){
        return requestService(PATH_SERVICE_SEND_EMPLOYEE_INVITATION_CSV(), param, "GET", true,
        function(data) {
        }, function() {
        });
    },
    createAccountsMassive:function(){
        $("#messagesSignUpMassive").hide();
        if($('#emailF').is(":checked")){
            var param={};
            if(organization.currentUser.currentFile!="" && organization.currentUser.currentFile!=null ){
                param.token=organization.currentUser.currentFile;
                param.organizationId=organization.currentOrganization.organizationId;
                showGenericSaving();
                $.when(organization.sendEmployeeInvitationCSV(param)).then(function(data){
                    hideGenericLoading();
                    if(data.mailInvitationProcess.responseCode=="1"){
                        organization.showProcessMail(data.mailInvitationProcess.processed,data.mailInvitationProcess.unProcessed,data.mailInvitationProcess.alreadyExists);
                        $("#nameFile").html("");
                        $("#nameFile").removeClass('files');
                        $("#loadButton").attr('disabled',false);
                        $("#loadCSV").hide();
                        $("#nameFile").hide();
                        $("#fileDesc").hide();
                        $("#descFile").hide();
                        $("#selectOption").hide();
                        $("#uniqueAccount").hide();
                        $("#masiveAccount").hide();
                        $("#tempAccount").hide();
                        $("#titleCreate").hide();
                        $("#titleResult").show();
                        $("#divButton2").show();
                        $("#csvFile").val("");
                        organization.currentUser.currentFile="";
                        showMessage("The request has been processed.");
                        showFancyPopup("#linkOrgAddEmployee",function(){},function(){});
                        organization.includeEmmployeesTable();
                        organization.currentUser.currentFile="";
                    }else if(data.mailInvitationProcess.responseCode=="2"){
                        showMessage("You has no privilege to do this action");
                    }else if(data.mailInvitationProcess.responseCode=="0"){
                        showMessage("Failed to send mail registration, please check and try again later.");
                    }else if(data.mailInvitationProcess.responseCode=="3"){
                        showMessage("The file is empty");
                    }else if(data.mailInvitationProcess.responseCode=="7"){
                        organization.showProcessMail(data.mailInvitationProcess.processed,
                        data.mailInvitationProcess.unProcessed,data.mailInvitationProcess.alreadyExists);
                        var htmlAux=''+
                        '
'+
                        'Some of the accounts were not created due to one of these reasons. The information did not match the expected format or the maximnum number of users allowed in your subscription plan was reached.'+
                        '
'+
                        '
'+
                        '
');
                        $("#popupAddEmployeeDiv").html(htmlAux);
                        $("#popupAddEmployeeDiv").addClass('classEmployee');
                        $("#popupAddEmployeeDiv").css("border","none");
                        showFancyPopup("#linkOrgAddEmployee",function(){},function(){});
                        organization.includeEmmployeesTable();
                        organization.currentUser.currentFile="";
                    }
                },function(){
                    redirectToGenericError("organization.createAccountsMassive()","We are sorry, an error occurred and failed to save your changes.",false);
                });
            }else {
                $("#messagesSignUpMassive").show();
            }
        }
    },
    showProcessMail:function(processed,unProcessed,alreadyExists){
        var html=organization.showEmailProcess(processed,unProcessed,alreadyExists);
        $("#accountDiv").html(html);
        $("#divButton").hide();
        $("#leyendAccount").html('
'+
                            ''+
                                'Unprocessed'+
                            ' '+
                       ' 
'+
                            ' '+
                                'Processed'+
                           '  '+
                        '
'+
                            ''+
                                'Already added'+
                            ' ');
        $("#accountDiv").css('border','solid 1px #ccc');
    },
    showAddEmployeePopup2:function(){
        $("#orgEmployeePopUp").remove();
        //organization.showAddEmployeePopup();
    },
    resendEnrollSpecializationEmail:function(param){
        return requestService(PATH_SERVICE_UPDATE_RESENDENROLLSPECIALIZATIONMAIL(), param, "GET", true,
        function(data) {
        },
        function() {
        });
    },
    evtReSendEnrollEmail:function(profile, courseId, organizationId,message){
        var param={};
        param.profileLogin=profile;
        param.courseId=courseId;
        param.organizationId=organizationId;
        param.message=message;
        showGenericSaving();
        $.when(organization.resendEnrollEmail(param)).then(function(data){
            hideGenericLoading();
            if(data.responseInfoJSON.responseCode==1)
                showMessage("The email was forwarded successfully");
            else
                showMessage("Failed to send mail registration, please check and try again later.");
        },function(){
            redirectToGenericError("organization.evtReSendEnrollEmail('"+profile+"',"+courseId+","+organizationId+",'"+message+"')",null,false);
        });
    },
    evtReSendEnrollSpecializationEmail:function(profile, specializationId, organizationId,message){
        var param={};
        param.profileLogin=profile;
        param.specializationId=specializationId;
        param.organizationId=organizationId;
        param.message=message;
        showGenericSaving();
        $.when(organization.resendEnrollSpecializationEmail(param)).then(function(data){
            hideGenericLoading();
            if(data.responseInfoJSON.responseCode==1){
                showMessage("The email was forwarded successfully");
                organization.includeAddApprenticesSpecializationComponent(specializationId,organizationId);
            }else{
                showMessage("Failed to send mail registration, please check and try again later.");
                }
        },function(){
            redirectToGenericError("organization.evtReSendEnrollSpecializationEmail('"+profile+"',"+specializationId+","+organizationId+",'"+message+"')",null,false);
        });
    },
    evtEditarRol:function(trId, name, desc){
        if(desc == null){
            //desc = organization.getRolDescription(trId);
        var param = {};
        param.idRol = trId;
        requestService(PATH_SERVICE_GET_ROL_DESCRIPTION(), param, "GET", true,function(data) {
            desc = data.employeeJSON.message;
            var editRoleHtml=''+
            ''+
            ' ';
            $("#rolTrRow"+trId).html(editRoleHtml);
            $("#rolTrRow"+trId).addClass('newNeedtd');
        },
        function(data){
            desc = data.employeeJSON.message;
            var editRoleHtml=''+
            ''+
            'Title:
Description:
'+ desc+' SAVE CANCEL  
 ';
            $("#rolTrRow"+trId).html(editRoleHtml);
            $("#rolTrRow"+trId).addClass('newNeedtd');
        });
        }else {
            var editRoleHtml=''+
            ''+
            'Title:
Description:
'+ desc+' SAVE CANCEL  
 ';
            $("#rolTrRow"+trId).html(editRoleHtml);
            $("#rolTrRow"+trId).addClass('newNeedtd');
        }
    },
    evtCreateNewRol:function(){
        $("#noData").html("");
        var editRoleHtml=''+
                        ''+
                        'Title:
Description:
SAVE CANCEL  
 "+employee+" "+employee+" 
");
        $("#content").append("");
        excludeComponent("#benefitsPopUp");
        includeComponent("#benefitsPopUp",PATH_HTML_ORGANIZATION_BENEFITS(), function(){
            showFancyPopup("#benefitsPopUpLink",function(){});
        });
    },
    showOrgSignupPopup:function(message){
        showGenericLoading();
        $.when(profile.isLogged()).then(function(data){
            hideGenericLoading();
            if(data.responseInfoJSON.responseCode!="0"){
                profile.hideLoginPopup();
                $("#signupPopup").remove();
                $("#signupPopupLink").remove();
                $("#content").append("
");
                $("#content").append("");
                excludeComponent("#orgSignupPopup");
                includeComponent("#orgSignupPopup",PATH_HTML_CREATE_NEW_ORGANIZATION(),function(){
                    if(message != null){
                        $("#messagesSignUpOrg").html(message);
                        $("#messagesSignUpOrg").removeClass("warning");
                        $("#messagesSignUpOrg").show();
                    }
                    $("#orgDomain").val( "@" + data.responseInfoJSON.message.split("@")[1] );
                    $("#orgDomain").attr("disabled","disabled");
                    $("#orgDomain").next("div.tipSignUp").hide();
                    showFancyPopup("#signupOrgPopupLink",function(){});
                });
            }else {
                profile.showSignupPopup("You need a user account to create an organization. Please register"+"");
            }
        },function(){
            redirectToGenericError("organization.showOrgSignupPopup()","We are sorry, an error occurred and failed to save your changes.",false);
        });
    },
    showAddOrgArea:function(idArea, name, descr, parentId){
        profile.hideLoginPopup();
        $("#signupPopup").remove();
        $("#signupPopupLink").remove();
        $("#content").append("
");
        $("#content").append("");
        excludeComponent("#linkchoserolPopUp");
        includeComponent("#linkchoserolPopUp",PATH_HTML_CREATE_NEW_AREA()+"?areaId="+idArea+"&parentId="+parentId,function(){
            $("#areaName").val(name);
            $("#areaDescription").val(descr);
            showFancyPopup("#linkchoserolPopUpid",function(){});
        });
    },
    showAddEmployeePopup:function(message){
        $("#content").append("
");
        $("#content").append("
");
        $("#header").append("
'+
        'Set area:  
'+
        '
'+
        'Select an area ';
        $.each(organization.organizationAreas, function(id, value) {
            html+=''+value.name+' ';
            });
            html+=' '+
            '
Set role:  
'+
            '
'+
            'Select a role ';
            $.each(organization.organizationRoles, function(id, value) {
            html+=''+value.name+' ';
        });
        html+=' '+
        '
'+
        '
'+
        'Filter by: 
'+
        '
'+
        'All '+
        'Active employees '+
        'Suspended employees '+
        ' 
Active employees 
Suspended employees 
';
        var labelHeader = '
People ';
        $("#definePeople").html(labelHeader + html);
        organization.includeEmmployeesTable();
    },
    downloadColaboratorsExcelFile:function(){
        return requestService(PATH_SERVICE_EXPORT_COLABORATORS(), null, "GET", true,
        function(data) {
            showMessage("In few minutes you will receive an email with the link to download the report.");
        }, function() {
            showMessage("In few minutes you will receive an email with the link to download the report.");
        });
    },
    includeEmmployeesTable:function(){
        var hash = generateHash();
        includeComponent("#employeesTable",PATH_HTML_EMPLOYEE_GRID()+'?organizationId='+organization.currentOrganization.organizationId,function(){
        });
    },
    writeRolHtmlRow:function(id,name, description){
        var html=''+
        ''+
        ''+
        ' ';
        $("#rolTrRow"+id).html(html);
        $("#rolTrRow"+id).removeClass('newNeedtd');
        organization.showMenu(id);
    },
    writeNewRolRow:function(id,name, description){
        var html=''+
        ''+
        ''+
        ' '+organization.currentOrganization.organizationName+'ADD AREA
 
';
                html='DRAG HERE TO REMOVE
'+html;
                var labelHeader = '
Areas ';
                $("#defineStructure").html(labelHeader + html);
                (initTouchSupport($))(jQuery);
                organization.chartOrgIni();
                organization.setDroppableBin();
                organization.mouseOverInit();
            }
            organization.loadOrganizationAreas();
        },function(){
            redirectToGenericError("organization.organizationStructure()","We are sorry, an error occurred charging organization structure.",false);
        });
    },
    updateArea:function(padre,hijo){
        var param={};
        param.areaId=hijo.substring(2);
        if(padre!="")
            param.parentId=padre.substring(2);
            showGenericSaving();
            $.when(organization.saveArea(param)).then(function(){
                hideGenericLoading();
                organization.loadOrganizationAreas();
            },function(){
                redirectToGenericError("organization.updateArea("+padre+","+hijo+")","We are sorry, an error occurred and failed to save your changes.",false);
            });
    },
    whiteTags:function(id,name, list, html){
        html2="";
        if(list!=null){
            html2=""+name+"";
            html=html+html2;
            $("#uls").append(""+name);
            $("#uls").append("");
            $.each(list, function(id, value) {
                html=organization.whiteTags(Math.round(value.areaId),value.name,value.hierarchy,html);
            });
            html=html+" ";
            html=html+" ";
            $("#uls").append(" ");
            $("#uls").append(" ");
        }else{
            $("#uls").append(""+name+" ");
            html=html+""+name+" ";
        }
        return html;
    },
    chartOrgIni:function() {
        $("#org").jOrgChart({
            chartElement : '#chart',
            dragAndDrop  : true,
            drag:function(e,ui){
            }
        });
    },
    deleteArea:function(param){
        return requestService(PATH_SERVICE_DELETE_AREA(), param, "GET", true,
        function(data) {
        },
        function() {
        });
    },
    setDroppableBin:function(){
        $("#paperBin").droppable({
            drop: function( event, ui ) {
                confirmation("Are you sure you want to delete this area?",function(){
                    var param={};
                    var idC=ui.draggable[0].id;
                    param.areaId=idC.substring(7);
                    showGenericLoading();
                    $.when(organization.deleteArea(param)).then(function(data){
                        hideGenericLoading();
                        organization.organizationStructure(organization.currentOrganization.organizationId);
                        $( ui.draggable ).draggable({ cursor: "auto", cursorAt: { top: 56, left: 56 } });
                    },function(){
                        redirectToGenericError(null,"We are sorry, an error occurred and failed to save your changes.",true);
                    });
                },function(){
                });
            },
            activeClass: "binHover"
        });
    },
    includeBreadCrum:function(courseId,type,courseTitle,organizationId){
        var typeDef='';
        var html='';
        if(type=='organization'){
            typeDef="Catalog";
            html=''+typeDef+' '+
                '  '+courseTitle+' ';
        }else if(type=='dashboard'){
            typeDef="Go to course!";
            html=''+typeDef+'   '+courseTitle+' ';
        }
        $("#breadcrumbs").html(html);
    },
    includeBreadCrumCreateEdit:function(organizationId,type){
        var typeDef='';
        var html='';
        if(type=='organization'){
            html=''+
            'Catalog   >  Create / Edit Course '+
            ''+
            '
';
        }else if(type=='teach'){
            html=''+
            'Teach   >  Create / Edit Course '+
            ''+
            '
';
        }
        $("#breadcrumbsCreate").html(html);
    },
    includeSEmployee:function(profile){
        organization.cleanContent();
        includeComponent("#orgSetUp",PATH_JSP_EMPLOYEEPREVIEW()+"?organizationId="+organization.currentOrganization.organizationId+"&profile="+profile,function(){
            $("#tablePreviewTitle").remove();
        });
    },
    includeSetupEmployee:function(){
        organization.cleanContent();
        organization.isOnlyEmployee=1;
        showGenericLoading();
        $.when(organization.loadEmployeeInformation()).then(function(data){
            hideGenericLoading();
            organization.includeSEmployee(organization.currentUser.employeeInformationList[0].employeeId);
        },function(){
            redirectToGenericError("organization.includeSetupEmployee()",null,false);
        });
    },
    includeSetupEmployee2:function(){
        organization.cleanContent();
        organization.isOnlyEmployee=1;
        showGenericLoading();
        $.when(organization.loadEmployeeInformation()).then(function(data){
            hideGenericLoading();
            organization.evtEmployeePreview(organization.currentUser.employeeInformationList[0].employeeId);
        },function(){
            redirectToGenericError("organization.includeSetupEmployee()",null,false);
        });
    },
    arrow:function(id){
        $("#employeesContent"+id).carouFredSel({
            items				: 3,
            direction			: "left",
            scroll : {
                items			: 1,
                duration		: 1000,
                pauseOnHover	: true
            },
            prev	: {
                button	: "#arrowLeft"+id,
                key		: "left"
            },
            next	: {
                button	: "#arrowRight"+id,
                key		: "right"
            },
            circular:false,
            auto:{
                play:false
            }
        });
    },
    arrowApprove:function(id){
        $("#employeesApprove"+id).carouFredSel({
            items				: 3,
            direction			: "left",
            scroll : {
                items			: 1,
                duration		: 1000,
                pauseOnHover	: true
            },
            prev	: {
                button	: "#arrowLeftApprove"+id,
                key		: "left"
            },
            next	: {
                button	: "#arrowRightApprove"+id,
                key		: "right"
            },
            circular:false,
            auto:{
                play:false
            }
        });
    },
    arrowReject:function(id){
        $("#employeesReject"+id).carouFredSel({
                items				: 3,
                direction			: "left",
            scroll : {
                items			: 1,
                duration		: 1000,
                pauseOnHover	: true
            },
            prev	: {
                button	: "#arrowLeftReject"+id,
                key		: "left"
            },
            next	: {
                button	: "#arrowRightReject"+id,
                key		: "right"
            },
            circular:false,
            auto:{
                play:false
            }
        });
    },
    //---------------NEED
    includeNeedsAdminComponent:function(){
        var hash = generateHash();
        showGenericLoading();
        $.when(
            organization.loadOrganizationVersions()
            ).then(function(){
            if(hash == currentHash){
                organization.cleanSetUpContent();
                includeComponent("#orgNeeds",PATH_HTML_NEED_ADMIN(),function(){
                    organization.showNeedAdmin();
                    organization.getDefaultVersion();
                    hideGenericLoading();
                });
            }
        },function(){
            if(hash == currentHash){
                redirectToGenericError("organization.includeNeedsAdminComponent()","We are sorry, an error occurred charging needs.",false);
            }
        });
    },
    getDefaultVersion:function(){
        var ver=Math.round(organization.organizationVersions[0].versionId);
        $("#versions option[value="+ver+"]").attr("selected","selected");
        organization.currentVersion.id=ver;
        $("#checkVersion").show();
        $("#labelFinalVersion").removeClass('selectedVer');
        organization.getVersion(ver);
    },
    loadOrganizationVersions:function(){
        var param={};
        param.organizationId=organization.currentOrganization.organizationId;
        return requestService(PATH_SERVICE_GET_ALL_ORG_VERSION(), param, "GET", true,
        function(result){
            organization.organizationVersions=result.needVersion;
        });
    },
    loadCurrentVersion:function(versionId){
        var param={};
        param.versionId=versionId;
        param.organizationId=organization.currentOrganization.organizationId;
        return requestService(PATH_SERVICE_GET_NEED_VERSION(), param, "GET", true,
        function(result){
            organization.currentVersionList=result.sourceNeedJSON;
        });
    },
    showNeedAdmin:function(){
        var html="";
        var deleteQuestionVersion="Do you want to delete the current version?";
        var marckAs="Sure you want to mark this as the final version?";
        html+=''+
        ''+
        ''+
        ' COPY VERSION DELETE 
';
        $("#needOptions").html(html);
    },
    selectVersion:function(idV){
        $("#versions option[value="+idV+"]").attr("selected","selected");
        organization.getVersion();
    },
    saveVersionCopy:function(param){
        return requestService(PATH_SERVICE_COPY_VERSION(), param, "GET", true,
        function(data) {
        }, function() {
        });
    },
    evtSaveVersionCopy:function(){
        if($("#copyForm").valid()){
            var param={};
            param.versionName=$("#inputCopy").val();
            param.versionId=organization.currentVersion.id;
            var hash = generateHash();
            showGenericSaving();
            $.when(organization.saveVersionCopy(param)).then(function(data){
                if(hash == currentHash){
                    hideGenericLoading();
                    if(data.needVersionJSON.responseCode=="1"){
                        $.fancybox.close();
                        showGenericSaving();
                        $.when(organization.loadOrganizationVersions()).then(function(){
                            hideGenericLoading();
                            organization.showNeedAdmin();
                            organization.selectVersion(data.needVersionJSON.needVersionId);
                            $.fancybox.close();
                        },function(){
                            redirectToGenericError(null,"We are sorry, an error occurred charging needs.",false);
                        });
                    }
                }
            },function(){
                if(hash == currentHash)
                redirectToGenericError("organization.evtSaveVersionCopy()","We are sorry, an error occurred and failed to save your changes.",false);
            });
        }
    },
    showNeedsTable:function(){
        var deleteQuestionNeed="Do you want to delete this need?";
        var deleteQuestionSource="Do you want to delete this capabilitie?";
        var html="";
        html+=''+
        ''+
        'CAPABILITIES
SKILLS
COURSES
 ';
        $.each(organization.currentVersionList,function(id, value){
            var idS=Math.round(value.sourceId);
            var needList=[];
            needList=value.needs;
            html+=''+
            ''+
            ''+
            '
'+value.sourceName+'
'+
            '
 '+
            '
'+
            ' '+
            ''+
            ''+
            ''+value.sourceName.trim()+'
'+value.description+'
'+
            ' '+
            '';
            if(needList!=null){
                var numberOfNeeds=needList.length;
                html+=''+
                '';
                $.each(needList,function(idn, valuen){
                    var varClass="";
                    numberOfNeeds=numberOfNeeds-1;
                    if(numberOfNeeds==0){
                        varClass='lastBottom';
                    }
                    var idN=Math.round(valuen.needId);
                    html+=''+
                    ''+valuen.priority+'
'+valuen.need.trim()+'
'+valuen.description+'
';
                    if(valuen.courses!=null){
                        $.each(valuen.courses,function(idc, valuec){
                            var ncId=Math.round(valuec.needcourseId);
                            if(Math.round(valuec.courseStatus)!=16){
                                html+='
';
                            }else{
                                html+='
';
                                html+='
';
                            }
                        });
                    }
                    html+='
 ';
                });
                html+=' 
';
            }else {
            html+='';
            }
            html+=' '+
            ' ';
        });
        html+='
';
        //$("#needBoard").html(html);
    },
    showNeedsEmployeeTable:function(){
    var html="";
    html+=''+
        ''+
        'CAPABILITIES
SKILLS
COURSES
 ';
        $.each(organization.currentVersionList,function(id, value){
            var idS=Math.round(value.sourceId);
            var needList=[];
            needList=value.needs;
            html+=''+
            ''+
            ''+
            '
'+value.sourceName+'
'+
            '
 '+
            '
'+
            ' '+
            ''+
            ''+
            ''+value.sourceName.trim()+'
'+value.description+'
'+
            ' '+
            '';
            if(needList!=null){
                var numberOfNeeds=needList.length;
                html+=''+
                '';
                $.each(needList,function(idn, valuen){
                    var varClass="";
                    numberOfNeeds=numberOfNeeds-1;
                    if(numberOfNeeds==0){
                        varClass='lastBottom';
                    }
                    var idN=Math.round(valuen.needId);
                    html+=''+
                    ''+valuen.priority+'
'+valuen.need.trim()+'
'+valuen.description+'
';
                    if(valuen.courses!=null){
                        $.each(valuen.courses,function(idc, valuec){
                            var ncId=Math.round(valuec.needcourseId);
                            if(Math.round(valuec.courseStatus)!=16){
                                html+='
';
                            }else{
                                html+='
';
                            }
                        });
                    }
                    html+='
 ';
                });
                html+=' 
';
            }else {
                html+='';
            }
            html+=' '+
            ' ';
        });
        html+='
';
        //$("#needBoard").html(html);
    },
    deleteNeedC:function(param){
        return requestService(PATH_SERVICE_DELETE_NEEDCOURSE(), param, "GET", true,
        function(data) {
        }, function() {
        });
    },
    deleteNeedCourse:function(idNC){
        confirmation("Are you sure you want to delete this course?",function(){
            var param={};
            param.needCourseId=idNC;
            showGenericSaving();
            $.when(organization.deleteNeedC(param)).then(function(data){
                hideGenericLoading();
                if(data.responseInfoJSON.responseCode=="1"){
                    $("#needCourseId"+idNC).remove();
                }
            },function(){
                redirectToGenericError("organization.deleteNeedCourse("+idNC+")","We are sorry, an error occurred and failed to save your changes.",false);
            });
        },function(){
        });
    },
    deleteN:function(param){
        return requestService(PATH_SERVICE_DELETE_NEED(), param, "GET", true,
        function(data) {
        }, function() {
        });
    },
    deleteNeed:function(idN){
        var param={};
        param.needId=idN;
        var hash = generateHash();
        showGenericSaving();
        $.when(organization.deleteN(param)).then(function(){
            if(hash == currentHash){
                hideGenericLoading();
                organization.selectVersion(organization.currentVersion.id);
            }
        },function(){
            if(hash == currentHash)
                redirectToGenericError("organization.deleteNeed("+idN+")","We are sorry, an error occurred and failed to save your changes.",false);
        });
    },
    deleteS:function(param){
        return requestService(PATH_SERVICE_DELETE_SOURCE(), param, "GET", true,
        function(data) {
        }, function() {
        });
    },
    deleteSource:function(idS){
        var param={};
        param.sourceId=idS;
        var hash = generateHash();
        showGenericSaving();
        $.when(organization.deleteS(param)).then(function(){
            if(hash == currentHash){
                hideGenericLoading();
                organization.selectVersion(organization.currentVersion.id);
            }
        },function(){
            if(hash == currentHash)
                redirectToGenericError("organization.deleteSource("+idS+")","We are sorry, an error occurred and failed to save your changes.",false);
        });
    },
    cancelMarck:function(){
        $.fancybox.close();
        $("#checkVersion").removeAttr("checked");
    },
    evtDeleteVersion:function(deleteQuestionNeed){
        var isFinal=false;
        $.each(organization.organizationVersions, function(id, org){
            var idV=Math.round(org.versionId);
            if((idV==$('#versions option:selected').val()) && (org.isFinalVersion==1)){
                showMessage("You cannot delete the published version.");
                isFinal=true;
                return null;
            }
        });
        if(!isFinal){
            confirmation(deleteQuestionNeed,function(){organization.deleteVersion();});
        }
    },
    deleteNeedV:function(param){
        return requestService(PATH_SERVICE_DELETE_VERSION(), param, "GET", true,
        function(data) {
        },
        function() {
        });
    },
    deleteVersion:function(){
        var param={};
        param.versionId=organization.currentVersion.id;
        var hash = generateHash();
        showGenericSaving();
        $.when(organization.deleteNeedV(param)).then(function(data){
            if(hash == currentHash){
                hideGenericLoading();
                showGenericLoading();
                $.when(organization.loadOrganizationVersions()).then(function(){
                    hideGenericLoading();
                    organization.showNeedAdmin();
                    organization.getDefaultVersion();
                },function(){
                    redirectToGenericError("organization.deleteVersion()","We are sorry, an error occurred charging needs.",false);
                });
            }
        },function(){
            if(hash == currentHash)
                redirectToGenericError("organization.deleteVersion()","We are sorry, an error occurred and failed to save your changes.",false);
        });
    },
    evtShowNeedstr:function(idSource){
        $("#sourceIdOpen"+idSource).show();
        $("#sourceIdClosed"+idSource).hide();
    },
    evtHideNeedstr:function(idSource){
        $("#sourceIdOpen"+idSource).hide();
        $("#sourceIdClosed"+idSource).show();
    },
    evtCreateNewNeed: function(idS) {
        var html = '' +
        '' +
        '
' +
        '1 ' +
        '2 ' +
        '3 ' +
        '4 ' +
        '5 ' +
        ' ' +
        '
' +
        '
 ' +
        '
Skill:
Description:
SAVE CANCEL 
 ';
        $("#tBodyNeed" + idS).prepend(html);
        $("#newNeedForm input").keypress(function(e) {
            if (e.which == 13) {
                organization.evtSaveNewNeed(idS);
            }
        });
        $(".editCourseFormHelp").hover(
            function () {
                course.evtShowHelp($(this).attr("message"), this);
            },
            function () {
                course.evtHideHelp();
            }
        );
    },
    evtEditNeed: function(idS, idN, need, descr, prio, deleteQuestionNeed, varClass) {
        var htmlTdPriority = "";
        var htmlTdDescr = "";
        var nameSelect = "selectPriority" + idN;
        htmlTdPriority = '' +
        '
' +
        '1 ' +
        '2 ' +
        '3 ' +
        '4 ' +
        '5 ' +
        ' ' +
        '
' +
        '
 ' +
        '
Skill:
Description:'+descr.trim()+' 
SAVE CANCEL 
'+prio+'
';
        htmldesc='';
        $("#tdPriority"+idN).html(htmlprio);
        $("#tdDescr"+idN).html(htmldesc);
        $("#tdPriority"+idN).removeClass('newNeedtd');
        $("#tdDescr"+idN).removeClass('newNeedtd');
    },
    evtEditSource:function(idS,sourceName, descr){
        var html="";
        $("#sourceIdOpen"+idS).hide();
        html=''+
        'Capability:
Description:'+descr+' 
SAVE CANCEL 
 ';
        $("#sourceIdOpen"+idS).after(html);
        $("#inputNewSource").focus();
        $("#newsourceform input").keypress(function(e) {
            if(e.which == 13) {
                organization.evtSaveNewSource(idS);
            }
        });
    },
    cancelEditSource:function(idS){
        $("#sourceIdOpen"+idS).show();
        $("#trNeedSourceEdit").remove();
    },
    cancelEditExternalClass:function(idEC){
        $("#rowForclass"+idEC).show();
        $("#trExternalClassEdit").remove();
    },
    evtSaveNewNeed:function(idS){
        var html="";
        if($("#newNeedForm").valid()){
            $('.obligatory').removeClass('on');
            var descr=$("#inputNewDescr").val();
            var need=$("#inputNewNeed").val();
            var prio=$("#selectNewPriority").val();
            showGenericSaving();
            $.when(organization.createEditNeed(idS,need,descr,prio)).then(function(){
                hideGenericLoading();
            },function(){
                redirectToGenericError("organization.evtSaveNewNeed("+idS+")","We are sorry, an error occurred and failed to save your changes.",false);
            });
        }else{
            $('.obligatory').addClass('on');
        }
    },
    createEditNeed:function(sourceId,need,description,priority,needId){
        var param={};
        param.need=need;
        param.description=description;
        param.versionId=organization.currentVersion.id;
        param.priority=priority;
        param.sourceId=sourceId;
        if(needId!=null)
            param.needId=needId;
        return requestService(PATH_SERVICE_CREATE_EDIT_NEED(), param, "GET", true,
            function(result){
            if(result.needJSON[0].responseCode=="1")
                organization.selectVersion(organization.currentVersion.id);
            if(result.needJSON[0].responseCode=="0")
                showMessage("no sirve");
        });
    },
    evtSaveCompletedNewVersion:function(){
        $("#header").append("");
        $("#header").append("'+
        'Capability:
Description:
SAVE CANCEL 
 ';
        $("#needTableId").append(html);
        $("#inputNewSource").focus();
        $("#newsourceform input").keypress(function(e) {
            if(e.which == 13) {
                organization.evtSaveNewSource();
            }
        });
    },
    saveNewSource:function(param){
        return	requestService(PATH_SERVICE_CREATE_NEW_SOURCE(), param, "GET", true,
        function(data) {
        }, function() {
        });
    },
    evtSaveNewSource:function(idS){
        var param={};
        if($("#newsourceform").valid()){
            $('.obligatory').removeClass('on');
            if(idS!=null)
                param.sourceId=idS;
                param.versionId=organization.currentVersion.id;
                param.sourceName=$("#inputNewSource").val();
                param.description=$("#inputNewSourceDescr").val();
                var hash = generateHash();
                showGenericSaving();
                $.when(organization.saveNewSource(param)).then(function(data){
                    if(hash == currentHash){
                        hideGenericLoading();
                        if(data.sourceNeedJSON.responseCode=="1"){
                            organization.selectVersion(organization.currentVersion.id);
                            $("#newsourceform").remove();
                        }else if(data.sourceNeedJSON.responseCode=="0"){
                            showMessage("error del servidor");
                        }
                    }
                },function(){
                    if(hash == currentHash)
                        redirectToGenericError("organization.evtSaveNewSource()","We are sorry, an error occurred and failed to save your changes.",false);
                });
        }else{
            $('.obligatory').addClass('on');
        }
    },
    evtAddCourses:function(needId,need){
        $("#header").append("");
        $("#header").append("Aqui va el resultado de la busqueda 
");
        var courses=result.courseJSON;
        var html = "";
        if(courses!=null){
            html+=organization.createHtmlSearch(courses,"needs");
            $("#searchResultN").html(html);
            if(courses.length == 0){
                $("#searchResultN").prepend("0 results found 
");
            }
                $("#searchResultN").prepend("Results for:  "+param.search+" 
");
                $("#searchWords").val(param.search);
                $("#buttonsCourses").show();
                reduceDescription();
        }
        showFancyPopupAddCourses("#linksearchNeedCourses",function(){});
    },
    searchCourses:function(param){
        return 	requestService(PATH_SERVICE_SEARCH(), param, "GET", true,
            function(result){
            }, function (result){ });
    },
    searchPublicCourses:function(param){
        return 	requestService(PATH_SERVICE_SEARCH_PUBLIC_COURSES(), param, "GET", true,
        function(result){
        }, function (result){ });
    },
    evtFindCourses:function(idNeed){
        $("#buttonsCourses").hide();
        var param = {};
        param.search = $("#searchWordsNeed").val();
        showGenericLoading();
        $.when(organization.searchCourses(param)).then(
            function(result){
                hideGenericLoading();
                organization.showNeedCourses(result, param);
            },function(){
            redirectToGenericError("organization.evtFindCourses("+idNeed+")",
                                    "We are sorry, an error occurred and failed to save your changes.",false);
        });
    },
    showButtons:function(){
        $("#buttonsCourses").show();
    },
    addNeedCourses:function(param){
        return requestService(PATH_SERVICE_ADD_NEED_COURSES(), param, "GET", true,
        function(data) {
        }, function() {
        });
    },
    evtAddNeedCourses:function(idN,courses){
        var param={};
        param.needString=courses;
        showGenericSaving();
        $.when(organization.addNeedCourses(param)).then(function(){
            hideGenericLoading();
            $.fancybox.close();
            organization.selectVersion(organization.currentVersion.id);
        },function(){
            redirectToGenericError("organization.evtAddNeedCourses("+idN+",'"+courses+"')","We are sorry, an error occurred and failed to save your changes.",false);
        });
    },
    getAreaInfo:function(e){
        var id=e.id.substring(7);
        if(id!=""){
            $("#"+e.id).append('
');
            includeComponent("#idGeneric"+id,PATH_HTML_INFO_AREA()+'?areaId='+id,function(){
            });
        }
    },
    lastClicked:"",
    wasClicked:false,
    mouseOverInit:function(){
        $(".showPopup").hover(
            function () {
                if(organization.lastClicked != $(this).attr("id")){
                    organization.wasClicked = false;
                    organization.removePopup();
                    organization.getAreaInfo(this);
                    organization.lastClicked = "";
                }
            },
            function () {
                if(!organization.wasClicked){
                    organization.removePopup();
                }
            }
        );
        $(".showPopup").click(function(){
            organization.wasClicked = true;
            organization.lastClicked = $(this).attr("id");
            organization.getAreaInfo(this);
        });
        $(document).mouseup(function(e){
            if($(e.target).parent(".areapopup").length==0 && !$(e.target).hasClass("areapopup")) {
                organization.removePopup();
            }
        });
    },
    removePopup:function(){
        $(".helpPopup").remove();
        $(".mouseOv").remove();
    },
    marckAsFinalV:function(param){
        return 	requestService(PATH_SERVICE_MARCK_AS_FINAL_VERSION(), param, "GET", true,
        function(data) {
        }, function() {});
    },
    marckAsFinalVersion:function(){
        var param={};
        param.organizationId=organization.currentOrganization.organizationId;
        param.versionId=organization.currentVersion.id;
        showGenericSaving();
        $.when(organization.marckAsFinalV(param)).then(function(data){
            if(data.responseInfoJSON.responseCode==1){
                $.fancybox.close();
                showGenericSaving();
                $.when(organization.loadOrganizationVersions()).then(function(){
                    hideGenericLoading();
                    organization.showNeedAdmin();
                    organization.selectVersion(organization.currentVersion.id);
                    $.fancybox.close();
                },function(){
                    redirectToGenericError(null,"We are sorry, an error occurred charging needs.",false);
                });
            }
        },function(){
            redirectToGenericError("organization.marckAsFinalVersion()","We are sorry, an error occurred and failed to save your changes.",true);
            $("#checkVersion").removeAttr("checked");
        });
    },
    checkObligatorySignUp:function(){
        $("input").each(function(){
            if($(this).hasClass("error")){
                $(this).parent().next().children(".obligatory").addClass("on");
            }else{
                $(this).parent().next().children(".obligatory").removeClass("on");
            }
        });
        $("select").each(function(){
            if($(this).hasClass("error")){
                $(this).parent().next().children(".obligatory").addClass("on");
            }else{
                $(this).parent().next().children(".obligatory").removeClass("on");
            }
        });
    },
    showOption:function(value){
        $("#messagesSignUp").hide();
        $("#messagesSignUpMassive").hide();
        if(value=="emailText"){
            if(organization.currentUser.currentFile!="" && organization.currentUser.currentFile!=null){
                organization.deleteContentCsv(organization.currentUser.currentFile);
            }
            $("#trNameTemp").hide();
            $("#trLastNameTemp").hide();
            $("#trNameUserTemp").hide();
            $("#trPasswordTemp").hide();
            $("#trShowMoreTemp").hide();
            $("#showMoreTemp").hide();
            $("#trEmail").show();
            $("#trName").show();
            $("#trLastName").show();
            $("#passwordGenerator").show();
            $("#passwordGenerator").prop('checked');
            $("#labelPassword").show();
            $("#trShowMore").show();
            $("#accountDiv").hide();
            $("#descFile").hide();
            $("#leyendAccount").hide();
            $("#loadCSV").hide();
            $("#tempName").val('');
            $("#tempPassword").val('');
        }else if(value=="emailCSV"){
            $("#trNameTemp").hide();
            $("#trLastNameTemp").hide();
            $("#trNameUserTemp").hide();
            $("#trPasswordTemp").hide();
            $("#trShowMoreTemp").hide();
            $("#showMoreTemp").hide();
            $("#emailEmployee").val("");
            $("#trEmail").hide();
            $("#trName").hide();
            $("#trLastName").hide();
            $("#passwordGenerator").hide();
            $("#labelPassword").hide();
            $("#passwordInput").hide();
            $("#trShowMore").hide();
            $("#accountDiv").show();
            $("#descFile").show();
            $("#leyendAccount").show();
            $("#loadCSV").show();
        }else if( value == "emailTextTmp" ){
            if(organization.currentUser.currentFile!="" && organization.currentUser.currentFile!=null){
                organization.deleteContentCsv(organization.currentUser.currentFile);
            }
            $("#trNameTemp").show();
            $("#trLastNameTemp").show();
            $("#trNameUserTemp").show();
            $("#trPasswordTemp").show();
            $("#trShowMoreTemp").show();
            $("#showMoreTemp").show();
            $("#trEmail").hide();
            $("#trName").hide();
            $("#trLastName").hide();
            $("#passwordGenerator").hide();
            $("#labelPassword").hide();
            $("#trShowMore").hide();
            $("#accountDiv").hide();
            $("#descFile").hide();
            $("#leyendAccount").hide();
            $("#loadCSV").hide();
            $("#passwordGenerator").hide();
            $("#labelPassword").hide();
            $("#trShowMore").hide();
            $("#passwordInput").hide();
            $("#profilePassword_id").hide();
            $("#thepwddiv2").hide();
            $("#tempName").val('');
            $("#tempPassword").val('');
        }
    },
    showOptionApp:function(value){
        if(value=="extApp"){
            $("#tdExtappTitle").show();
            $("#tdExtappInput").show();
            $("#tdEmployeeAppInput").hide();
            $("#tdEmployeeAppTitle").hide();
            $("#email").addClass("required");
            $("#emailInvEmployee").removeClass("required");
            $("#loadCSV").hide();
        }else if(value=="employeeApp"){
            $("#hiddenIDApp").val("");
            $("#tdExtappTitle").hide();
            $("#tdExtappInput").hide();
            $("#tdEmployeeAppInput").show();
            $("#tdEmployeeAppTitle").show();
            $("#email").removeClass("required");
            $("#emailInvEmployee").addClass("required");
            $("#loadCSV").hide();
        }else if(value=="emailCSV"){
            $("#loadCSV").show();
            $("#tdEmployeeAppInput").hide();
            $("#tdEmployeeAppTitle").hide();
            $("#tdExtappTitle").hide();
            $("#tdExtappInput").hide();
        }
    },
    sendCsvFile:function(){
        try{
            $("#fileForm").ajaxSubmit({
                dataType:"json",
                beforeSubmit:function(){
                    organization.currentUser.currentFile="";
                },
                success:function(data){
                    data  = data;
                    organization.currentUser.currentFile=data.token;
                    $("#nameFile").html(''+data.fileName+'
');
                    $("#nameFile").append('' + ("Invalid file type, allowed only csv files and txt")
                    + ' ');
                    $("#messagesSignUp").show();
                    }else if(data.error="error"){
                        showMessage("Can not load file");
                    }
                }
            });
        }catch(e){
        }
    },
    deleteCsvFile:function(param){
        return 	requestService(PATH_SERVICE_DELETE_FILE_CSV(), param, "GET", true,
        function(data) {
        }, function() {});
    },
    deleteContentCsv:function(token){
        var param={};
        param.token=token;
        $.when(organization.deleteCsvFile(param)).then(function(data){
            if(data.responseInfoJSON.responseCode==1){
                $("#nameFile").html("");
                $("#nameFile").removeClass('files');
                $("#loadButton").attr('disabled',false);
                $("#csvFile").val("");
                organization.currentUser.currentFile="";
            }else if(data.responseInfoJSON.responseCode==2){
                showMessage('It has permission to perform this action');
            }
        },function(){
            redirectToGenericError("organization.deleteContentCsv('"+token+"')","We are sorry, an error occurred and failed to save your changes.",false);
        });
    },
    resendSelectedEmployeeInvitation:function(param){
        return requestService(PATH_SERVICE_RESEND_EMP_INVITATION(), param, "GET", true,
        function(data) {
        }, function() {
        });
    },
    initAutocomplete:function(organizationId,selector){
        $(selector).autocomplete({
            source:  function( request, response ) {
                $("#hiddenIDApp").val("");
                $("#hiddenID").val("");
                $("#hiddenID").val("");
                var length=$(selector).val().length;
                if(length!=0){
                    var param={};
                    var emailInvLower = $(selector).val().trim().toLowerCase();
                    $(selector).val(emailInvLower);
                    param.keyword = emailInvLower;
                    param.organizationId=organizationId;
                    requestService(PATH_SERVICE_GET_USERS_BY_KEY(), param, "GET", false,
                    function(result){
                        organization.usersListAux=[];
                        organization.usersList=result.profileJSON;
                        $.each(organization.usersList,function(id,value){
                            var empInvList = {};
                            if(value.profileLastName!=null){
                                empInvList.label=value.profileName.trim()+", "+value.profileLastName.trim()+" ("+value.profileLogin.trim()+")";
                            }else{
                                empInvList.label=value.profileName.trim()+", "+value.profileLogin.trim()+")";
                            }
                            empInvList.value=value.profileLogin.trim();
                            organization.usersListAux.push(empInvList);
                        });
                    });
                    response(organization.usersListAux );
                    return;
            }
        },
        appendTo: selector == "#emailInvEmployee" ? "#tdApp" : selector == "#adminInput" ? "#containerAdmin" : "#employeeInputTd",
            minLength: 1,
            selectFirst: true,
            select: function( event, ui ) {
                var selectedObj = ui.item;
                $(selector).val(selectedObj.label);
                $("#hiddenIDApp").val(selectedObj.value);
                $("#hiddenID").val(selectedObj.value);
                $("#hiddenIDADMIN").val(selectedObj.value);
                $(selector).removeClass('errorBox');
                return false;
            },
            change:function( event, ui ) {
                var data=$.data(this);
                if(data.autocomplete.selectedItem==null){
                    $("#hiddenIDApp").val("");
                }
                else{
                    $("#hiddenElementID").val(data.autocomplete.selectedItem.value);
                }
            }
        });
    },
    revokePrivilegeInstructor:function(param){
        return	requestService(PATH_SERVICE_REVOKE_PRIVILEGE_INSTRUCTOR(), param, "GET", true,
        function(result){
        });
    },
    revokePrivilege:function(param){
        return	requestService(PATH_SERVICE_REVOKE_PRIVILEGE(), param, "GET", true,
        function(result){
        });
    },
    evtRevokePrivilege:function(oprId){
        var param={};
        param.oprId=oprId;
        showGenericLoading();
        $.when(organization.revokePrivilege(param)).then(function(result){
            hideGenericLoading();
            if(result.responseInfoJSON.responseCode==1){
                showMessage("The privilege is revoked.");
                organization.includeDefinePrivileges();
            }else if(result.responseInfoJSON.responseCode==2){
                //no posee privilegios
                showMessage("It has no privileges to perform this action.");
            }else if(result.responseInfoJSON.responseCode==3){
                //organizationProfileRolId invalido
                showMessage("The administrator id does not exist.");
            }else if(result.responseInfoJSON.responseCode==4){
                //no pertenece a la org
                showMessage("Supplied user does not belong to the organization.");
            }else if(result.responseInfoJSON.responseCode==5){
                showMessage("You can not be removed as administrator.");
            }else if(result.responseInfoJSON.responseCode==6){
                //no pertenece a la org
                showMessage("You can not remove the last administrator.");
            }
        },function(){
            redirectToGenericError("organization.evtRevokePrivilege("+oprId+")","We are sorry, an error occurred and failed to save your changes.",true);
        });
    },
    evtRevokePrivilegeInstructors:function(oprId){
        var param={};
        param.oprId=oprId;
        showGenericLoading();
        $.when(organization.revokePrivilegeInstructor(param)).then(function(result){
        hideGenericLoading();
        if(result.responseInfoJSON.responseCode==1){
            showMessage("The privilege is revoked.");
            organization.includeDefineInstructors();
        }else if(result.responseInfoJSON.responseCode==2){
            //no posee privilegios
            showMessage("It has no privileges to perform this action.");
        }else if(result.responseInfoJSON.responseCode==3){
            //organizationProfileRolId invalido
            showMessage("The administrator id does not exist.");
        }else if(result.responseInfoJSON.responseCode==4){
            //no pertenece a la org
            showMessage("Supplied user does not belong to the organization.");
        }else if(result.responseInfoJSON.responseCode==5){
            showMessage("You can not be removed as administrator.");
        }else if(result.responseInfoJSON.responseCode==6){
            //no pertenece a la org
            showMessage("You can not remove the last administrator.");
        }
        },function(){
            redirectToGenericError("organization.evtRevokePrivilegeInstructors("+oprId+")","We are sorry, an error occurred and failed to save your changes.",true);
        });
        },
    grantPrivilege:function(param){
        return requestService(PATH_SERVICE_GRANT_PRIVILEGE(), param, "GET", true,
        function(result){
        });
    },
    grantPrivilegeInstructors:function(param){
        return requestService(PATH_SERVICE_GRANT_PRIVILEGE_INSTRUCTORS(), param, "GET", true,
        function(result){
        });
    },
    evtGrantPrivilege:function(){
        var param={};
        if($("#adminInput").val()!=null && $("#adminInput").val()!=""){
            if ($("#hiddenIDADMIN").val()!=null && $("#hiddenIDADMIN").val()!=""){
                param.profile=$("#hiddenIDADMIN").val();
            }else {
                param.profile = $("#adminInput").val();
            }
            $("#adminInput").css("border", "");
            var hash = generateHash();
            showGenericLoading();
            $.when(organization.grantPrivilege(param)).then(function(result){
                if(hash == currentHash){
                    hideGenericLoading();
                    if(result.responseInfoJSON.responseCode==1){
                        showMessage("Administrator privilege granted.");
                        organization.includeDefinePrivileges();
                        }else if(result.responseInfoJSON.responseCode==2){
                            //no posee privilegios
                            showMessage("It has no privileges to perform this action.");
                        }else if(result.responseInfoJSON.responseCode==3){
                            //no pertenece a la org
                            showMessage("Supplied user does not belong to the organization.");
                        }else if(result.responseInfoJSON.responseCode==4){
                            //ya posee el privilegio
                            showMessage("The user already have this privilege.");
                        }else if(result.responseInfoJSON.responseCode==5){
                            //no existe el perfil
                            showMessage("The user supplied is not registered.");
                        }
                    }
                },function(){
                    if(hash == currentHash)
                    redirectToGenericError("organization.evtGrantPrivilege()","We are sorry, an error occurred and failed to save your changes.",true);
                 });
                }else{
                    $("#adminInput").css("border", "solid 1px red");
                    showMessage("You must select a valid user.");
                }
    },
    evtGrantPrivilegeInstructors:function(){
        var param={};
        if($("#adminInput").val()!=null && $("#adminInput").val()!=""){
            if ($("#hiddenIDADMIN").val()!=null && $("#hiddenIDADMIN").val()!=""){
                param.profile=$("#hiddenIDADMIN").val();
            }else {
                param.profile = $("#adminInput").val();
            }
            $("#adminInput").css("border", "");
            var hash = generateHash();
            showGenericLoading();
            $.when(organization.grantPrivilegeInstructors(param)).then(function(result){
                if(hash == currentHash){
                    hideGenericLoading();
                    if(result.responseInfoJSON.responseCode==1){
                    showMessage("Administrator privilege granted.");
                    organization.includeDefineInstructors();
                    }else if(result.responseInfoJSON.responseCode==2){
                    //no posee privilegios
                    showMessage("It has no privileges to perform this action.");
                    }else if(result.responseInfoJSON.responseCode==3){
                    //no pertenece a la org
                    showMessage("Supplied user does not belong to the organization.");
                    }else if(result.responseInfoJSON.responseCode==4){
                    //ya posee el privilegio
                    showMessage("The user already have this privilege.");
                    }else if(result.responseInfoJSON.responseCode==5){
                    //no existe el perfil
                    showMessage("The user supplied is not registered.");
                    }
                }
            },function(){
                if(hash == currentHash)
                    redirectToGenericError("organization.evtGrantPrivilegeInstructors()","We are sorry, an error occurred and failed to save your changes.",true);
            });
        }else{
            $("#adminInput").css("border", "solid 1px red");
            showMessage("You must select a valid user.");
        }
    },
    evtLoadRequestPayment:function(profiles, courseId){
        courseEnroll.persons = profiles.split(",");
        $.fancybox.close();
        //show payment
        excludeComponent("#content");
        includeComponent("#content",PATH_HTML_COURSEPURCHASE()+"?isCheckoutPage=0&courseId="+courseId+"&profiles="+profiles+"&isEvaluatePage=1",function(){
        });
    },
    payCourseRequest:function(courseId){
        var param = {};
        param.courseId = courseId;
        var listPersonsString = "";
        countPersons = 0;
        $.each(organization.persons,function(id,value){
            listPersonsString += value.mail;
            if(countPersons < organization.persons.length){
                listPersonsString += ",";
            }
            countPersons++;
        });
        param.listOfPersons = listPersonsString;
        param.organizationId = organization.currentOrganization.organizationId;
        requestService(PATH_SERVICE_SAVEPAYMENTORG(), param, "GET", false,
            function(result){
                if(result.responseInfoJSON.responseCode==1){
                    window.location.href = getContextPath() + "/#checkout/" + result.responseInfoJSON.message;
                }else{
                    redirectToGenericError("organization.payCourseRequest("+courseId+")",null,true);
                }
            },function(result){
                redirectToGenericError("organization.payCourseRequest("+courseId+")",null,true);
        });
    },
    persons:[],
    addPerson:function(mail){
        if(mail!=null)
            personMail = mail;
        else
            personMail = $("#addMail").val();
        individualPrice = organization.courseFee;
        html = "";
        var personParams = {};
        personParams.mail = personMail;
        personParams.fee = individualPrice;
        if(personMail != "" && !organization.personExists(personMail)){
            organization.persons.push(personParams);
            html = ''
            + personMail
            + ' '
            + individualPrice + ' ' + organization.currency + ' ' +
            'The number of courses in the internal catalog exceed the limit established for your organization
UPGRADE ACCOUNT 
");
        $("#content").append("");
        excludeComponent("#linkSchedulePopUp");
        includeComponent("#linkSchedulePopUp",PATH_HTML_ADD_EXTERNAL_CLASS()+"?externalCourseId="+externalCourseId,function(){
            showFancyPopup("#linkSchedulePopUpid",function(){});
        });
    },
    showNewApprenticeScheduleClass:function(externalCourseId,externalClassId,classDate,classTime,courseName){
        $.fancybox.close();
        $("#content").append("
");
        $("#content").append("");
        excludeComponent("#linkSchedulePopUp");
        includeComponent("#linkSchedulePopUp",PATH_HTML_ADD_APPRENTICE_EXTERNAL_CLASS()+"?externalCourseId="+externalCourseId+"&organizationId="+organization.currentOrganization.organizationId+"&externalClassId="+externalClassId+"&classDate="+classDate+"&classTime="+classTime+"&courseName="+courseName,function(){
            showFancyPopup("#linkSchedulePopUpid",function(){});
        });
    },
    showExternalEvents:function(externalCourseId){
        $.fancybox.close();
        $("#orgCatalog").hide();
        excludeComponent("#scheduledClasses");
        showGenericLoading();
        includeComponent("#scheduledClasses",PATH_HTML_VIEW_EXTERNAL_EVENTS()+"?externalCourseId="+externalCourseId,
        function(){
            hideGenericLoading();
        });
    },
    createEditExternalClass:function(param){
        return requestService(PATH_SERVICE_CREATE_EDIT_EDIT_EXTERNAL_CLASS(), param, "GET", true,
        function(data) {
        }, function() {
        });
    },
    evtCreateEditExternalClassShedule:function(externalCourseId,externalClassId){
        var param={};
        var startTime="";
        $("#newexternalclassform"+externalClassId).validate();
            if($("#newexternalclassform"+externalClassId).valid()){
                var StartD =$("#dateExtStart"+externalClassId).val();
                var split = StartD.split('/');
                var dateStart = new Date(split[2], split[1] - 1, split[0]); //Y M D
                var timestamp = dateStart.getTime();
                var finishD =$("#dateExtFinishEdit"+externalClassId).val();
                var split = finishD.split('/');
                var dateFinish = new Date(split[2], split[1] - 1, split[0]); //Y M D
                var timestamp = dateFinish.getTime();
                if(dateStart <= dateFinish){
                    $("#dateExtFinishEdit"+externalClassId).removeClass("errorBox");
                    param.externalClassId=externalClassId;
                    param.externalCourseId=externalCourseId;
                    param.numberOfApprentices=$("#numApprenticesExt"+externalClassId).val();
                    param.place=$("#placeExt"+externalClassId).val();
                    param.startDate=$("#dateExtStart"+externalClassId).val();
                    param.finishDate=$("#dateExtFinishEdit"+externalClassId).val();
                    startTime=$("#horaExt"+externalClassId).val();
                    param.startTime=startTime;
                    param.instructor=$("#instructorExt"+externalClassId).val();
                    var hash = generateHash();
                    showGenericLoading();
                    $.when(organization.createEditExternalClass(param)).then(function(data){
                        if(hash == currentHash){
                            hideGenericLoading();
                            if(data.externalClassJSON.responseCode=="1"){
                                $.fancybox.close();
                                $("#scheduledClasses").empty();
                                showMessage("The event was successfully added.");
                                organization.showExternalEvents(externalCourseId);
                            }else{
                                showMessage("The operation could not execute, please try again later");
                            }
                        }
                    },function(){
                        if(hash == currentHash)
                        redirectToGenericError("organization.evtCreateEditExternalClassShedule("+externalCourseId+","+externalClassId+")","We are sorry, an error occurred and failed to save your changes.",true);
                    });
                }else {
                    $("#dateExtFinishEdit"+externalClassId).addClass("errorBox");
                    showMessage("The finish date can not be less than the start date.");
                }
            }
    },
    evtCreateEditExternalClass:function(externalCourseId,externalClassId){
        var param={};
        var startTime="";
        if($("#addextClassForm").valid()){
            var StartD =$("#dateExt").val();
            var split = StartD.split('/');
            var dateStart = new Date(split[2], split[1] - 1, split[0]); //Y M D
            var timestamp = dateStart.getTime();
            var finishD =$("#dateExtFinish").val();
            var split = finishD.split('/');
            var dateFinish = new Date(split[2], split[1] - 1, split[0]); //Y M D
            var timestamp = dateFinish.getTime();
            if(dateStart <= dateFinish){
                $("#dateExtFinish").removeClass("errorBox");
                param.externalClassId=externalClassId;
                param.externalCourseId=externalCourseId;
                param.numberOfApprentices=$("#numApprenticesExt").val();
                param.place=$("#placeExt").val();
                param.startDate=$("#dateExt").val();
                param.finishDate=$("#dateExtFinish").val();
                startTime=$("#horaExt").val();
                param.startTime=startTime;
                param.instructor=$("#instructorExt").val();
                var hash = generateHash();
                showGenericLoading();
                $.when(organization.createEditExternalClass(param)).then(function(data){
                    if(hash == currentHash){
                        hideGenericLoading();
                        if(data.externalClassJSON.responseCode=="1"){
                            $.fancybox.close();
                            $("#scheduledClasses").empty();
                            showMessage("The event was successfully added.");
                            organization.showExternalEvents(externalCourseId);
                        }else{
                            showMessage("The operation could not execute, please try again later");
                        }
                    }
                },function(){
                    if(hash == currentHash)
                    redirectToGenericError("organization.evtCreateEditExternalClass("+externalCourseId+","+externalClassId+")","We are sorry, an error occurred and failed to save your changes.",true);
                });
            }else {
                $("#dateExtFinish").addClass("errorBox");
                showMessage("The finish date can not be less than the start date.");
            }
        }
    },
    agendaChangeRowEvent:function(type,rId, courseId, e){
        var action='';
        var x='';
        if(organization.rowIdListAux.length > 0){
            x='more';
            $(".classDetail"+ organization.rowIdListAux[0]).hide();
            $("#tdClassTitleEvent"+organization.rowIdListAux[0]).addClass('lastBottom');
            action = "organization.agendaChangeRowEvent('"+x+"',"+organization.rowIdListAux[0]+","+organization.courseIdListAux[0]+");";
            $("#titleR"+organization.rowIdListAux[0]).attr("onclick",action);
            x='';
            organization.rowIdListAux=[];
            organization.courseIdListAux=[];
        }
        if(organization.idECListAux.length > 0){
            organization.cancelEditExternalClass(organization.idECListAux[0]);
            organization.idECListAux=[];
        }
        if(type=='more'){
            x='less';
            $(".classDetail"+rId).show();
            $(".classDetail"+rId).css("background","#EDEDED");
            $("#tdClassTitleEvent"+rId).removeClass('lastBottom');
            organization.rowIdListAux.push(rId);
            organization.courseIdListAux.push(courseId);
        }else{
            x='more';
            $(".classDetail"+rId).hide();
            $("#tdClassTitleEvent"+rId).addClass('lastBottom');
        }
        action = "organization.agendaChangeRowEvent('"+x+"',"+rId+","+courseId+");";
        $("#titleR"+rId).attr("onclick",action);
    },
    assistanceChangeRowEvent:function(type,rId, courseId,date,startTime,courseName){
        var action='';
        var x='';
        $.fancybox.close();
        $("#orgCatalog").hide();
        $("#scheduledClasses .profileTable").hide();
        excludeComponent("#scheduledClasses");
        showGenericLoading();
        includeComponent("#scheduledClasses",PATH_HTML_REGISTER_ASSISTENCE_EXTERNAL_EVENTS()+"?externalCourseId="+rId+"&courseId="+courseId+"&date="+date+"&startTime="+startTime+"&courseName="+courseName+"&organizationId="+organization.currentOrganization.organizationId,
        function(){
            hideGenericLoading();
        });
    },
    agendaChangeRow:function(type,rId){
        var html='';
        var x='';
        if(type=='more'){
            x='less';
            html=''+
                    ''+
                        '  '+
                    ' '+
                 ' ';
        $("#rowForclass"+idEC).after(html);
        $("#pencilEditExternalClass"+idEC).click(function(e) {
        });
        $( "#dateExtStart"+idEC ).datepicker({
            minDate:1,
            changeYear: true,
            changeMonth: true,
            yearRange: 'c:c+10',
            showMonthAfterYear: false
        });
        $( "#dateExtFinishEdit"+idEC ).datepicker({
            minDate:1,
            changeYear: true,
            changeMonth: true,
            yearRange: 'c:c+10',
            showMonthAfterYear: false
        });
        validateField("#horaExt"+idEC,7);
    },
    createHtmlSearch:function(courses,type){
        var html="";
        $.each(courses, function(id, course){
            var c = {};
            c.status=0;
            c.courseId=course.courseId;
            c.courseTitle=course.courseTitle;
            c.profileName =course.profileName;
            c.profileLastName =course.profileLastName;
            c.courseEvaluation = course.courseTotalRate;
            c.profileEvaluation = course.setProfileRating;
            c.coursePin = course.coursePin;
            c.courseDescription = course.courseDescription;
            c.profileImage = course.profileImage;
            c.profileLogin = course.profileLogin;
            c.courseImage = course.courseImage;
            c.courseStatus=course.courseStatus;
            c.supplier=course.supplier;
            search.lastResult[c.courseId]=c;
            if(course.courseStatus!=16){
                html+=  "";
                if(type=="planning"){
                    html +="
";
                }else if(type=="needs") {
                    html +="
";
                }
                html +="";
                html +=		"" +
                ""+
                " ";
            }else{
                html +=  "";
                if(type=="planning"){
                    html +="
";
                }else if(type=="needs") {
                    html +="
";
                }
                html +=		"" +
                ""+
                "
"+
                "
"+
                ""+
                ""+
                "  "+
                ""+
                ""+$.trim(c.supplier)+"
"+
                " "+
                " "+
                "
"+
                "
"+
                "
 ";
            }
        });
        html +=  " ";
        return html;
    },
    iniLearnGrid: function(orgId,title) {
        organization.checkCollaboratorsStatusFilter();
        var colNames, colModel, tableWidth,titleBar;
        titleBar =  title;
        if (window.innerWidth >= 768 && window.innerWidth < 992) {
            colNames = [
            "Name",
            "Email",
            "Certificate Load",
            "Certificate Download",
            "idEnrollExt","classId","profileLogin","confirmedAssistance","profileId","profileLastName",
            "Assistance"
            ];
            colModel = [
            { name: "profileName", index: "profileName", width: 190, resizable: false, align: "center"  },
            { name: "profileLogin", index: "profileLogin", width: 150, resizable: false },
            { name: "enrollExtId", index: "enrollExtId", hidden: true, width: 77, resizable: false },
            { name: "externalClassId", index: "externalClassId", hidden: true, width: 78, resizable: false },
            { name: "enrollExtId", index: "enrollExtId", width: 1, hidden: true, resizable: false },
            { name: "externalClassId", index: "externalClassId", width: 1, hidden: true, resizable: false },
            { name: "profileLogin", index: "profileLogin", width: 1, hidden: true, resizable: false },
            { name: "confirmedAssistance", index: "confirmedAssistance", width: 1, hidden: true, resizable: false },
            { name: "profileId", index: "profileId", width: 1, hidden: true, resizable: false },
            { name: "profileLastName", index: "profileLastName", width: 1, hidden: true, resizable: false },
            { name: "confirmedAssistance", index: "confirmedAssistance", width: 170, resizable: false }
            ];
            tableWidth = window.innerWidth - 40;
        } else {
            colNames = [
            "Name",
            "Email",
            "Certificate Load",
            "Certificate Download",
            "idEnrollExt","classId","profileLogin","confirmedAssistance","profileId","profileLastName",
            "Assistance"
            ];
            colModel = [
            { name: "profileName", index: "profileName", width: 400, resizable: false, align: "left" },
            { name: "profileLogin", index: "profileLogin", width: 269, resizable: false },
            { name: "enrollExtId", index: "enrollExtId", hidden: true, width: 230, resizable: false, align: "center" },
            { name: "externalClassId", index: "externalClassId", hidden: true, width: 250, resizable: false, align: "center" },
            { name: "enrollExtId", index: "enrollExtId", width: 1, hidden: true, resizable: false },
            { name: "externalClassId", index: "externalClassId", width: 1, hidden: true, resizable: false },
            { name: "profileLogin", index: "profileLogin", width: 1, hidden: true, resizable: false },
            { name: "confirmedAssistance", index: "confirmedAssistance", width: 1, hidden: true, resizable: false },
            { name: "profileId", index: "profileId", width: 1, hidden: true, resizable: false },
            { name: "profileLastName", index: "profileLastName", width: 1, hidden: true, resizable: false },
            { name: "confirmedAssistance", index: "confirmedAssistance",editable:true, edittype:'checkbox', editoptions: { value:"True:False"},formatter: "checkbox", formatoptions: {disabled : false},width: 319, align: "center"}
            ];
            tableWidth = 900;
        }
        $("#grid").jqGrid({
            url: PATH_SERVICE_GET_ALL_APPRENTICES_ENROLLED_SCHEDULED_CLASS()+'?organizationId='+orgId+'&status='+organization.currentEmployeeStatus,
            datatype: "json",
            colNames: colNames,
            colModel: colModel,
            height: 'auto',
            rowNum:5,
            rowList:[5,10],
            pager: '#pager',
            loadonce:false,
            ignoreCase:true,
            multiselect:false,
            viewrecords: true,
            width: null,
            shrinkToFit: false,
            gridComplete: function () {
            organization.initializeApprenticeTable();
                $(".navtable").hide();
            },
            beforeSelectRow: function(rowid, e) {
                var cbsdis = $("tr#" + rowid + ".jqgrow > td > input.cbox:disabled", grid[0]);
                if (cbsdis.length === 0) {
                    return true;    // allow select the row
                } else {
                    return false;   // not allow select the row
                }
            },
            onSelectAll: function(aRowids,status) {
                $("#showEmployeeHistoryButton").hide();
                if (status) {
                    organization.showUnBlockButton("SHOW");
                    organization.showBlockButton("SHOW");
                    organization.showAreaRolOption("SHOW");
                    var Checkboxes = $("tr.jqgrow > td > input.cbox:disabled", grid[0]);
                    Checkboxes.removeAttr("checked");
                    $("#grid").get(0).p.selarrrow =  $("#grid").find("tr.jqgrow:has(td > input.cbox:checked)").map(function() { return this.id; }).get(); // convert to instance of Array
                } else {
                    organization.showUnBlockButton("HIDE");
                    organization.showBlockButton("HIDE");
                    organization.showAreaRolOption("HIDE");
                }
            },
            jsonReader: {
                repeatitems: false
            },
            onSelectRow: function(id) {
                $("#showEmployeeHistoryButton").hide();
                if (($("#" + id).find('td:eq(2)').html()) == "0") {
                    if ($("#jqg_grid_" + id).is(":checked")) {
                        organization.showResendButton("SHOW");
                    } else if (!$("#jqg_grid_" + id).is(":checked") && jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 0){
                        organization.showResendButton("HIDE");
                        organization.showBlockButton("HIDE");
                        organization.showUnBlockButton("HIDE");
                    }
                } else {
                    if (($("#" + id).find('td:eq(3)').html()) == "1") {
                        if($("#jqg_grid_"+id).is(":checked")){
                            organization.showUnBlockButton("SHOW");
                        } else if (!$("#jqg_grid_" + id).is(":checked") && jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 0) {
                            organization.showBlockButton("HIDE");
                            organization.showUnBlockButton("HIDE");
                            organization.showResendButton("HIDE");
                        }
                    } else if (($("#" + id).find('td:eq(3)').html()) == "2" && jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 0) {
                        organization.showUnBlockButton("SHOW");
                        organization.showBlockButton("SHOW");
                    } else {
                        if ($("#jqg_grid_" + id).is(":checked")) {
                            organization.showBlockButton("SHOW");
                        } else if(!$("#jqg_grid_" + id).is(":checked") && jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 0){
                            organization.showBlockButton("HIDE");
                            organization.showUnBlockButton("HIDE");
                            organization.showResendButton("HIDE");
                        }
                    }
                    if ($("#jqg_grid_" + id).is(":checked")) {
                        organization.showAreaRolOption("SHOW");
                    } else if(!$("#jqg_grid_" + id).is(":checked") && jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 0){
                        organization.showAreaRolOption("HIDE");
                    }
                    if (jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 1) {
                        $("#showEmployeeHistoryButton").show();
                    } else {
                        $("#showEmployeeHistoryButton").hide();
                    }
                }
            }
        });
        $(".ui-jqgrid-bdiv").css('min-height', 'auto');
        $(".ui-icon-circle-triangle-n").css('display', 'none');
        $(".ui-jqgrid-titlebar").css('background', '#69b41b');
        $(".ui-jqgrid-titlebar").css('height', '25px');
        $(".ui-jqgrid-titlebar").css('padding-top', '3px');
        $(".ui-jqgrid-titlebar").css('color', 'white');
        $(".ui-jqgrid-titlebar").css('font-family', 'Arial, Helvetica, sans-serif');
        $(".ui-jqgrid-titlebar").css('font-weight', '700');
        $(".ui-jqgrid-title").css('text-align', 'center');
        $(".ui-jqgrid-title").css('width', '100%');
        $(".ui-jqgrid .ui-jqgrid-title").css('font-size', '12px');
        $(".ui-jqgrid .ui-jqgrid-bdiv").css('overflow','hidden');
        $(".ui-widget-header").css('border', '1px solid #fff');
        $(".ui-corner-top").css('border-top-left-radius', '0px');
        $(".ui-corner-top").css('-webkit-border-top-left-radius', '0px');
        $(".ui-corner-top").css('border-top-right-radius', '0px');
        $(".ui-corner-top").css('-webkit-border-top-right-radius', '0px');
        $(".ui-jqgrid-view").css('border', '0px solid #ccc');
                $(".ui-jqgrid-view").css('width', '100%');
                $("#grid").css('width', '100%');
        $("ui-row-ltr > td").css('border-right', 'solid 1px #fff');
        $("ui-row-ltr > td").css('border-bottom', 'solid 1px #fff');
        $(".ui-widget-content").css('border', 'none');
        $("ui-row-ltr > td").css('background', 'rgb(237, 237, 237)');
        $("ui-row-ltr > td").css('font-family', 'Arial, Helvetica, sans-serif');
        $("ui-row-ltr > td").css('font-size', '12px');
        $("ui-row-ltr > td").css('color', '#666');
        $("ui-row-ltr > td").css('font-weight', '700');
        jQuery("#grid").jqGrid('navGrid','#pager',
        {
            edit: false,
            add: false,
            del: false,
            search: true,
            refresh: true,
                width:null
            },
            {}, // edit options
            {}, // add options
            {}, //del options
            { multipleSearch: false } // search options
        );
        $("#pager_left").css('width', '');
    },
    iniGrid: function(orgId) {
        organization.checkCollaboratorsStatusFilter();
        var colNames, colModel, tableWidth;
        if (window.innerWidth >= 768 && window.innerWidth < 992) {
            colNames = [
                "Id", "confirmed", "blocked",
                "Email",
                "Name",
                "COUNTRY",
                "Area",
                "profileId"
            ];
            colModel = [
                { name: "employeeId", index: "employeeId", width: 1, hidden: true, resizable: false },
                { name: "confirmed", index: "confirmed", width: 1, hidden: true, resizable: false },
                { name: "blocked", index: "blocked", width: 1, hidden: true, resizable: false },
                { name: "profileLogin", index: "profileLogin", width: 190, resizable: false },
                { name: "profile", index: "profile", width: 170, resizable: false },
                { name: "country", index: "country", width: 78, resizable: false },
                { name: "areaName", index: "areaName", width: 98, resizable: false },
                { name: "profileId", index: "profileId", width: 1, hidden: true, resizable: false }
            ];
            tableWidth = window.innerWidth - 40;
        } else {
            colNames = [
            "Id", "confirmed", "blocked",
            "Email",
            "Name",
            "PHONE",
            "COUNTRY",
            "Area",
            "ROLE",
            "profileId"
            ];
            colModel = [
            { name: "employeeId", index: "employeeId", width: 1, hidden: true, resizable: false },
            { name: "confirmed", index: "confirmed", width: 1, hidden: true, resizable: false },
            { name: "blocked", index: "blocked", width: 1, hidden: true, resizable: false },
            { name: "profileLogin", index: "profileLogin", width: 190, resizable: false },
            { name: "profile", index: "profile", width: 170, resizable: false },
            { name: "phone", index: "phone", width: 77, resizable: false },
            { name: "country", index: "country", width: 78, resizable: false },
            { name: "areaName", index: "areaName", width: 98, resizable: false },
            { name: "rolName", index: "rolName", width: 98, resizable: false },
            { name: "profileId", index: "profileId", width: 1, hidden: true, resizable: false }
            ];
            tableWidth = 900;
        }
        $("#grid").jqGrid({
            url: PATH_SERVICE_GET_ALL_ORGANIZATION_EMPLOYEES()+'?organizationId='+orgId+'&status='+organization.currentEmployeeStatus,
            datatype: "json",
            colNames: colNames,
            colModel: colModel,
            height: '100%',
            rowNum:10,
            rowList:[10,20,30],
            pager: '#pager',
            loadonce:false,
            ignoreCase:true,
            multiselect:true,
            viewrecords: true,
            width: tableWidth,
            gridComplete: function () {
                organization.initializeTable();
                $(".navtable").hide();
            },
            beforeSelectRow: function(rowid, e) {
                var cbsdis = $("tr#" + rowid + ".jqgrow > td > input.cbox:disabled", grid[0]);
                if (cbsdis.length === 0) {
                    return true;    // allow select the row
                } else {
                    return false;   // not allow select the row
                }
            },
            onSelectAll: function(aRowids,status) {
                $("#showEmployeeHistoryButton").hide();
                if (status) {
                    organization.showUnBlockButton("SHOW");
                    organization.showBlockButton("SHOW");
                    organization.showAreaRolOption("SHOW");
                    var Checkboxes = $("tr.jqgrow > td > input.cbox:disabled", grid[0]);
                    Checkboxes.removeAttr("checked");
                    $("#grid").get(0).p.selarrrow =  $("#grid").find("tr.jqgrow:has(td > input.cbox:checked)").map(function() { return this.id; }).get(); // convert to instance of Array
                } else {
                    organization.showUnBlockButton("HIDE");
                    organization.showBlockButton("HIDE");
                    organization.showAreaRolOption("HIDE");
                }
            },
            jsonReader: {
                repeatitems: false,
                id: "employeeId"
            },
            onSelectRow: function(id) {
                $("#showEmployeeHistoryButton").hide();
                if (($("#" + id).find('td:eq(2)').html()) == "0") {
                    if ($("#jqg_grid_" + id).is(":checked")) {
                        organization.showResendButton("SHOW");
                    } else if (!$("#jqg_grid_" + id).is(":checked") && jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 0){
                        organization.showResendButton("HIDE");
                        organization.showBlockButton("HIDE");
                        organization.showUnBlockButton("HIDE");
                    }
                } else {
                    if (($("#" + id).find('td:eq(3)').html()) == "1") {
                        if($("#jqg_grid_"+id).is(":checked")){
                            organization.showUnBlockButton("SHOW");
                        } else if (!$("#jqg_grid_" + id).is(":checked") && jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 0) {
                            organization.showBlockButton("HIDE");
                            organization.showUnBlockButton("HIDE");
                            organization.showResendButton("HIDE");
                        }
                    } else if (($("#" + id).find('td:eq(3)').html()) == "2" && jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 0) {
                        organization.showUnBlockButton("SHOW");
                        organization.showBlockButton("SHOW");
                    } else {
                        if ($("#jqg_grid_" + id).is(":checked")) {
                            organization.showBlockButton("SHOW");
                        } else if(!$("#jqg_grid_" + id).is(":checked") && jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 0){
                            organization.showBlockButton("HIDE");
                            organization.showUnBlockButton("HIDE");
                            organization.showResendButton("HIDE");
                        }
                    }
                    if ($("#jqg_grid_" + id).is(":checked")) {
                        organization.showAreaRolOption("SHOW");
                    } else if(!$("#jqg_grid_" + id).is(":checked") && jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 0){
                        organization.showAreaRolOption("HIDE");
                    }
                    if (jQuery("#grid").jqGrid('getGridParam', 'selarrrow').length == 1) {
                        $("#showEmployeeHistoryButton").show();
                    } else {
                        $("#showEmployeeHistoryButton").hide();
                    }
                }
            }
        });
        jQuery("#grid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
        $(".ui-jqgrid-bdiv").css('min-height', '250px');
        jQuery("#grid").jqGrid('navGrid','#pager',
        {
            edit: false,
            add: false,
            del: false,
            search: true,
            refresh: true
        },
            {}, // edit options
            {}, // add options
            {}, //del options
            { multipleSearch: true } // search options
        );
    },
    initializeApprenticeTable: function() {
        var rows = $('#grid').jqGrid('getDataIDs');
        var userIdIndex;
        if (window.innerWidth >= 768 && window.innerWidth < 992) {
            userIdIndex = 5;
        } else {
            userIdIndex = 5;
        }
        for (var i = 0; i < rows.length; i++) {
            var idEnrollExt = i;
            var classId = $("#" + rows[i]).find("td").eq(5).html();
            var profileLogin = $("#" + rows[i]).find("td").eq(6).html();
            var confirmedAssistance = $("#" + rows[i]).find("td").eq(7).html();
            var profileId = $("#" + rows[i]).find("td").eq(8).html();
            var profileName = $("#" + rows[i]).find("td").eq(0).html();
            var profileLastName = $("#" + rows[i]).find("td").eq(9).html();
            $("#" + rows[i]).find("td").eq(0)[0].innerHTML = profileName +' '+profileLastName;
            if(confirmedAssistance > 0){
                $("#" + rows[i]).find("td").eq(10)[0].innerHTML = 'Confirmed ';
            }else{
                $("#" + rows[i]).find("td").eq(10)[0].innerHTML = '' + userName + ' ';
            if (confirmed != 0) {
            $("#" + rows[i]).find("td").eq(4)[0].innerHTML =
            '' + userLogin + ' ';
            }
            var blocked = $("#" + rows[i]).find('td:eq(3)').html();
            if (blocked == "1") {
                $("#" + rows[i]).find("td").css("background-color", "#F6CECE");
                $("#" + rows[i]).find("a").css("background-color", "#F6CECE");
            } else if(blocked == "2") {
                $("#" + rows[i]).find("td").css("background-color", "#FFD1A7");
                $("#" + rows[i]).find("a").css("background-color", "#FFD1A7");
            }
        }
        if (organization.checkCollaboratorsFilters()) {
            organization.restoreCollaboratorsFilters();
            organization.clearCollaboratorsFilters();
        }
    },
    saveCollaboratorsFilters: function() {
        sessionStorage.setItem('status_filter', $('#employeeStatusSelect').val());
        sessionStorage.setItem('email_filter', $('#gs_profileLogin').val());
        sessionStorage.setItem('name_filter', $('#gs_profile').val());
        sessionStorage.setItem('phone_filter', $('#gs_phone').val());
        sessionStorage.setItem('country_filter', $('#gs_country').val());
        sessionStorage.setItem('area_filter', $('#gs_areaName').val());
        sessionStorage.setItem('role_filter', $('#gs_rolName').val());
        sessionStorage.setItem('page', $('#grid').getGridParam('page'));
    },
    updateConfirmedAssistance:function(param){
        return requestService(PATH_SERVICE_UPDATE_CONFIRMED_ASSISTENCE(), param, "GET", true,
        function(data) {
        }, function() {
        });
    },
    registerAssistence: function(idEnrollExt,classId,profileLogin) {
        var param={};
        param.classId=classId;
        param.profileLogin=profileLogin;
        if($('#chk'+idEnrollExt).is(":checked")){
            $('#lbl'+idEnrollExt).text("Confirmed");
            showMessage("Confirmed");
            param.confirmedAssistance=1;
        }else {
            $('#lbl'+idEnrollExt).text("");
            param.confirmedAssistance=0;
        }
        var hash = generateHash();
        showGenericLoading();
        $.when(organization.updateConfirmedAssistance(param)).then(function(data){
            if(hash == currentHash){
                hideGenericLoading();
                if(data.responseInfoJSON.responseCode=="1"){
                }else{
                    showMessage("The operation could not execute, please try again later");
                }
            }
        },
        function(){
        if(hash == currentHash)
            redirectToGenericError("organization.registerAssistence('"+idEnrollExt+"', '"+classId+"',"+profileLogin+")","We are sorry, an error occurred and failed to save your changes.",true);
        });
    },
    uploadCertificate: function(idEnrollExt) {
        if($('#chk'+idEnrollExt).is(":checked")){
            $('#editCertificate'+idEnrollExt).trigger('click');
        }
    },
    downloadCertificate: function(enrollId,profileId) {
        var url = "/platform/DownloadServlet?enrollId="+enrollId+"&fileName=Certificate.pdf&profileId="+profileId;
        if($('#chk'+enrollId).is(":checked")){
            window.location.href  = url;
        }
    },
    restoreCollaboratorsFilters: function() {
        var status = sessionStorage.getItem('status_filter');
        var page = parseInt(sessionStorage.getItem('page'));
        $('#employeeStatusSelect').val(status);
        organization.currentEmployeeStatus = status;
        $('#gs_profileLogin').val(sessionStorage.getItem('email_filter'));
        $('#gs_profile').val(sessionStorage.getItem('name_filter'));
        $('#gs_phone').val(sessionStorage.getItem('phone_filter'));
        $('#gs_country').val(sessionStorage.getItem('country_filter'));
        $('#gs_areaName').val(sessionStorage.getItem('area_filter'));
        $('#gs_rolName').val(sessionStorage.getItem('role_filter'));
        setTimeout(function() {
            $('#grid')[0].triggerToolbar();
            if (page > 1) {
                setTimeout(function() {
                    $('#grid').trigger("reloadGrid",[{ page: page }]);
                }, 1000);
            }
        }, 1000);
    },
    clearCollaboratorsFilters: function() {
        sessionStorage.removeItem('status_filter');
        sessionStorage.removeItem('email_filter');
        sessionStorage.removeItem('name_filter');
        sessionStorage.removeItem('phone_filter');
        sessionStorage.removeItem('country_filter');
        sessionStorage.removeItem('area_filter');
        sessionStorage.removeItem('role_filter');
        sessionStorage.removeItem('page');
    },
    checkCollaboratorsStatusFilter: function() {
        var status = sessionStorage.getItem('status_filter');
        if (status) {
            organization.currentEmployeeStatus = status;
        }
    },
    checkCollaboratorsFilters: function() {
        return sessionStorage.getItem('status_filter')
        || sessionStorage.getItem('email_filter')
        || sessionStorage.getItem('name_filter')
        || sessionStorage.getItem('phone_filter')
        || sessionStorage.getItem('country_filter')
        || sessionStorage.getItem('area_filter')
        || sessionStorage.getItem('role_filter')
        || sessionStorage.getItem('page');
    },
    showBlockButton:function(type){
        if(type=="SHOW"){
            $("#blockButton").show();
        }else if(type=="HIDE"){
            $("#blockButton").hide();
        }
    },
    showUnBlockButton:function(type){
        if(type=="SHOW"){
            $("#unblockButton").show();
        }else if(type=="HIDE"){
            $("#unblockButton").hide();
        }
    },
    showResendButton:function(type){
        if(type=="SHOW"){
            $("#resendButton").show();
        }else if(type=="HIDE"){
            $("#resendButton").hide();
        }
    },
    showAreaRolOption:function(type){
        if(type=="SHOW"){
            $("#setAreaRol").show();
        }else if(type=="HIDE"){
            $("#setAreaRol").hide();
        }
    },
    changeEmployeeStatus:function(param){
        return requestService(PATH_SERVICE_UPDATE_EMPLOYEE_STATUS(), param, "GET", true,
        function(data) {	}, function() {});
    },
    hidePeopleOptions:function(){
        $("#blockButton").hide();
        $("#unblockButton").hide();
        $("#setAreaRol").hide();
    },
    evtChangeEmployeeStatus:function(type){
        var employeesList;
        var employeesString="";
        employeesList = jQuery("#grid").jqGrid('getGridParam','selarrrow');
        if(employeesList.length!=0){
            $.each(employeesList, function(id, value) {
                if(employeesList[id]!=null){
                    employeesString=employeesString+employeesList[id]+",";
                }
            });
            var param={};
            param.employees=employeesString;
            param.status=type;
            var hash = generateHash();
            showGenericLoading();
            $.when(organization.changeEmployeeStatus(param)).then(function(data){
                if(hash == currentHash){
                    hideGenericLoading();
                    if(data.mailInvitationProcess.responseCode=="1"){
                        organization.hidePeopleOptions();
                        organization.includeEmmployeesTable();
                        if(data.mailInvitationProcess.unProcessed!=null){
                            var html="";
                            html+='';
                            $.each(data.mailInvitationProcess.unProcessed, function(id, value) {
                                html+=''+value+'
';
                            organization.showUnProcessedActivation(html);
                        }
                    }
                }
            },function(){
                if(hash == currentHash){
                    hideGenericLoading();
                    redirectToGenericError("organization.evtChangeEmployeeStatus("+type+")","We are sorry, an error occurred and failed to save your changes.",true);
                }
            });
        }else{
            showMessage("You must select at least one person");
        }
    },
    evtResendInvitation:function(){
        //se obtienen todos los colaboradores seleccionados
        var checkedList = jQuery("#grid").jqGrid('getGridParam','selarrrow');
        var aux = 0;
        var param={};
        param.organizationId=organization.currentOrganization.organizationId;
        param.message="";
        param.profile="";
        $.each(checkedList, function(id, value) {
            // se obtienen los colaboradores pendientes por responder
            if(($("#"+value).find('td:eq(2)').html())=="0"){
                if (aux >=1){
                param.profile=param.profile+";";
                aux=0;
                }
                param.profile=param.profile+$("#"+value).find('td:eq(4)').html();
                aux+=1;
            }
          });
        $.when(organization.resendSelectedEmployeeInvitation(param)).then(function(data){
            hideGenericLoading();
            if(data.mailInvitationProcess.responseCode=="1"){
                showMessage("The request has been processed.");
            }else if(data.mailInvitationProcess.responseCode=="2"){
                showMessage("You has no privilege to do this action");
            }else if(data.mailInvitationProcess.responseCode=="0"){
                showMessage("Failed to send mail registration, please check and try again later.");
            }else if(data.mailInvitationProcess.responseCode=="7"){
                showMessage("Failed to send mail registration");
            }
        },function(){
            redirectToGenericError("organization.evtResendInvitation()","We are sorry, an error occurred and failed to save your changes.",false);
                     });
                 },
                 showUnProcessedActivation:function(html){
                     $("#content").append("
");
                     $("#content").append("
");
        $("#content").append("");
        excludeComponent("#editOrgPopup");
        includeComponent("#editOrgPopup",PATH_JSP_EDIT_ORG()+"?organizationId="+organizationId,function(){
            showFancyPopup("#editOrgPopupLink",function(){});
        });
    },
    editOrganization:function(param){
        return requestService(PATH_SERVICE_EDIT_ORGANIZATION(), param, "GET", true,
        function(data) {	}, function() {});
    },
    evtEditOrganization:function(){
        var hash = generateHash();
        if($("#orgEdit").valid()){
            var param = {};
            param.name=$("#orgName").val();
            param.description=$("#editOrgDescription").val();
            param.industryId=$('#orgIndustry option:selected').val();
            param.countryId=$('#orgCountry option:selected').val();
            param.phoneNumber=$("#orgPhone").val();
            param.organizationId=organization.currentOrganization.organizationId;
            showGenericLoading();
            $.when(organization.editOrganization(param)).then(function(data){
                if(hash == currentHash){
                    hideGenericLoading();
                    $("#orgNamediv").html(param.name);
                    $("#orgCountrydiv").html(data.organizationJSON.countryName);
                    $("#orgPhonediv").html(param.phoneNumber);
                }
            },function(){
                if(hash == currentHash){
                    hideGenericLoading();
                    redirectToGenericError("organization.evtEditOrganization()","We are sorry, an error occurred and failed to save your changes.",true);
                }
            });
        }
    },
    addDomainOrg:function(param){
        return requestService(PATH_SERVICE_ADD_NEW_DOMAIN(), param, "GET", true,
        function(data) {}, function() {});
    },
    addCategorieOrg:function(param){
        return requestService(PATH_SERVICE_ADD_NEW_CATEGORY(), param, "GET", true,
        function(data) {}, function() {});
    },
    evtAddOrgDomain:function(){
        var hash = generateHash();
        if($("#formNewDomain").valid()){
            var param = {};
            var domain=$("#orgDomain").val();
            param.domain=domain;
            param.organizationId=organization.currentOrganization.organizationId;
            var dom=domain.substring(1);
            dom=dom.replace(".","");
            $.when(organization.addDomainOrg(param)).then(function(data){
                if(hash == currentHash){
                    if(data.responseInfoJSON.responseCode==1){
                        var html='';
                        $("#domainContentTd").append(html);
                        $("#orgDomain").val("");
                    }else if(data.responseInfoJSON.responseCode==3){
                        showMessage(""+domain+" is not allowed for being a public domain");
                        $("#orgDomain").val("").focus();
                    }else{
                        showMessage("We are sorry, an error occurred and failed to save your changes.");
                    }
                }
            },function(){
                if(hash == currentHash){
                    hideGenericLoading();
                    redirectToGenericError("organization.evtEditOrganization()","We are sorry, an error occurred and failed to save your changes.",true);
                }
            });
        }
    },
    evtAddOrgCategorie:function(){
        var hash = generateHash();
        var idTr = '';
        $("#formNewCategory #orgCategory").removeClass("error");
        var category = $("#orgCategory").val();
        if(category != '' && category.trim().length >=1 ){
            var param = {};
            param.category = category;
            param.organizationId = organization.currentOrganization.organizationId;
            $.when(organization.addCategorieOrg(param)).then(function(data){
                if(hash == currentHash){
                    if(data.responseInfoJSON.responseCode >= 1){
                            idTr = category.replace(" ","-");
                        var html='';
                        $("#categoryContentTd").append(html);
                        $("#orgCategory").val("");
                    }else{
                        showMessage("We are sorry, an error occurred and failed to save your changes.");
                    }
                }
            },function(){
                if(hash == currentHash){
                    hideGenericLoading();
                    redirectToGenericError("organization.evtAddOrgCategorie()","We are sorry, an error occurred and failed to save your changes.",true);
                }
            });
        }else{
$("#formNewCategory #orgCategory").addClass("error");
        }
    },
    deleteDomainOrg:function(param){
        return requestService(PATH_SERVICE_DELETE_DOMAIN(), param, "GET", true,
        function(data) {	}, function() {});
    },
    deleteCategorieOrg:function(param){
        return requestService(PATH_SERVICE_DELETE_CATEGORY(), param, "GET", true,
        function(data) {	}, function() {});
    },
    evtDeleteOrgDomain:function(domain){
        var hash = generateHash();
        var param = {};
        param.domain=domain;
        param.organizationId=organization.currentOrganization.organizationId;
        var dom=domain.substring(1);
        dom=dom.replace(".","");
        $.when(organization.deleteDomainOrg(param)).then(function(data){
            if(hash == currentHash){
                if(data.responseInfoJSON.responseCode==1){
                    $("#"+dom).remove();
                }else if(data.responseInfoJSON.responseCode==2){
                    showMessage("Can not remove the last domain associated with the account");
                }else if(data.responseInfoJSON.responseCode==0){
                    showMessage("We are sorry, an error occurred and failed to save your changes.");
                }
            }
        },function(){
            if(hash == currentHash){
                hideGenericLoading();
                redirectToGenericError("organization.evtDeleteOrgDomain('+domain+')","We are sorry, an error occurred and failed to save your changes.",true);
            }
        });
    },
    evtDeleteOrgCategorie:function(category){
        var hash = generateHash();
        var idTr = category.replace(" ","-");
        var param = {};
        param.category = category;
        param.organizationId = organization.currentOrganization.organizationId;
        $.when(organization.deleteCategorieOrg(param)).then(function(data){
            if(hash == currentHash){
                if(data.responseInfoJSON.responseCode==1){
                    $("#"+idTr).remove();
                }else if(data.responseInfoJSON.responseCode==0){
                    showMessage("We are sorry, an error occurred and failed to save your changes.");
                }
            }
        },function(){
            if(hash == currentHash){
                hideGenericLoading();
                redirectToGenericError("organization.evtDeleteOrgCategorie('+category+')","We are sorry, an error occurred and failed to save your changes.",true);
            }
        });
    },
    evtEmployeePreview:function(profile){
        $.fancybox.close();
        excludeComponent("#employeePreviewPopup");
        $("#content").append("
");
        $("#content").append("");
        includeComponent("#employeePreviewPopup",PATH_JSP_EMPLOYEEPREVIEW()+"?organizationId="+organization.currentOrganization.organizationId+"&profile="+profile,function(){
            showFancyPopup("#employeePreviewPopupLink",function(){});
        });
    },
    showHtmlEmployeeRole:function(idE,stringDate,sDate, fDate,areaN, roleN, areaId,roleId, profile){
        var html=''+stringDate+'
'+areaN+'
'+roleN+'
'+
        '
'+
        'Start date: '+
        '
'+
        '
'+
        'Finish date: '+
        '
'+
        '
'+
        '
'+
        '
'+
        '
'+
        '
'+
        ''+
        'Select an area';
        $.each(organization.organizationAreas, function(id, value) {
            if(value.areaId==areaId){
                html+=' '+value.name+' ';
            }else{
                html+=''+value.name+' ';
            }
        });
        html+=' '+
        '
'+
        '
'+
        ''+
        'Select a role';
        $.each(organization.organizationRoles, function(id, value) {
            if(value.employeeRolId==roleId){
                html+=' '+value.name+' ';
            }else{
                html+=''+value.name+' ';
            }
        });
        html+=' '+
        '
'+
        '
'+
        'SAVE CANCEL '+
        '
'+
        '
'+value.profile_name+' '+value.profile_last_name+' '+actionLabel+' '+value.course_title+' '+actionDate+'
  
 ';
                htmlContent += '
'+"Pending corrections on"+" "+value.course_title+" "+"since"+ " "+convertDate(value.pending_since,'en')+'