var app = ons.bootstrap("g-board", ["500tech.simple-calendar", "ngDraggable", "chart.js", '720kb.tooltips', 'luegg.directives', 'ngTagsInput', 'ngSanitize',
    'gantt.sortable',
    'gantt.movable',
    'gantt.drawtask',
    'gantt.tooltips',
    'gantt.bounds',
    'gantt.progress',
    "ngFileUpload",
    'gantt.table',
    'gantt.tree',
    'gantt.groups',
    'gantt.resizeSensor'
]);

app.directive("selectNgFiles", function () {
    return {
        require: "ngModel",
        link: function postLink(scope, elem, attrs, ngModel) {
            elem.on("change", function (e) {
                var files = elem[0].files;
                ngModel.$setViewValue(files);
            })
        }
    }
});

app.filter('unique', function () {
    // we will return a function which will take in a collection
    // and a keyname
    return function (collection, keyname) {
        // we define our output and keys array;
        var output = [],
            keys = [];

        // we utilize angular's foreach function
        // this takes in our original collection and an iterator function
        angular.forEach(collection, function (item) {
            // we check to see whether our object exists
            var key = item[keyname];
            // if it's not already part of our keys array
            if (keys.indexOf(key) === -1) {
                // add it to our keys array
                keys.push(key);
                // push this item to our final output array
                output.push(item);
            }
        });
        // return our array which should be devoid of
        // any duplicates
        return output;
    };
});

app.filter("reverse", function () {
    return function (items) {
        return items.slice().reverse();
    };
});

app.filter('linkyWithHtml', function ($filter) {
    return function (value) {
        var linked = $filter('linky')(value);
        var replaced = linked.replace(/\&gt;/g, '>').replace(/\&lt;/g, '<');
        return replaced;
    };
});

app.config(function ($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
        'self',
        'https://www.youtube.com/**',
        'https://docs.google.com/**'
    ]);
});

app.filter('split', function () {
    return function (input, splitChar, splitIndex) {
        // do some bounds checking here to ensure it has that index
        return input.split(splitChar)[splitIndex];
    }
});

app.directive('ngFileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var model = $parse(attrs.ngFileModel);
            var isMultiple = attrs.multiple;
            var modelSetter = model.assign;
            element.bind('change', function () {
                var values = [];
                angular.forEach(element[0].files, function (item) {
                    var value = {
                        // File Name
                        name: item.name,
                        //File Size
                        size: item.size,
                        //File URL to view
                        url: URL.createObjectURL(item),
                        // File Input Value
                        _file: item
                    };
                    values.push(value);
                });
                scope.$apply(function () {
                    if (isMultiple) {
                        modelSetter(scope, values);
                    } else {
                        modelSetter(scope, values[0]);
                    }
                });
            });
        }
    };
}]);

app.directive('ngRightClick', function ($parse) {
    return function (scope, element, attrs) {
        var fn = $parse(attrs.ngRightClick);
        element.bind('contextmenu', function (event) {
            scope.$apply(function () {
                event.preventDefault();
                fn(scope, {
                    $event: event
                });
            });
        });
    };
});

app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

app.directive('enterSubmit', function () {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {

            elem.bind('keydown', function (event) {
                var code = event.keyCode || event.which;

                if (code === 13) {
                    if (!event.shiftKey) {
                        event.preventDefault();
                        scope.$apply(attrs.enterSubmit);
                    }
                }
            });
        }
    }
});


app.service('ngCopy', ['$window', function ($window) {
    var body = angular.element($window.document.body);
    var textarea = angular.element('<textarea/>');
    textarea.css({
        position: 'fixed',
        opacity: '0'
    });

    return function (toCopy) {
        textarea.val(toCopy);
        body.append(textarea);
        textarea[0].select();

        try {
            var successful = document.execCommand('copy');
            if (!successful) throw successful;
        } catch (err) {
            window.prompt("Copy to clipboard: Ctrl+C, Enter", toCopy);
        }

        textarea.remove();
    }
}]);

app.directive('ngClickCopy', ['ngCopy', function (ngCopy) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind('click', function (e) {
                ngCopy(attrs.ngClickCopy);
            });
        }
    }
}]);

app.service("$dom", function ($q, $http) {
    var arbol = [];
    var tickets = [];
    var areas = [];
    var userStudio = {};
    var selected = {};
    var user = {};
    var tag = "";
    var server = "../..";
    var ganttNode = {};
    return {
        getServer: function () {
            return server;
            //return "http://board.genniux.net";
        },
        getUser: function () {
            return user;
        },
        setUser: function (u) {
            user = u;
        },
        getArbol: function () {
            return arbol;
        },
        setArbol: function (a) {
            arbol = a;
        },
        getTag: function () {
            return tag;
        },
        setTag: function (t) {
            tag = t;
        },
        getTickets: function () {
            return tickets;
        },
        setTickets: function (t) {
            tickets = t;
        },
        getAreas: function () {
            return areas;
        },
        setAreas: function (a) {
            areas = a;
        },
        getSelected: function () {
            return selected;
        },
        setSelected: function (s) {
            var sel = s;
            var deferred = $q.defer();

            sel.tmpComment = {
                id: "",
                activity_id: "",
                autor: "",
                comment: "",
                date: "",
                hour: "",
                editado: false,
                respuesta: null,
                status: "pendiente"
            };
            $http.get(server + "/php/specsAPI/consultaSpec.php?user=" + user.usuario + "&id=" + s.id).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel.specs = dt.data.detail;
                } else {
                    sel.specs = [];
                }
                $http.get(server + "/php/comment/consultaComment.php?user=" + user.usuario + "&activity_id=" + s.id + "&reverse=true").then(function (dc) {
                    console.log(JSON.stringify(dc.data));
                    if (dc.data.status == "OK") {
                        sel.comments = dc.data.detail;
                    } else {
                        sel.comments = [];
                    }
                    $http.get(server + "/php2alex/files/getFiles.php?id=" + s.id).then(function (df) {
                        //console.log(df);
                        sel.files = df.data;
                        $http
                            .get(
                                server + "/php/resources/getResources.php?id=" + s.id
                            )
                            .then(function (df) {
                                //console.log(df);
                                sel.resources = df.data.detail;
                                selected = sel;
                                deferred.resolve(selected);
                            });
                    });
                });
            });
            return deferred.promise;
        },
        setGanttNode: function (nodo) {
            console.log(JSON.stringify(nodo));
            ganttNode = nodo;
        },
        getGanttNode: function () {
            return ganttNode;
        },
        getUsuarios: function (s, c) {
            var deferred = $q.defer();
            $http.get(s + "/php/getUsersFromOrigin.php?origin=" + c).then(function (d) {
                deferred.resolve(d.data.detail);
            });
            return deferred.promise;
        },
        getUsers: function (origin) {
            var sel = [];
            var deferred = $q.defer();
            $http.get(server + "/php/getUsersFromOrigin.php?origin=" + origin).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt.data.detail);
                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },
        addUser: function (wikiname, origen, type, pass, email) {
            var sel = [];
            var deferred = $q.defer();
            $http.get(server + "/php/addUser.php?wikiname=" + wikiname + "&origen=" + origen + "&type=" + type + "&pass=" + pass + "&email=" + email).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt.data.detail);
                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },
        addUserTablero: function (obj) {
            var deferred = $q.defer();
            /*
wikiname
origen
type
pass
email
*/
            var objEnviar = {
                wikiname: encodeURIComponent(obj.wikiname),
                origen: encodeURIComponent(obj.origen),
                type: encodeURIComponent(obj.type),
                pass: encodeURIComponent(obj.pass),
                email: encodeURIComponent(obj.email)
            };
            console.log(objEnviar);


            $http({
                method: "POST",
                url: server + "/php/users/addUserTablero.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.comercio=decodeURIComponent(obj.comercio);
                deferred.resolve(response);
            });
            return deferred.promise;
        },


        removeUser: function (wikiname) {
            var sel = [];
            var deferred = $q.defer();
            $http.get(server + "/php/removeUser.php?wikiname=" + wikiname).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt.data.detail);
                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },
        getTickets: function (cuenta) {
            var sel = [];
            var deferred = $q.defer();
            $http.get(server + "/php/support/getTickets.php?cuenta=" + cuenta).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt.data.detail);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },
        getActividades: function (origen) {

            var sel = [];
            var deferred = $q.defer();
            $http.get(server + "/php/GetNumActTerUser.php?origen=" + origen).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt.data.detail);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },

        setStatus: function (id, estatus, tipo) {
            var sel = [];
            var deferred = $q.defer();
            console.log(id + estatus + tipo);
            $http.get(server + "/php/UpdateStudio.php?id=" + id + "&estatus=" + encodeURIComponent(estatus) + "&tipo=" + tipo).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt.data.detail);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },
        setHora: function (id, estatus, tipo, fecha_fin) {
            var sel = [];
            var deferred = $q.defer();
            console.log(id + estatus + tipo);
            $http.get(server + "/php/UpdateStudio.php?id=" + id + "&estatus=" + encodeURIComponent(estatus) + "&tipo=" + tipo + "&fecha_fin=" + fecha_fin).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt.data.detail);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },
        setFecha: function (id, estatus, tipo, fecha_real) {
            var sel = [];
            var deferred = $q.defer();
            console.log(id + estatus + tipo + "----" + fecha_real);
            $http.get(server + "/php/UpdateStudio.php?id=" + id + "&estatus=" + encodeURIComponent(estatus) + "&tipo=" + tipo + "&fecha_real=" + encodeURIComponent(fecha_real)).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },
        setFecha2: function (id, estatus, tipo, fecha_real) {
            var sel = [];
            var deferred = $q.defer();
            console.log(id + estatus + tipo + "----" + fecha_real);
            $http.get(server + "/php/UpdateStudio.php?id=" + id + "&estatus=" + encodeURIComponent(estatus) + "&tipo=" + tipo + "&fecha_inicio=" + encodeURIComponent(fecha_real)).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },
        setFechaCheck: function (id, estatus, tipo, fecha_real) {
            var sel = [];
            var deferred = $q.defer();
            console.log(id + estatus + tipo + "----" + fecha_real);
            $http.get(server + "/php/UpdateStudio.php?id=" + id + "&estatus=" + encodeURIComponent(estatus) + "&tipo=" + tipo + "&fecha_real=" + encodeURIComponent(fecha_real)).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },
        addUserEmail: function (email, wikiname) {
            var sel = [];
            console.log(email);
            var deferred = $q.defer();
            $http.get(server + "/php/addUserEmail.php?email=" + encodeURIComponent(email) + "&wikiname=" + encodeURIComponent(wikiname)).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },

        myUser: function (wikiname) {
            var sel = [];
            var deferred = $q.defer();
            $http.get(server + "/php/obtenerUser.php?wikiname=" + encodeURIComponent(wikiname)).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },

        myUser: function (wikiname) {
            var sel = [];
            var deferred = $q.defer();
            $http.get(server + "/php/obtenerUser.php?wikiname=" + encodeURIComponent(wikiname)).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },
        addCuentaAsociada: function (id, cuenta_asociada) {
            var sel = [];
            var deferred = $q.defer();
            $http.get(server + "/php/addCuentaAsociada.php?id=" + encodeURIComponent(id) + "&cuenta_asociada=" + encodeURIComponent(cuenta_asociada)).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },

        addEvento: function (id_puesto, id_act, estatus, id_cuenta) {
            var sel = [];
            console.log(id_puesto);
            var deferred = $q.defer();
            $http.get(server + "/php/insertEvent.php?id_puesto=" + encodeURIComponent(id_puesto) + "&id_act=" + encodeURIComponent(id_act) + "&estatus=" + encodeURIComponent(estatus) + "&id_cuenta=" + encodeURIComponent(id_cuenta)).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },

        obtenerEventos: function (id_puesto) {
            var sel = [];
            console.log(id_puesto);
            var deferred = $q.defer();
            $http.get(server + "/php/obtenerEventos.php?id_puesto=" + encodeURIComponent(id_puesto)).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },

        EliminarEvento: function (id_act, id_puesto, estatus) {
            var sel = [];
            console.log(id_act);
            console.log(id_puesto);
            console.log(estatus);
            var deferred = $q.defer();
            $http.get(server + "/php/EliminarEvento.php?id_act=" + encodeURIComponent(id_act) + "&id_puesto=" + encodeURIComponent(id_puesto) + "&estatus=" + encodeURIComponent(estatus)).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },


        CambiarUrlImg: function (id, url) {
            var sel = [];
            var deferred = $q.defer();

            sel = [];
            document.getElementById("" + id).removeAttribute("src");
            var MiCar = document.getElementById("" + id);
            MiCar.setAttribute("src", "" + url);

            deferred.resolve(sel);

            return deferred.promise;
        },

        UpdateActStudio: function (obj) {
            var deferred = $q.defer();
            console.log(obj);

            obj.avance = encodeURIComponent(obj.avance);
            obj.check = obj.check;
            obj.colorNumber = encodeURIComponent(obj.colorNumber);
            obj.colorStatus = encodeURIComponent(obj.colorStatus);
            obj.comentarios = encodeURIComponent(obj.comentarios);
            obj.cuenta = encodeURIComponent(obj.cuenta);
            obj.descripcion = encodeURIComponent(obj.descripcion);
            obj.eje = encodeURIComponent(obj.eje);
            obj.encargado_ahora = encodeURIComponent(obj.encargado_ahora);
            obj.estatus = encodeURIComponent(obj.estatus);
            obj.estimacion = encodeURIComponent(obj.estimacion);
            obj.fecha_fin = encodeURIComponent(obj.fecha_fin);
            obj.fecha_inicio = encodeURIComponent(obj.fecha_inicio);
            obj.fecha_real = encodeURIComponent(obj.fecha_real);
            obj.hijos = encodeURIComponent(obj.hijos);
            obj.hour = encodeURIComponent(obj.hour);
            obj.id = encodeURIComponent(obj.id);
            obj.link = encodeURIComponent(obj.link);
            obj.metrica = encodeURIComponent(obj.metrica);
            obj.newActivity = encodeURIComponent(obj.newActivity);
            obj.newComment = encodeURIComponent(obj.newComment);
            obj.newSpec = encodeURIComponent(obj.newSpec);
            obj.next_step = encodeURIComponent(obj.next_step);
            obj.padre = encodeURIComponent(obj.padre);
            obj.padre_titulo = encodeURIComponent(obj.padre_titulo);
            obj.prioridad = encodeURIComponent(obj.prioridad);
            obj.prioridad_num = encodeURIComponent(obj.prioridad_num);
            obj.responsable_1 = encodeURIComponent(obj.responsable_1);
            obj.responsable_2 = encodeURIComponent(obj.responsable_2);
            obj.specs = encodeURIComponent(obj.specs);
            obj.timing = encodeURIComponent(obj.timing);
            obj.tipo = encodeURIComponent(obj.tipo);
            obj.titulo = encodeURIComponent(obj.titulo);
            obj.topico = encodeURIComponent(obj.topico);

            $http({
                method: "POST",
                url: server + "/php/actualizarStudioObj.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                obj.avance = decodeURIComponent(obj.avance);
                //obj.check=Boolean(decodeURIComponent(obj.check));
                obj.colorNumber = decodeURIComponent(obj.colorNumber);
                obj.colorStatus = decodeURIComponent(obj.colorStatus);
                obj.comentarios = decodeURIComponent(obj.comentarios);
                obj.cuenta = decodeURIComponent(obj.cuenta);
                obj.descripcion = decodeURIComponent(obj.descripcion);
                obj.eje = decodeURIComponent(obj.eje);
                obj.encargado_ahora = decodeURIComponent(obj.encargado_ahora);
                obj.estatus = decodeURIComponent(obj.estatus);
                obj.estimacion = decodeURIComponent(obj.estimacion);
                obj.fecha_fin = decodeURIComponent(obj.fecha_fin);
                obj.fecha_inicio = decodeURIComponent(obj.fecha_inicio);
                obj.fecha_real = decodeURIComponent(obj.fecha_real);
                obj.hijos = decodeURIComponent(obj.hijos);
                obj.hour = decodeURIComponent(obj.hour);
                obj.id = decodeURIComponent(obj.id);
                obj.link = decodeURIComponent(obj.link);
                obj.metrica = decodeURIComponent(obj.metrica);
                obj.newActivity = decodeURIComponent(obj.newActivity);
                obj.newComment = decodeURIComponent(obj.newComment);
                obj.newSpec = decodeURIComponent(obj.newSpec);
                obj.next_step = decodeURIComponent(obj.next_step);
                obj.padre = decodeURIComponent(obj.padre);
                obj.padre_titulo = decodeURIComponent(obj.padre_titulo);
                obj.prioridad = decodeURIComponent(obj.prioridad);
                obj.prioridad_num = decodeURIComponent(obj.prioridad_num);
                obj.responsable_1 = decodeURIComponent(obj.responsable_1);
                obj.responsable_2 = decodeURIComponent(obj.responsable_2);
                obj.specs = decodeURIComponent(obj.specs);
                obj.timing = decodeURIComponent(obj.timing);
                obj.tipo = decodeURIComponent(obj.tipo);
                obj.titulo = decodeURIComponent(obj.titulo);
                obj.topico = decodeURIComponent(obj.topico);

                deferred.resolve(response);
            });
            return deferred.promise;
        },

        setUserStudioEdit: function (u) {
            userStudio = u;
        },

        getUserStudioEdit: function () {
            return userStudio;
        },

        EliminarActStudio: function (id_act) {
            var sel = [];
            console.log(id_act);
            var deferred = $q.defer();
            $http.get(server + "/php/EliminarActStudio.php?id_act=" + encodeURIComponent(id_act)).then(function (dt) {
                if (dt.data.status == "OK") {
                    sel = dt.data.detail;
                } else {
                    sel = [];
                }
                console.log(dt);

                deferred.resolve(dt.data.detail);
            });
            return deferred.promise;
        },


        getPlanUsuarios: function (obj) {
            var deferred = $q.defer();
            /*
            cuenta
            responsable_1
            responsable_2
            encargado_ahora
            */
            var objEnviar = {
                cuenta: encodeURIComponent(obj.cuenta),
                responsable_1: encodeURIComponent(obj.responsable_1),
                responsable_2: encodeURIComponent(obj.responsable_2),
                encargado_ahora: encodeURIComponent(obj.encargado_ahora)
            };
            console.log(objEnviar);


            $http({
                method: "POST",
                url: server + "/php/bitacoras/getPlanUsuariosStudio.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.comercio=decodeURIComponent(obj.comercio);
                deferred.resolve(response.data.detail);
            });
            return deferred.promise;
        },




        getSpecsAE: function (obj) {
            var deferred = $q.defer();
            /*
            cuenta
            responsable_1
            responsable_2
            encargado_ahora
            */
            var objEnviar = {
                id_actividadE: encodeURIComponent(obj.id_actividadE)
            };
            console.log(objEnviar);


            $http({
                method: "POST",
                url: server + "/php/bitacoras/getSpecsAE.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.comercio=decodeURIComponent(obj.comercio);
                deferred.resolve(response.data);
            });
            return deferred.promise;
        },



        updateCheckSpec: function (obj) {
            var deferred = $q.defer();
            /*
            id_spec
            actividad_estatus
            */
            var objEnviar = {
                id_spec: encodeURIComponent(obj.id_spec),
                actividad_estatus: encodeURIComponent(obj.actividad_estatus)
            };
            console.log(objEnviar);


            $http({
                method: "POST",
                url: server + "/php/bitacoras/updateCheckSpec.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.comercio=decodeURIComponent(obj.comercio);
                deferred.resolve(response.data.detail);
            });
            return deferred.promise;
        },



        updateCheckIndividualAE: function (obj) {
            var deferred = $q.defer();
            /*
            id_entregable
            actividad_estatus
            */
            var objEnviar = {
                id_entregable: encodeURIComponent(obj.id_entregable),
                actividad_estatus: encodeURIComponent(obj.actividad_estatus)
            };
            console.log(objEnviar);


            $http({
                method: "POST",
                url: server + "/php/bitacoras/updateCheckIndividualAE.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.comercio=decodeURIComponent(obj.comercio);
                deferred.resolve(response.data.detail);
            });
            return deferred.promise;
        },


        updateFechaFinAE: function (obj) {
            var deferred = $q.defer();
            /*
            id_entregable
            fecha_inicio
            */
            var objEnviar = {
                id_entregable: encodeURIComponent(obj.id_entregable),
                fecha_fin: (obj.fecha_fin)
            };
            console.log(objEnviar);


            $http({
                method: "POST",
                url: server + "/php/bitacoras/updateFechaFinAE.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.comercio=decodeURIComponent(obj.comercio);
                deferred.resolve(response.data.detail);
            });
            return deferred.promise;
        },



        updateFechaInicioAE: function (obj) {
            var deferred = $q.defer();
            /*
            id_entregable
            fecha_inicio
            */
            var objEnviar = {
                id_entregable: encodeURIComponent(obj.id_entregable),
                fecha_inicio: (obj.fecha_inicio)
            };
            console.log(objEnviar);


            $http({
                method: "POST",
                url: server + "/php/bitacoras/updateFechaInicioAE.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.comercio=decodeURIComponent(obj.comercio);
                deferred.resolve(response.data.detail);
            });
            return deferred.promise;
        },



        updateCheckAE: function (obj) {
            var deferred = $q.defer();
            /*
            id_entregable
            actividad_estatus
            */
            var objEnviar = {
                id_entregable: encodeURIComponent(obj.id_entregable),
                actividad_estatus: encodeURIComponent(obj.actividad_estatus)
            };
            console.log(objEnviar);


            $http({
                method: "POST",
                url: server + "/php/bitacoras/updateCheckAE.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.comercio=decodeURIComponent(obj.comercio);
                deferred.resolve(response.data.detail);
            });
            return deferred.promise;
        },







        insertarPlay: function (obj) {
            var deferred = $q.defer();

            obj.id_user = encodeURIComponent(obj.id_user);
            obj.token = encodeURIComponent(obj.token);
            obj.app = encodeURIComponent(obj.app);
            obj.estatus = encodeURIComponent(obj.estatus);

            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/onesignal/insertarPlay.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.avance=decodeURIComponent(obj.avance);

                deferred.resolve(response);
            });
            return deferred.promise;
        },

        updatePlay: function (obj) {
            var deferred = $q.defer();

            obj.id_user = encodeURIComponent(obj.id_user);
            obj.token = encodeURIComponent(obj.token);
            obj.app = encodeURIComponent(obj.app);
            obj.estatus = encodeURIComponent(obj.estatus);

            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/onesignal/updatePlay.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.avance=decodeURIComponent(obj.avance);

                deferred.resolve(response);
            });
            return deferred.promise;
        },





        deletePlay: function (obj) {
            var deferred = $q.defer();

            obj.id_user = encodeURIComponent(obj.id_user);
            obj.token = encodeURIComponent(obj.token);
            obj.app = encodeURIComponent(obj.app);
            obj.status = encodeURIComponent(obj.status);

            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/onesignal/deletePlay.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.avance=decodeURIComponent(obj.avance);

                deferred.resolve(response);
            });
            return deferred.promise;
        },



        enviarNoti: function (obj) {
            var deferred = $q.defer();

            obj.id_user = encodeURIComponent(obj.id_user);
            obj.app = encodeURIComponent(obj.app);
            obj.titulo_act = encodeURIComponent(obj.titulo_act);
            obj.usuario = encodeURIComponent(obj.usuario);
            obj.mensaje = encodeURIComponent(obj.mensaje);

            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/onesignal/enviarNoti.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                //obj.avance=decodeURIComponent(obj.avance);
                //console.log(response);

                deferred.resolve(response);
            });
            return deferred.promise;
        },


        enviarNotiMulti: function (obj) {
            var deferred = $q.defer();

            obj.id_user = encodeURIComponent(obj.id_user);
            obj.app = encodeURIComponent(obj.app);
            obj.titulo_act = encodeURIComponent(obj.titulo_act);
            obj.titulo_cabecera = encodeURIComponent(obj.titulo_cabecera);
            obj.usuario = encodeURIComponent(obj.usuario);
            obj.mensaje = encodeURIComponent(obj.mensaje);

            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/onesignal/enviarNotiMulti.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                //obj.avance=decodeURIComponent(obj.avance);
                //console.log(response);

                deferred.resolve(response);
            });
            return deferred.promise;
        },




        insertarNotificaciones: function (obj) {
            var deferred = $q.defer();
            obj.app = encodeURIComponent(obj.app);

            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/notificaciones/insertarNotificaciones.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.avance=decodeURIComponent(obj.avance);

                deferred.resolve(response);
            });
            return deferred.promise;
        },
        insertarNotificacionesBoardAMiPlan: function (obj) {
            var deferred = $q.defer();
            obj.app = encodeURIComponent(obj.app);
            obj.prioridad = encodeURIComponent(obj.prioridad);
            obj.titulo = encodeURIComponent(obj.titulo);

            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/notificaciones/insertarNotificacionesBoardAMiPlan.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.avance=decodeURIComponent(obj.avance);

                deferred.resolve(response);
            });
            return deferred.promise;
        },


        insertarNotificacionesPunchListenBaord: function (obj) {
            var deferred = $q.defer();
            obj.app = encodeURIComponent(obj.app);
            obj.prioridad = encodeURIComponent(obj.prioridad);
            obj.titulo = encodeURIComponent(obj.titulo);

            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/notificaciones/insertarNotificacionesPunchListenBaord.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.avance=decodeURIComponent(obj.avance);

                deferred.resolve(response);
            });
            return deferred.promise;
        },



        getNotificaciones: function (obj) {
            var deferred = $q.defer();
            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/notificaciones/getNotificaciones.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.avance=decodeURIComponent(obj.avance);

                deferred.resolve(response);
            });
            return deferred.promise;
        },


        getpermisos: function (obj) {
            var deferred = $q.defer();
            obj.puesto = "" + user.puesto;
            console.warn(obj);
            $http({
                method: "POST",
                url: server + "/php/notificaciones/getpermisos.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.avance=decodeURIComponent(obj.avance);

                deferred.resolve(response);
            });
            return deferred.promise;
        },


        getNotificacionesContadores: function (obj) {
            var deferred = $q.defer();
            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/notificaciones/getNotificacionesContadores.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.avance=decodeURIComponent(obj.avance);

                deferred.resolve(response);
            });
            return deferred.promise;
        },




        updateNotificacionEstatus: function (obj) {
            var deferred = $q.defer();
            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/notificaciones/updateNotificacionEstatus.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.avance=decodeURIComponent(obj.avance);

                deferred.resolve(response);
            });
            return deferred.promise;
        },





        insertarNotificacionesMiPlanABoard: function (obj) {
            var deferred = $q.defer();
            obj.app = encodeURIComponent(obj.app);
            obj.prioridad = encodeURIComponent(obj.prioridad);
            obj.titulo = encodeURIComponent(obj.titulo);

            console.log(obj);
            $http({
                method: "POST",
                url: server + "/php/notificaciones/insertarNotificacionesMiPlanABoard.php",
                data: obj,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                //obj.avance=decodeURIComponent(obj.avance);

                deferred.resolve(response);
            });
            return deferred.promise;
        },







        getEjes: function (obj) {
            var deferred = $q.defer();

            var objEnviar = {
                id: encodeURIComponent(obj.id)
            };
            console.log(objEnviar);
            $http({
                method: "POST",
                url: server + "/php/pap/getEjes.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                deferred.resolve(response);
            });
            return deferred.promise;
        },







        getAgendaDia: function (obj) {
            var deferred = $q.defer();

            var objEnviar = {
                cuenta: encodeURIComponent(obj.cuenta),
                user: encodeURIComponent(obj.user),
                fecha_fin: encodeURIComponent(obj.fecha_fin),
                hora: (obj.hora),
                type: (obj.type)
            };
            console.log(objEnviar);
            $http({
                method: "POST",
                url: server + "/php/agenda/getAgendaDia.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                deferred.resolve(response);
            });
            return deferred.promise;
        },


        setFechaAgenda: function (obj) {
            var deferred = $q.defer();

            var objEnviar = {
                id: encodeURIComponent(obj.id),
                fecha_fin: encodeURIComponent(obj.fecha_fin),
                hour: encodeURIComponent(obj.hour)
            };
            console.log(objEnviar);
            $http({
                method: "POST",
                url: server + "/php/agenda/setFechaAgenda.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                deferred.resolve(response);
            });
            return deferred.promise;
        },
        getEventosG: function (obj) {
            var deferred = $q.defer();

            var objEnviar = {
                id_user: (obj.id_user)
            };
            console.log(objEnviar);
            $http({
                method: "POST",
                url: server + "/php/google_calendar/getEventosG.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                deferred.resolve(response);
            });
            return deferred.promise;
        },
        addEventoG: function (obj) {
            var deferred = $q.defer();

            var objEnviar = {
                id_act: (obj.id_act),
                id_user: (obj.id_user),
                id_evento: (obj.id_evento)
            };
            console.log(objEnviar);
            $http({
                method: "POST",
                url: server + "/php/google_calendar/addEventoG.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                deferred.resolve(response);
            });
            return deferred.promise;
        },
        deleteG: function (obj) {
            var deferred = $q.defer();

            var objEnviar = {
                id_evento: (obj.id_evento)
            };
            console.log(objEnviar);
            $http({
                method: "POST",
                url: server + "/php/google_calendar/deleteG.php",
                data: objEnviar,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(function (response) {
                console.log(response);
                deferred.resolve(response);
            });
            return deferred.promise;
        },







    }
});

app.controller("MainController", function ($scope, $dom, $http, $location, $anchorScroll, $window, $q, $rootScope, Upload, $timeout) {
    $scope.buscarUser = "";


    $scope.ImagenesUser = function (valor) { // console.log(valor);
        try {


            if (valor === null || valor === "NotSet") {
                var obj = {
                    src: '/img/generic-user.png',
                    val: 'null',
                    ver: true
                };
                return (obj)
            } else {
                //      console.log($scope.usuarios[valor].picture);
                try {
                    if ($scope.usuarios[valor].picture === "" || $scope.usuarios[valor].picture === null) {
                        var valor2 = valor.split("");
                        var iniciales = "";
                        for (var i = 0; i < valor2.length; i++) {
                            //console.log(valor2[i]);
                            if (valor2[i] === valor2[i].toUpperCase()) {
                                iniciales += valor2[i];
                            };
                        };
                        var obj = {
                            src: '' + iniciales,
                            val: valor,
                            ver: false
                        };
                        return (obj)
                    } else {
                        var obj = {
                            src: "/php/imagenes/" + $scope.usuarios[valor].picture,
                            val: valor,
                            ver: true
                        };
                        return (obj)
                    }

                } catch (error) {
                    var obj = {
                        src: '/img/generic-user.png',
                        val: 'null',
                        ver: true
                    };
                    return (obj)
                }
            }
        } catch (error) {
            var obj = {
                src: '/img/generic-user.png',
                val: 'null',
                ver: true
            };
            return (obj)
        }
    }


    //        obj.titulo=encodeURIComponent(obj.titulo);
    //        obj.avance=decodeURIComponent(obj.avance);


    $scope.Redirigir = function (ruta) {
        if (ruta === 'noticias') {
            window.open("https://genniux.net/app/noticias/");
            //window.location.href='http://genniux.net/app/noticias/'
        };
        if (ruta === 'punch') {
            window.open("https://genniux.net/app/punchlist/");
            //window.location.href='https://genniux.net/app/punchlist/'
        };
    };

    $scope.CambiarUser = function (userStudio) {
        $dom.setUserStudioEdit(userStudio);
    }


    $scope.editUserM = function ($event) {
        document.getElementById("miim").removeAttribute("src");
        var MiCar = document.getElementById("miim");
        MiCar.setAttribute("src", "" + $scope.server + "/php/imagenes/" + $scope.usuarios[$scope.sesion.usuario].picture);

        $scope.editUser.show({
            parentScope: $scope
        });

    }


    $scope.editUserO = function (imagen) {

        $scope.editUser.hide();
    }
    $scope.subirImgUser = function (f) {
        //console.log(f);
        $scope.UploadImgUser(1, f, 0, f.length).then(function (resp) {
            console.log("finished");
        });

    };

    $scope.ImgUsrTem = "";
    $scope.Mos = function () {
        $scope.reader = new FileReader();
        $scope.errSub = "";

        try {
            $scope.reader.readAsDataURL($scope.file);
        } catch (error) {
            $scope.errSub = "Favor de seleccionar una imagen.";
            $scope.verOpciones($event);
        }

        $scope.reader.onload = function () {
            //console.log($scope.reader.result);
            // console.log($scope.ImgUsrTem);
            // console.log($scope.$broadcast);
            // $scope.editUser.show();
            $scope.errSub = "";

            //  $scope.miid.click();
        };
        $scope.reader.onerror = function (error) {
            console.log('Error: ', error);
        };

        $scope.reader.onprogress = function (data) {
            console.log(data);

        };
        $scope.reader.onprogress = function (data) {
            //console.log(data);

        };
        $scope.reader.onloadend = function (data) {
            //console.log(data);
            //console.log("terminado");
            $scope.ImgUsrTem = $scope.reader.result;
            //console.log($scope.reader.result);
            $dom.CambiarUrlImg('miim', $scope.reader.result).then(function (data) {
                //$scope.editUser.show();
                try {

                    $scope.verOpciones($event);
                } catch (error) {}
            });
        }
        // console.log($scope.reader);
    }
    $scope.Desague = function () {

    }
    $scope.CancelarEUser = function () {

        $scope.editUser.hide();
    }
    $scope.mostrarloadImg = false;

    $scope.submit = function () {
        // alert();
        //console.log("Entro");
        //console.log($scope.file);
        //console.log($scope.form);
        //console.log($scope.form.file);
        $scope.errSub = "";
        console.log($scope.usuarios);
        console.log($scope.sesion);
        $scope.mostrarloadImg = true;
        //console.log($scope.form.file.$viewValue.name);
        try {
            var tipo_a = $scope.form.file.$viewValue.name;
            var tipo_arr = tipo_a.split('.');
            var tipo_f = tipo_arr[tipo_arr.length - 1];
            if (tipo_f == "png" || tipo_f == "jpg" || tipo_f == "jpeg" || tipo_f == "gif" || tipo_f == "bmp" || tipo_f == "tif") {
                $scope.mos_g_ar = true;
                if ($scope.form.file.$valid && $scope.file) {
                    //$scope.sesion.nombre=$scope.sesion.nombre+"."+tipo_f;
                    var res = $scope.upload2($scope.file, $scope.usuarios[$scope.sesion.nombre].picture, $scope.sesion.nombre);
                    $scope.mos_g_ar = false;
                    return true;
                } else {
                    $scope.mos_g_ar = false;
                }
            } else {
                ons.notification.alert('Favor de seleccionar una imagen. ', {
                    title: "Alerta",
                    buttonLabels: "Confirmar"
                });

                $scope.errSub = "Favor de seleccionar una imagen.";
                $scope.mostrarloadImg = false;
            }
        } catch (err) {}

        return false;
    };

    // upload on file select or drop
    $scope.upload2 = function (file, path, wikiname) {
        Upload.upload({
            url: $scope.server + "/php/addImgUser.php",
            method: 'POST',
            data: {
                file: file,
                'targetPath': path,
                'wikiname': wikiname
            }
        }).then(function (resp) {
            console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
            // $scope.newPrograma.image=''+masterPath+'/xpress/files/files/img/'+resp.config.data.file.name;
            // $scope.usuarios[$scope.sesion.usuario].picture=$scope.ImgUsrTem;
            ons.notification.alert('Imagen actualizada correctamente. Se recargara la pagina para guardar cambios.', {
                title: "Alerta",
                buttonLabels: "Confirmar"
            }).
            then(function (data) {
                console.log("hola");
                //window.location.reload();
                window.location.href = 'http://board.genniux.net/beta/';
                $scope.mostrarloadImg = false;

            });

        }, function (resp) {
            $scope.errSub = "Error al subir el archivo.";
            $scope.mostrarloadImg = false;
            //  console.log('Error status: ' + resp.status);
        }, function (evt) {
            console.log(evt);

            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);

        });
    }



    $scope.getNotificacionesContadores = function (id_user) {
        var obj = {
            id_user: id_user
        };
        $dom.getNotificacionesContadores(obj).then(function (res) {
            console.log(res);
            $scope.totalNotiPunch = res.data.detail;
        });

    }



    $scope.Suscribir = function () {
        console.log($scope.miswithc1);
        console.log($scope.miswithc1._element[0].checked);
        console.log($scope.miswithc1.checked);
        $scope.OneSignal.push(["registerForPushNotifications"]);
        event.preventDefault();
        $scope.miswithc1.checked = false;
    }


    $scope.IniciarPush = function () {


        console.log("iniciando");
        $scope.OneSignal = window.OneSignal || [];
        $scope.valores = [];
        console.log($scope.OneSignal);
        $scope.OneSignal.push(function () {
            $scope.OneSignal.init({
                appId: "658b5bd8-f108-4a3a-9bc1-596d32bedaa2",
                autoRegister: false,
                /* Set to true to automatically prompt visitors */
                httpPermissionRequest: {
                    enable: true
                },
                notifyButton: {
                    enable: false /* Set to false to hide */
                },
                subdomainName: "gbl2.os.tc" /* The label for your site that you added in Site Setup mylabel.os.tc */
                /* appId: "2a9bc69e-8be8-4a77-a9e8-00ad8f08477c",
            autoRegister: true,
             promptOptions: {
                        actionMessage: "¿Deseas mantenerte al tanto de tus actividades?.",
                        acceptButtonText: "Aceptar",
                        cancelButtonText: "Cancelar"
                      }*/
            });
            $scope.OneSignal.on('notificationPermissionChange', function (permissionChange) {
                console.log('New permission state:', permissionChange);
                if (permissionChange.to === "granted") {
                    //$scope.miswithc1.checked=true;
                    console.log("Con permiso");
                    //$scope.$apply();
                } else {
                    //$scope.miswithc1.checked=false;
                    //$scope.$apply();
                    console.log("Sin permiso");

                }
            });
            $scope.OneSignal.on('customPromptClick', function (promptClickResult) {
                console.log('HTTP Pop-Up Prompt click result:', promptClickResult);
                if (promptClickResult.result === "granted") {
                    $scope.miswithc1.checked = true;
                    $scope.$apply();
                    console.log("verdadero")
                    $scope.CampanaenLineaContador = 0;

                } else {
                    console.log("Falso");
                    $scope.miswithc1.checked = false;
                    $scope.$apply();
                }
            });

            $scope.OneSignal.push(["getNotificationPermission", function (permission) {
                console.log("Site Notification Permission:", permission);
                // (Output) Site Notification Permission: default
            }]);

            $scope.OneSignal.on('notificationDisplay', function (event) {
                //console.warn('OneSignal notification displayed:', event);
                console.warn(event);

                console.log(event);
                console.log("******************************");
                console.log("NOTIFICATION");
                console.log("******************************");
                //$scope.valores.push(event);
                if (event.data !== undefined && event.data.__isOneSignalWelcomeNotification === undefined) {
                    $scope.totalNotiPunch = parseInt($scope.totalNotiPunch) + 1;
                    var usuarioAgregarscope = "";
                    var id_user_envio = "" + event.data.id_user_envio;
                    for (var obj in $scope.usuarios) {
                        if ($scope.usuarios[obj].puestoID === id_user_envio) {
                            console.log($scope.usuarios[obj].puestoID);
                            usuarioAgregarscope = "" + $scope.usuarios[obj].wikiname;
                        };
                    }
                    var idNotificaionAgregar = "";
                    for (var i = 0; i < event.data.ids_usersDefinidos.length; i++) {
                        var objId = event.data.ids_usersDefinidos[i];
                        var objJsonId = JSON.parse(objId);
                        console.log(objJsonId);
                        if (objJsonId.user === $scope.sesion.puesto) {
                            console.warn(objJsonId);

                            idNotificaionAgregar = objJsonId.id;
                            break;
                        };
                    };

                    var mi_id_actividad_entregable = "";
                    console.error(event.data.id_actividad_entregable);
                    if (event.data.id_actividad_entregable !== undefined) {
                        mi_id_actividad_entregable = event.data.id_actividad_entregable;
                    };

                    var obj = {
                        app: "" + event.data.app,
                        id_actividad_entregable: "" + mi_id_actividad_entregable,
                        comment: "" + event.data.comment,
                        visto: "" + event.data.visto,
                        visto: "" + event.data.firma,
                        fecha_pub: "" + event.data.fecha_pub,
                        fecha_visto: "" + event.data.fecha_visto,
                        hora_pub: "" + event.data.hora_pub,
                        hora_visto: "" + event.data.hora_visto,
                        id: "" + idNotificaionAgregar,
                        id_actividad: "" + event.data.id_actividad,
                        prioridad: "" + event.data.prioridad,
                        type: "" + event.data.type,
                        titulo: "" + decodeURIComponent(event.data.titulo),
                        userEnvio: "" + usuarioAgregarscope,
                        userRecibio: "" + $scope.sesion.nombre
                    };
                    console.warn(obj);
                    $scope.notificacionesBell.push(obj);
                    $scope.$apply();
                };
            });
            $scope.OneSignal.isPushNotificationsEnabled(function (isEnabled) {
                if (isEnabled) {

                    $scope.OneSignal.getUserId(function (userId) {
                        console.log('player_id of the subscribed user is : ' + userId);
                        $scope.userId = userId;

                        $scope.AgregarPlay($scope.usuario.puesto, userId, 'boardmiplan', 1);
                        $scope.cargandoCampana = false;
                        $scope.CampanaenLinea = true;
                        $scope.CampanaenLineaContador = 0;

                    });
                } else {
                    $scope.OneSignal.push(["registerForPushNotifications"]);
                    event.preventDefault();
                    $scope.cargandoCampana = false;
                    $scope.CampanaenLinea = false;
                }
            });


            $scope.OneSignal.on('subscriptionChange', function (isSubscribed) {
                console.log("The user's subscription state is now:", isSubscribed);
                if (isSubscribed) {
                    $scope.OneSignal.getUserId(function (userId) {
                        console.log('player_id of the subscribed user is : ' + userId);
                        $scope.userId = userId;
                        $scope.AgregarPlay($scope.usuario.puesto, userId, 'boardmiplan', 1);
                        $scope.CampanaenLinea = true;
                        $scope.CampanaenLineaContador = 0;

                    });
                };
            });

        });
    }


    $scope.AgregarPlay = function (pid_user, ptoken, papp, pestatus) {
        //'boardmiplan'
        //$scope.usuario.puesto
        var objToken = {
            id_user: pid_user,
            token: ptoken,
            app: papp,
            estatus: pestatus
        };

        $dom.insertarPlay(objToken).then(function (res) {
            $scope.suscritoButton = true;
            console.log(res);
            if (res.data.estatus === "1") {
                $scope.miswithcSuscrito.checked = true;
                $scope.CampanaenLinea = true;
                $scope.CampanaenLineaContador = 0;

            } else {
                $scope.CampanaenLinea = false;
                $scope.miswithcSuscrito.checked = false;
            }
        });
    }

    document.getElementById('miswitch').addEventListener('change', function (e) {
        $scope.Suscribir(e);
        /*
              console.log('click', e.target.checked);
             // e.target.checked=false;
             console.log('click', e.target.checked);*/
    });

    document.getElementById('miswitch2').addEventListener('change', function (e) {
        if (e.target.checked) {
            var objToken = {
                id_user: $scope.usuario.puesto,
                token: $scope.userId,
                app: 'boardmiplan',
                estatus: 1
            };
            $scope.CampanaenLinea = true;
            $scope.CampanaenLineaContador = 0;

            $dom.updatePlay(objToken);
            var objN = {
                id_user: $scope.sesion.puesto
            };
            $dom.getNotificacionesContadores(objN).then(function (res) {
                console.log(res);
                $scope.totalNotiPunch = res.data.detail;
                $dom.getNotificaciones(objN).then(function (res2) {
                    console.log(res2);
                    $scope.notificacionesBell = res2.data.detail;
                });
            });

        } else {
            var objToken = {
                id_user: $scope.usuario.puesto,
                token: $scope.userId,
                app: 'boardmiplan',
                estatus: 0
            };
            $scope.CampanaenLinea = false;

            $dom.updatePlay(objToken);
        }
        /*
              console.log('click', e.target.checked);
             // e.target.checked=false;
             console.log('click', e.target.checked);*/
    });



    ons.ready(function () {
        $scope.loadModal.show();
        if (Cookies.get("usuario2") !== undefined) {
            $scope.sesion = JSON.parse(Cookies.get("usuario2"));
            $dom.getUsuarios($dom.getServer(), $scope.sesion.origen).then(function (d) {
                console.log($scope.sesion);
                $scope.usuarios = d;
                $scope.members = d;
                $scope.sesion.puestoNombre = $scope.usuarios[$scope.sesion.usuario].puestoNombre;
                $dom.setUser($scope.sesion);
                $scope.page = "punchlist";
                $scope.user.status = true;
                $scope.loadModal.hide();
                $scope.getPrivateChat();
                $scope.getConversations();
                $scope.getNotificacionesContadores($scope.sesion.puesto);


                $scope.getMyGroups();
                $scope.getLog();
                $scope.usuario = $dom.getUser();





                $scope.cargandoCampana = true;
                $scope.CampanaenLineaContador = 0;
                $scope.suscritoButton = false;
                var objN = {
                    id_user: $scope.sesion.puesto
                };
                $dom.getNotificacionesContadores(objN).then(function (res) {
                    console.log(res);
                    $scope.totalNotiPunch = res.data.detail;
                    $dom.getNotificaciones(objN).then(function (res2) {
                        console.log(res2);
                        $scope.notificacionesBell = res2.data.detail;
                    });
                });
                $scope.IniciarPush();


                $scope.tipoVista = $location.search().tipo;
                $scope.idVista = $location.search().id;
                if ($scope.tipoVista !== undefined && $scope.idVista !== undefined) {
                    var objShowNoti = {
                        tipo: "" + $location.search().tipo,
                        id: "" + $location.search().id
                    };
                    // console.warn(objShowNoti);
                    $scope.showNotificationApp(objShowNoti);

                };




            });
        } else {

            $scope.loadModal.hide();
        }
    });






    $scope.w = $window.innerWidth;
    angular.element($window).on('resize', function () {
        $scope.w = $window.innerWidth;
        if ($scope.w < 782) {
            switch ($scope.page) {
                case 'posts':
                    $scope.page = 'm-posts';
                    break;
                default:

            }
        } else {
            switch ($scope.page) {
                case 'm-posts':
                    $scope.page = 'posts';
                    break;
                default:

            }
        }
        $scope.$apply();
    });
    $scope.user = {
        status: false
    };
    $scope.shared = false;
    $scope.page = "loading";
    $scope.navegar = function (tag) {
        $scope.hideNotificationApp();
        /*switch (tag) {
  case "dashboard":
  $scope.page = tag;
  break;
  case "strategy":
  $scope.page = tag;
  break;
  case "punchlist":
  $scope.page = tag;
  break;
  case "weekly":
  $scope.page = tag;
  break;
  case "studio":
  $scope.page = tag;
  break;
  default:

}*/
        $scope.page = tag;
    }
    $scope.returnMayusculas = function (s) {
        var rwt = "NA";
        if (s !== null && s !== undefined) {
            rwt = s.replace(/[a-z]/g, '').split('');
            rwt = rwt[0] + rwt[1];
        }
        return rwt;
    }
    $scope.verOpciones = function (ev) {
        ons.createPopover("opciones.html", {
            parentScope: $scope
        }).then(function (d) {
            d.show(ev.srcElement);
        });
    }


    $scope.getObjetivoUnico = function (id) {
        $http.get($dom.getServer() + "/php/support/getTicket.php?id=" + id + "&cuenta=" + $dom.getUser().origen).then(function (data) {
            //console.log(data.data.detail);
            if (data.data.detail.length > 0) {
                var sel = data.data.detail[0];
                $scope.Preview = sel.titulo;
                var s = sel;
                $scope.server = $dom.getServer();
                var server = $dom.getServer();
                var user = $dom.getUser();
                $scope.toggleDerecho(sel);
            } else {
                $scope.notFound = true;
            }
        });
    }


    $scope.sharedMostrarAgendaGlobal = false;
    $scope.MostrarAgendaGlobal = function () {
        if ($scope.sharedMostrarAgendaGlobal) {
            $scope.sharedMostrarAgendaGlobal = false;
        } else {
            $scope.shared = false;
            $scope.sharedMostrarAgendaGlobal = true;
        }
    }
    $scope.cerrarAgendaGlobal = function () {
        $scope.sharedMostrarAgendaGlobal = false;
    }

    $scope.selected = $dom.getSelected();
    $scope.toggleDerecho = function (s) {
        $scope.sharedMostrarAgendaGlobal = false;
        //$location.hash('');
        //$anchorScroll();
        $scope.tituloEjesCabeceraDerecho = [];
        $scope.loadModal.show();
        $dom.setSelected(s).then(function (sel) {
            console.log(sel);
            $scope.uploadMessage = "";
            $scope.selected = sel;
            if ($scope.selected.eje === "no" || $scope.selected.eje === "si") {

                var objEnviar = {
                    id: encodeURIComponent($scope.selected.id)
                };
                $dom.getEjes(objEnviar).then(function (res) {
                    console.warn(res);
                    $scope.tituloEjesCabeceraDerecho = res.data.tituloRutaObjetivo;
                    $scope.loadModal.hide();
                    $scope.shared = true;
                });




            } else {
                //$location.hash('comment-'+$scope.selected.comments.length);
                //$anchorScroll();
                $scope.loadModal.hide();
                //$scope.rtab.setActiveTab(0);
                $scope.shared = true;

                console.log(($scope.selected));

            }


        });
    }




    $scope.server = $dom.getServer();
    $scope.login = function () {
        console.log("LOGIN");
        $http.get($dom.getServer() + "/php/signup.php?wikiname=" + $scope.username + "&password=" + $scope.password).then(function (data) {
            $scope.sesion = data.data;
            console.log(JSON.stringify(data.data));
            if ($scope.sesion.resultado == "true") {
                console.log("loged");
                Cookies.set('usuario2', {
                    nombre: $scope.sesion.usuario,
                    usuario: $scope.sesion.usuario,
                    email: $scope.sesion.email,
                    origen: $scope.sesion.origen,
                    type: $scope.sesion.type,
                    puesto: $scope.sesion.puesto,
                    puestoNombre: $scope.sesion.puestoNombre,
                    lastSection: "punchlist.html"
                }, {
                    expires: 30
                });
                $dom.setUser($scope.sesion);
                //$scope.getNotificacionesContadores($scope.sesion.puesto);

                $dom.getUsuarios($dom.getServer(), $scope.sesion.origen).then(function (d) {
                    $scope.usuarios = d;
                    $scope.sesion.puestoNombre = $scope.usuarios[$scope.sesion.usuario].puestoNombre;

                    $scope.usuario = $dom.getUser();




                    $window.location.reload(true);


                    //location.reload();

                    $scope.page = "punchlist";
                    $scope.user.status = true;
                });

                //$window.location.reload(true);

            } else {
                alert($scope.sesion.mensaje);
            }
        });
    }
    $scope.usuarios = [];
    $scope.editTarget = {
        tag: "",
        selected: {},
        lista: []
    };
    // $scope.editar=function($event,o,tag){
    //   $scope.editTarget.tag=tag;
    //   $scope.editTarget.selected=o;
    //   if (tag=="padre") {
    //     if (o.eje=="Ticket") {
    //       $scope.editTarget.lista=$dom.getAreas();
    //     }
    //   }
    //   ons.createPopover("editar.html",{parentScope:$scope}).then(function(d){
    //     $scope.editD = d;
    //     d.show($event.target);
    //   });
    // }
    // $scope.execEdit=function(et){
    //   switch (et.tag) {
    //     case 'estatus':
    //     var s = et.selected.estatus.split('-');
    //       et.selected.colorStatus=s[1];
    //       et.selected.colorNumber=s[0];
    //       break;
    //     case "padre":
    //     for (var i = 0; i < et.lista.length; i++) {
    //       if (et.lista[i].id==et.selected.padre) {
    //         et.selected.padre_titulo=et.lista[i].titulo;
    //         break;
    //       }
    //     }
    //       break;
    //     default:
    //   }
    //     console.log("Editar "+et.tag+" con los siguientes datos:");
    //     console.log(et);
    //     // AQUI SE INSERTA LA CONSULTA SQL
    //   $scope.editD.hide();
    // }

    /* EDICIONES */

    $scope.editar = function ($event, ticket, tag) {

        // console.log("EDITAR");
        $scope.tagEdit = tag;
        $scope.tmpTicket = ticket;
        $scope.newValue = angular.copy(ticket);
        $scope.newValue.last_value = $scope.newValue[$scope.tagEdit];
        $scope.newValue.fecha_fin = new Date($scope.newValue.fecha_fin);

        if (tag == 'fecha_fin') {
            if (ticket[tag] == "0000-00-00") {
                var today = new Date;
                $scope.newValue[tag] = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
            }
        }

        if (tag == "padre") {
            if (ticket.eje == "Ticket") {
                $scope.editTarget.lista = $dom.getAreas();
            }
        }

        console.log($scope.newValue[tag]);

        ons.createPopover("editar.html", {
            parentScope: $scope
        }).then(function (d) {
            $scope.generalEditModal = d;
            d.show($event.target);
        });
        //$scope.usuarios = $datos.getUsuarios();
    }


    $scope.updateField = function (campo, valor) {

        $http.post($scope.server + "/php2alex/pap/update.php", {
            tabla: "pap_sub_eje",
            campo: campo,
            valor: valor,
            campoObjetivo: "id",
            valorObjetivo: $scope.tmpTicket.id
        }).then(function (data) {
            console.log(JSON.stringify(data.data));

            $scope.tmpTicket[campo] = valor;

            console.log($scope.tmpTicket[campo]);

            console.log(campo);

            if (campo == "estatus") {
                $scope.tmpTicket["colorStatus"] = $scope.newValue["estatus"].split("-")[1];
                console.log($scope.tmpTicket["colorStatus"]);
                $scope.tmpTicket[campo] = $scope.newValue[campo];
            }

        });
    }


    $scope.$on('eventX', function (ev, args) {
        //   alert('eventX');
        console.log('eventX found on Controller1 $scope');
    });

    $scope.de = "";
    $scope.despuesEditar = function (de, objeto) {
        $scope.de = de;
        $scope.objetoSeleccionado = objeto;
    }

    $scope.saveChanges = function () {

        if ($scope.de !== "agenda" && $scope.de !== "") {
            $scope.$broadcast('actualizarEdicionAgenda', $scope.tmpTicket);
        } else if ($scope.page === "punchlist" && $scope.de === "agenda") {
            $scope.$broadcast('actualizarEdicionPunchList', $scope.tmpTicket);
        } else if ($scope.page === "strategy" && $scope.de === "agenda") {
            $scope.$broadcast('actualizarEdicionStrategy', $scope.tmpTicket);
        }


        console.log("SAVE");

        if ($scope.tagEdit == "estatus") {
            $scope.tmpTicket["colorStatus"] = $scope.newValue[$scope.tagEdit].split("-")[1];
            $scope.tmpTicket[$scope.tagEdit] = $scope.newValue[$scope.tagEdit];

            var today = new Date();

            console.log($scope.tmpTicket[$scope.tagEdit]);
            if ($scope.tmpTicket[$scope.tagEdit] == "7-Done") {
                var month = today.getMonth() + 1;
                var day = today.getDate();
                if (month < 10) {
                    month = "0" + month;
                }
                if (day < 10) {
                    day = "0" + day;
                }
                today = today.getFullYear() + "-" + month + "-" + day;
            } else {
                today = "0000-00-00";
            }
            console.log($scope.tmpTicket[$scope.tagEdit]);
            console.log(today);



            $http.post($scope.server + "/php2alex/pap/update.php", {
                tabla: "pap_sub_eje",
                campo: "fecha_real",
                valor: today,
                campoObjetivo: "id",
                valorObjetivo: $scope.tmpTicket.id
            }).then(function (data) {
                console.log(JSON.stringify(data.data));

                $scope.tmpTicket.fecha_real = today;
                $scope.newValue.fecha_real = today;
            });

        } else if ($scope.tagEdit == "responsable_1" || $scope.tagEdit == "responsable_2") {
            console.log("Responsables");

            try {
                $scope.newValue[$scope.tagEdit] = JSON.parse($scope.newValue[$scope.tagEdit]);
                console.log(JSON.stringify($scope.newValue[$scope.tagEdit]));

                console.log($scope.newValue[$scope.tagEdit] + " - " + $scope.tmpTicket[$scope.tagEdit]);
                if ($scope.newValue[$scope.tagEdit] != null) {
                    $scope.newValue.label = $scope.newValue[$scope.tagEdit].wikiname;

                    $scope.tmpTicket[$scope.tagEdit] = $scope.newValue[$scope.tagEdit].wikiname;

                    console.log(typeof $scope.newValue[$scope.tagEdit]);
                    console.log($scope.newValue[$scope.tagEdit]);
                    $scope.newValue[$scope.tagEdit] = $scope.newValue[$scope.tagEdit].puestoID;



                } else {
                    console.log("NULL");
                }
            } catch (err) {
                console.log(JSON.stringify(err));
            }

            var date = $scope.newValue.fecha_fin;
            var mes = date.getMonth() + 1;
            var dia = date.getDate();


            if (mes < 10) {
                mes = "0" + mes;
            }

            if (dia < 10) {
                dia = "0" + dia;
            }


            $scope.newValue.fecha_fin = date.getFullYear() + "-" + mes + "-" + dia;

            $scope.updateField("fecha_fin", $scope.newValue.fecha_fin);


            $scope.updateField("next_step", $scope.newValue.next_step);

            $scope.updateField("estatus", $scope.newValue.estatus);


            $scope.insertComment($scope.tmpTicket, $scope.newValue.editMessage);

        } else if ($scope.tagEdit == "padre") {
            for (var i = 0; i < $scope.editTarget.lista.length; i++) {
                if ($scope.editTarget.lista[i].id == $scope.newValue[$scope.tagEdit]) {
                    $scope.tmpTicket.padre_titulo = $scope.editTarget.lista[i].titulo;

                }
            }
        } else {
            $scope.tmpTicket[$scope.tagEdit] = $scope.newValue[$scope.tagEdit];

        }

        console.log("Editar " + $scope.tagEdit + " con los siguientes datos:");
        console.log($scope.newValue[$scope.tagEdit]);

        // AQUI SE INSERTA LA CONSULTA SQL
        $http.post($scope.server + "/php2alex/pap/update.php", {
            tabla: "pap_sub_eje",
            campo: $scope.tagEdit,
            valor: $scope.newValue[$scope.tagEdit],
            campoObjetivo: "id",
            valorObjetivo: $scope.tmpTicket.id
        }).then(function (data) {
            console.log(JSON.stringify(data.data));
            if ($scope.tagEdit == "estatus" && $scope.newValue[$scope.tagEdit] === "7-Done") {
                console.log($scope.newValue[$scope.tagEdit]);
                console.log($scope.tmpTicket);
                /////Cambiar estatus
                $scope.tagEdit = "timing";
                $scope.tmpTicket.timing = "OK";
                $scope.tmpTicket[$scope.tagEdit] = "OK";
                $scope.newValue[$scope.tagEdit] = "OK";
                console.warn($scope.tmpTicket);
                $scope.saveChanges();
            } else if ($scope.tagEdit == "responsable_1" || $scope.tagEdit == "responsable_2") {
                console.log("Responsables");

                console.log($scope.newValue[$scope.tagEdit]); // Responsable id
                console.log($scope.usuario.puesto); // Usuario que cambio
                console.log($scope.tmpTicket); //Mi ticket actual
                //alert($scope.tmpTicket.eje);

                var miappActual = "";
                if ($scope.tmpTicket.eje === "si" || $scope.tmpTicket.eje === "no") {
                    miappActual = "objetivo*";
                } else if ($scope.tmpTicket.eje === "Ticket") {
                    miappActual = "punchlist*";

                };

                var objEnviarNotiPunch = {
                    id_actividad: $scope.tmpTicket.id,
                    type: $scope.tmpTicket.type,
                    titulo: $scope.tmpTicket.titulo,
                    prioridad: $scope.tmpTicket.prioridad,
                    id_mensaje: '0',
                    id_user_envio: $scope.usuario.puesto,
                    app: '' + miappActual + $scope.tagEdit,
                    estatus: '0',
                    fecha_pub: $scope.getDateTimeActual().date,
                    hora_pub: $scope.getDateTimeActual().time,
                    fecha_visto: "0000-00-00",
                    hora_visto: "00:00",
                    para: $scope.newValue[$scope.tagEdit]
                };
                console.log(objEnviarNotiPunch);

                $dom.insertarNotificacionesPunchListenBaord(objEnviarNotiPunch).then(function (res) {
                    console.log(objEnviarNotiPunch);
                });
            }

        });

        if ($scope.newValue.responsable_1 == $scope.sesion.usuario) {
            $scope.targetUsers = [$scope.newValue.responsable_2];

        } else if ($scope.newValue.responsable_2 == $scope.sesion.usuario) {
            $scope.targetUsers = [$scope.newValue.responsable_1];
        } else {
            $scope.targetUsers = [$scope.responsable_1, $scope.newValue.responsable_2];
        }






        $scope.newValue.campo = $scope.fields[$scope.tagEdit];

        //  $scope.newValue.campo = $scope.tagEdit;
        $scope.newValue.new_value = $scope.newValue[$scope.tagEdit]
        console.log(JSON.stringify($scope.newValue));


        var tmpSubeje = angular.copy($scope.newValue);
        if ($scope.tagEdit == "responsable_1" || $scope.tagEdit == "responsable_2") {
            tmpSubeje.new_value = tmpSubeje.label
        }

        var data = {
            subeje: tmpSubeje.id,
            target: 0,
            activity: tmpSubeje
        };
        data.activity.comments = [];

        $scope.sendMessage("updateActivity", $scope.targetUsers, data, true);

        //
        // $dom.getUsuarios($dom.getServer(),$scope.sesion.origen).then(function(d){
        //   //console.log(JSON.stringify(d));
        //
        //   for (var key in d) {
        //     $scope.allUsers.push(d[key].wikiname);
        //   }
        //   //    console.log(JSON.stringify($scope.allUsers));
        //
        //
        //   //$scope.allUsers=d;
        // });



    }

    /*FILES*/

    $scope.files = [];

    $scope.upload = function (id, f) {
        //console.log(f);
        $scope.execSubir(id, f, 0, f.length).then(function (resp) {
            console.log("finished");
        });

    };
    $scope.prepareFile = function (file) {
        var deferred = $q.defer();
        var reader = new FileReader();

        reader.readAsDataURL(file);

        reader.onload = function () {
            //console.log(reader.result);
            //$scope.uploadFile(reader.result,id);
            deferred.resolve(reader.result);
        };

        reader.onerror = function (error) {

            console.log('Error: ', error);

        };
        return deferred.promise;
    }
    $scope.uploadMessage = "";
    $scope.execSubir = function (id, files, start, limit) {
        if ($scope.selected === undefined) {
            $scope.selected = $dom.getSelected();
        };

        var deferred = $q.defer();
        $scope.prepareFile(files[start]._file).then(function (fp) {
            $http.post($scope.server + "/php2alex/files/b64.php", {
                id: id,
                file: fp,
                name: files[start]
            }).then(function (df) {
                //$scope.toggleDerecho($scope.selected);
                //console.log(df);
                $http.get($scope.server + "/php2alex/files/getFiles.php?id=" + id).then(function (df) {
                    //console.log(df);
                    $scope.selected.files = df.data;
                    /*$scope.files=[];
                    f=[];*/
                    start++;
                    if (start < limit) {
                        $scope.execSubir(id, files, start, files.length).then(function (resp) {
                            //console.log(resp);
                            $scope.uploadMessage = "Se subierón " + (start + 1) + " archivos";
                            $scope.$apply();
                        });
                    } else {
                        $scope.uploadMessage = "Se subierón " + (start + 1) + " archivos";
                        setTimeout(function () {
                            $scope.uploadMessage = "";
                            $scope.$apply();
                        }, 4500);
                        deferred.resolve(true);
                    }
                });
                //console.log(df);

            });
        });
        return deferred.promise;
    }
    $scope.deleteFile = function (file, nombre) {
        $http.get($scope.server + "/php2alex/files/deleteFile.php?file=" + file).
        then(function (data) {
            for (var i = 0; i < $scope.selected.files.length; i++) {
                console.log($scope.selected.files[i].archivo);
                if ($scope.selected.files[i].archivo == nombre) {
                    $scope.selected.files.splice(i, 1);
                }
            }
        });
    }

    $scope.delete = function (n) {
        var deferred = $q.defer();
        ons.notification.confirm({
            message: "¿seguro que deseas eliminar?",
            callback: function (resp) {
                if (resp > 0) {
                    $http.get($dom.getServer() + "/php/pap/deleteCarefully.php?id=" + n.sub_eje.id).then(function (data) {
                        console.log(data);
                        if (data.data.status !== "error") {
                            ons.notification.alert({
                                message: data.data.mensaje
                            });
                            deferred.resolve(true);
                        } else {
                            ons.notification.alert({
                                message: data.data.mensaje
                            });
                            deferred.resolve(false);
                        }
                    });
                } else {
                    deferred.resolve(false);
                }
            }
        });

        return deferred.promise;
    }
    $scope.cerrar = function () {
        $scope.shared = false;
    }
    $scope.logout = function () {
        Cookies.remove('usuario2');
        console.log($scope.userId);
        if ($scope.userId === undefined) {
            $window.location.reload();

        } else {
            console.log("borrar");
            // $scope.DeletePlay(pid_user,ptoken,papp,pestatus);
            //$scope.usuario.puesto,userId,'boardmiplan',1
            var objToken = {
                id_user: $scope.usuario.puesto,
                token: $scope.userId,
                app: 'boardmiplan',
                estatus: 1
            };

            $dom.deletePlay(objToken).then(function (res) {
                console.log(res);
                $window.location.reload();

            });
        }

    }


    $scope.DeletePlay = function (pid_user, ptoken, papp, pestatus) {
        //'boardmiplan'
        //$scope.usuario.puesto
        var objToken = {
            id_user: pid_user,
            token: ptoken,
            app: papp,
            estatus: pestatus
        };

        $dom.deletePlay(objToken).then(function (res) {
            console.log(res);
        });
    }



    /*============================  WebSocket  ======================================*/


    $scope.conn = new ReconnectingWebSocket('wss://genniux.net/wss2/:9000');
    $scope.bot = new ReconnectingWebSocket('wss://genniux.net/wss2/:9000');


    $scope.sendMessage = function (tipo, users, data, log) {
        if (data.target == undefined) {
            data.target = 0;
        }
        if (data.campo == undefined) {
            data.campo = "";
            data.new_value = "";
            data.last_value = "";
        }


        if (log) {
            var encontrado = false;
            for (var i = 0; i < users.length; i++) {
                if (users[i] == "Bot" + $scope.sesion.origen) {
                    encontrado = true;
                    break;
                }
            }

            if (!encontrado) {
                console.log(users);
                users.push("Bot" + $scope.sesion.origen);

            }

        }

        var today = new Date;
        $scope.today = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
        $scope.time = today.getHours() + ":" + today.getMinutes();

        if (tipo == "updateActivity") {
            users = ["Bot" + $scope.sesion.origen]
        }

        console.log(JSON.stringify(users));


        for (var i = 0; i < users.length; i++) {

            if (tipo == "updateActivity") {
                var tmpData = {
                    actividad: data.subeje,
                    target: data.target,
                    colaborador: users[i],
                    tipo: tipo,
                    remitente: $scope.sesion.usuario,
                    fecha: $scope.today,
                    hora: $scope.time,
                    campo: data.activity.campo,
                    new_value: data.activity.new_value,
                    last_value: data.activity.last_value
                }
            } else if (tipo == "newComment") {
                var tmpData = {
                    actividad: data.subeje,
                    target: data.target,
                    colaborador: users[i],
                    tipo: tipo,
                    remitente: $scope.sesion.usuario,
                    fecha: $scope.today,
                    hora: $scope.time,
                    campo: null,
                    new_value: null,
                    last_value: null
                }
            } else if (tipo == "newMessage") {
                var tmpData = {
                    grupo: data.subeje,
                    target: data.target,
                    colaborador: users[i],
                    tipo: tipo,
                    remitente: $scope.sesion.usuario,
                    fecha: $scope.today,
                    hora: $scope.time,
                    campo: null,
                    new_value: null,
                    last_value: null
                }
            } else if (tipo == "newSpec") {
                var tmpData = {
                    actividad: data.subeje,
                    target: data.target,
                    colaborador: users[i],
                    tipo: tipo,
                    remitente: $scope.sesion.usuario,
                    fecha: $scope.today,
                    hora: $scope.time,
                    campo: null,
                    new_value: null,
                    last_value: null
                }
            }

            if (users[i] != $scope.sesion.usuario) {
                console.log(JSON.stringify(tmpData));
                console.log(users[i]);
                $http.post($scope.server + "/php/notifications/addNotification.php?", tmpData).then(function (response) {
                    //console.log(JSON.stringify(data.data));
                    if (response.data.response == "OK") {

                        console.log("REGISTRADO: " + response.data.id + " - " + tipo + " - " + response.data.user + " - " + data.subeje);
                        var date = new Date();
                        var today = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                        var time = date.getHours() + ":" + date.getMinutes();

                        data.same = false;

                        $scope.serverMessage = {
                            tipo: tipo,
                            users: [response.data.user],
                            user: $scope.sesion.usuario,
                            data: data,
                            fecha: today,
                            hora: time,
                            origen: $scope.sesion.origen,
                            notificacion: response.data.id
                        };

                        // if($scope.serverMessage.user!=$scope.user.nombre){
                        //   $scope.serverMessage.user=$scope.user.nombre
                        // }
                        $scope.serverMessage = JSON.stringify($scope.serverMessage);
                        console.log("Enviado: " + $scope.serverMessage);


                        $scope.conn.send($scope.serverMessage);


                    }


                });
            } else {

                //alert("Same User");

                var date = new Date();
                var today = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                var time = date.getHours() + ":" + date.getMinutes();

                data.same = true;
                $scope.serverMessage = {
                    tipo: tipo,
                    users: [$scope.sesion.usuario],
                    user: $scope.sesion.usuario,
                    data: data,
                    fecha: today,
                    hora: time,
                    origen: $scope.sesion.origen,
                };

                // if($scope.serverMessage.user!=$scope.user.nombre){
                //   $scope.serverMessage.user=$scope.user.nombre
                // }
                $scope.serverMessage = JSON.stringify($scope.serverMessage);
                // console.log("Enviado: "+$scope.serverMessage);


                $scope.conn.send($scope.serverMessage);

            }

        }


    }


    $scope.GBoard = "GBoard";
    document.title = "" + $scope.GBoard;


    var socketUser = function () {
        $scope.conn = new ReconnectingWebSocket('wss://board.genniux.com:9000');
        //$scope.conn = new ReconnectingWebSocket('ws://carlosvazquez.cloudapp.net:8080');

        $timeout(socketUser, 5000); // reset the timer
    }

    // $timeout(socketUser, 5000);
    $scope.playAudio = function () {
        var audio = new Audio('sounds/message.mp3');
        audio.play();
    };

    $scope.showNotification = function (noti, type) {

        var length = 25;

        if (type == "private") {
            var icon = $scope.server + "/php/imagenes/" + $scope.usuarios[noti.remitente].picture;

        } else {
            var icon = $scope.server + "/img/grupo.png";
            //var icon = $scope.server+"/php/imagenes/"+$scope.usuarios[noti.remitente].picture;

        }
        message = {
            body: noti.data.comment.comment.substring(0, length),
            icon: icon,
            badge: $scope.server + "/img/logo.png",
            requireInteraction: true
        }

        // Let's check if the browser supports notifications
        if (!("Notification" in window)) {
            console.log("This browser does not support desktop notification");
        }
        // Let's check whether notification permissions have already been granted
        else if (Notification.permission === "granted") {
            // If it's okay let's create a notification
            if (document.visibilityState != "visible") {
                var notification = new Notification(noti.remitente, message);

                setTimeout(notification.close.bind(notification), 4000);
            }
        }
        // Otherwise, we need to ask the user for permission
        else if (Notification.permission !== 'denied') {
            Notification.requestPermission(function (permission) {
                // If the user accepts, let's create a notification
                if (permission === "granted") {


                    if (document.visibilityState != "visible") {
                        var notification = new Notification(noti.remitente, message);

                        setTimeout(notification.close.bind(notification), 4000);
                    }
                }
            });
        }

    }

    $scope.conn.onopen = function (e) {
        console.log("Connection established!");
        // $scope.conn.send(JSON.stringify({tipo:"user",user:$scope.username}));
        // var div = document.getElementById('mensajes');
        // div.innerHTML = div.innerHTML + '<br>Te has conectado<br>';
    };

    $scope.conn.onmessage = function (e) {

        $scope.notMessage = JSON.parse(e.data);

        console.log("RECIBIDO: " + JSON.stringify($scope.notMessage));

        //tipos de mensaje,  newActivity, UpdateActivity

        switch ($scope.notMessage.tipo) {
            case "newActivity":
                //console.log(JSON.stringify($scope.notMessage.data));
                //$scope.agenda.push($scope.notMessage.data);

                //
                // $scope.updateAgenda();


                break;
            case "addActivity":
                // $scope.arbol = $arbol.getArbol();
                // console.log($scope.notMessage.data.padre);
                // $scope.tmpNodo = $scope.searchInTree($scope.arbol,$scope.notMessage.data.padre);
                // //console.log(JSON.stringify($scope.tmpNodo));
                //
                // //console.log($scope.notMessage.data.nivel);
                // $scope.tmpNodo.hijos.push({sub_eje:$scope.notMessage.data,nivel:$scope.tmpNodo.nivel+1,hijos:[]});
                //
                // console.log("newActivity added");
                break;

            case "newComment":


                console.log("REMITENTE: " + $scope.notMessage.remitente);

                if ($scope.notMessage.remitente != $scope.sesion.usuario) {
                    $scope.playAudio();

                    if ($scope.notMessage.data.comment != undefined && $scope.notMessage.data.comment.comment != "" && $scope.notMessage.data.comment.comment != null) {
                        try {
                            $scope.showNotification($scope.notMessage, "private");
                        } catch (err) {
                            console.log("Error: ");
                        }
                    }


                } else {
                    console.log("SAME");
                }



                //$scope.info = $scope.notMessage.data;
                //$scope.updateAgenda();
                // $scope.arbol = $arbol.getArbol();
                // if($scope.info!=undefined){
                //   if($scope.info.id==$scope.notMessage.data.id){
                //     $scope.info.newComment++;
                //     $scope.getComment();
                //   }
                // }



                //console.log(JSON.stringify($scope.arbol));
                //console.log($scope.notMessage.data.subeje);
                $scope.tmpConversation = $scope.searchInConversation($scope.notMessage.data.subeje);
                //console.log(JSON.stringify($scope.tmpConversation));
                console.log(JSON.stringify($scope.notMessage.data));


                if ($scope.tmpConversation == undefined) {

                    console.log("UNDEFINED");
                    $scope.tmpConversation = $scope.notMessage.data.conversation;

                    if ($scope.notMessage.remitente != $scope.sesion.usuario) {
                        $scope.tmpConversation.subeje.newComment = 1;
                    }
                    $scope.tmpConversation.comments = [];
                    //console.log($scope.tmpConversation.origen);
                    switch ($scope.tmpConversation.origen) {
                        case "private":
                            console.log("private push");
                            if ($scope.tmpConversation.subeje.responsable_1 == $scope.sesion.usuario) {
                                $scope.tmpConversation.subeje.titulo = $scope.tmpConversation.subeje.responsable_2;
                            } else {
                                $scope.tmpConversation.subeje.titulo = $scope.tmpConversation.subeje.responsable_1;
                            }
                            $scope.privates.push($scope.tmpConversation);
                            break;
                        case "forum":
                            console.log("forum push");
                            $scope.conversations.push($scope.tmpConversation);
                            break;
                        default:

                    }

                    //console.log(JSON.stringify($scope.privates));
                } else {

                    if ($scope.notMessage.remitente != $scope.sesion.usuario) {
                        $scope.tmpConversation.subeje.newComment++;
                    }

                }
                if ($scope.tmpConversation != undefined) {
                    //console.log(JSON.stringify($scope.tmpConversation.comments.length));
                    if ($scope.tmpConversation.comments.length == 0) {
                        //console.log("GET COMMENT");
                        $scope.getComment($scope.tmpConversation).then(function (data) {

                            $scope.tmpConversation.comments = data.detail;
                            var tmpLast = $scope.tmpConversation.comments[0];
                            // console.log(JSON.stringify(tmpLast));
                            if (tmpLast) {
                                $scope.tmpConversation.lastComment = {
                                    comment: tmpLast.comment,
                                    autor: tmpLast.autor,
                                    date: tmpLast.date,
                                    hour: tmpLast.hour
                                };

                            }

                        });
                    } else {


                        //console.log($scope.tmpConversation.origen);
                        //console.log($scope.chatNotifications[$scope.tmpConversation.origen]);

                        if ($scope.notMessage.data.comment.id != '' && $scope.notMessage.data.comment.id != undefined) {

                            if ($scope.notMessage.remitente != $scope.sesion.usuario) {
                                $scope.notMessage.data.comment.notificaciones = 1;
                            }
                            $scope.tmpConversation.comments.push($scope.notMessage.data.comment);
                            $scope.tmpConversation.lastComment = $scope.notMessage.data.comment;


                            setTimeout(function () {


                                var objDiv = document.getElementById("contentMessageBox");
                                if (objDiv) {
                                    objDiv.scrollTop = objDiv.scrollHeight;
                                }

                                var objDiv = document.getElementById("comments");
                                if (objDiv) {
                                    objDiv.scrollTop = objDiv.scrollHeight;
                                }
                            }, 300);

                            console.log("data.comment");
                            //console.log("Nuevo comentario "+$scope.notMessage.data.comment.comment+" en "+$scope.tmpConversation.subeje.titulo);
                        }

                    }


                }
                $scope.tmpConversation.origen = $scope.notMessage.data.conversation.origen;
                console.log(JSON.stringify($scope.chatNotifications));


                if ($scope.notMessage.remitente != $scope.sesion.usuario) {
                    $scope.chatNotifications[$scope.tmpConversation.origen]++;
                }

                if ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private > 0) {
                    $scope.GBoard = "(" + ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private) + ") " + "GBoard";
                    document.title = "" + $scope.GBoard;
                } else {
                    $scope.GBoard = "GBoard";
                    document.title = "" + $scope.GBoard;
                }

                console.log(JSON.stringify($scope.chatNotifications));


                if ($scope.selected.id == $scope.notMessage.data.subeje) {
                    $scope.selected.comments.push($scope.notMessage.data.comment);
                }

                $scope.$apply();
                // console.log("php/comment/consultaComment.php?activity_id=" + $scope.notMessage.data.id +"&user="+$scope.user.nombre+"&reverse="+true);
                // $http.get("php/comment/consultaComment.php?activity_id=" + $scope.notMessage.data.id +"&user="+$scope.user.nombre+"&reverse="+true).
                // success(function(data) {
                //   //console.log(JSON.stringify(data));
                //   if($scope.tmpConversation!=undefined){
                //     $scope.tmpConversation.comments=data.detail;
                //     var tmpLast = $scope.tmpConversation.pop();
                //     $scope.tmpConversation.lastComment={comment:tmpLast,autor:tmpLast.autor};
                //     $scope.tmpConversation.comments.push(tmpLast);
                //   }
                //
                // });

                //console.log(JSON.stringify($scope.tmpConversation));

                //console.log($scope.tmpConversation.subeje.newComment);

                // $scope.getPrivateChat();
                // $scope.getConversations();

                // $scope.tmpNodo = $scope.searchInTree($scope.arbol,$scope.notMessage.data.id);
                // $scope.tmpNodo.sub_eje.newComment++;
                //console.log($scope.tmpNodo.sub_eje.newComment);
                break;


            case "newMessage":


                // console.log("REMITENTE: "+$scope.notMessage.remitente);
                // console.log("USUARIO: "+$scope.sesion.usuario);

                if ($scope.notMessage.remitente != $scope.sesion.usuario) {
                    $scope.playAudio();

                    if ($scope.notMessage.data.comment != undefined && $scope.notMessage.data.comment.comment != "" && $scope.notMessage.data.comment.comment != null) {
                        try {
                            $scope.showNotification($scope.notMessage, "group");
                        } catch (err) {
                            console.log("Error");
                        }

                    }

                } else {
                    console.log("SAME");
                }

                $scope.tmpGroup = $scope.searchInGroup($scope.notMessage.data.subeje);
                if ($scope.tmpGroup == undefined) {
                    $scope.tmpGroup = $scope.notMessage.data.conversation;

                    if ($scope.notMessage.remitente != $scope.sesion.usuario) {
                        $scope.tmpGroup.subeje.newMessage = 1
                    }

                    $scope.misGrupos.push($scope.tmpGroup);
                    $scope.tmpGroup.comments = [];
                } else {

                    if ($scope.notMessage.remitente != $scope.sesion.usuario) {
                        $scope.tmpGroup.subeje.newMessage++;
                    }

                }
                if ($scope.tmpGroup != undefined) {

                    $scope.tmpGroup.origen = $scope.notMessage.data.conversation.origen;


                    if ($scope.tmpGroup.comments.length == 0) {
                        $scope.getMessage($scope.tmpGroup).then(function (data) {
                            if (data.response == "OK") {
                                $scope.tmpGroup.comments = data.detail;
                                var tmpLast = $scope.tmpGroup.comments[0];
                                // console.log(JSON.stringify(tmpLast));
                                if (tmpLast) {
                                    $scope.tmpGroup.lastComment = {
                                        comment: tmpLast.comment,
                                        autor: tmpLast.autor,
                                        date: tmpLast.date,
                                        hour: tmpLast.hour
                                    };
                                    console.log(JSON.stringify($scope.tmpGroup.lastComment));
                                }
                            }
                        })
                    } else {
                        if ($scope.notMessage.data.comment.id != '' && $scope.notMessage.data.comment.id != undefined) {
                            //$scope.getMessage();

                            if ($scope.notMessage.remitente != $scope.sesion.usuario) {
                                $scope.notMessage.data.comment.notificaciones = 1;
                            }

                            $scope.tmpGroup.comments.push($scope.notMessage.data.comment);
                            $scope.tmpGroup.lastComment = $scope.notMessage.data.comment;
                            setTimeout(function () {


                                var objDiv = document.getElementById("contentMessageBox");
                                if (objDiv) {
                                    objDiv.scrollTop = objDiv.scrollHeight;
                                }

                                var objDiv = document.getElementById("comments");
                                if (objDiv) {
                                    objDiv.scrollTop = objDiv.scrollHeight;
                                }
                            }, 300);
                            console.log(JSON.stringify($scope.tmpGroup.lastComment));
                        }
                    }



                }

                if ($scope.notMessage.remitente != $scope.sesion.usuario) {
                    $scope.chatNotifications[$scope.tmpGroup.origen]++;

                }

                if ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private > 0) {
                    $scope.GBoard = "(" + ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private) + ") " + "GBoard";
                    document.title = "" + $scope.GBoard;
                } else {
                    $scope.GBoard = "GBoard";
                    document.title = "" + $scope.GBoard;
                }



                //alert($scope.tmpGroup.origen);
                //$scope.getMyGroups();



                $scope.$apply();





                break;

            case "newSpec":

                var id = $scope.notMessage.data.subeje;

                //console.log("emit: "+id);

                //alert(id);
                //alert($scope.notMessage.data.same);
                if ($scope.notMessage.data.same) {
                    if ($scope.selected.id == id) {
                        $scope.selected.specs.push($scope.notMessage.data.spec);
                    }
                } else {
                    if ($scope.selected.id == id) {
                        $scope.notMessage.data.spec.notificaciones = 1;
                        $scope.selected.specs.push($scope.notMessage.data.spec);
                        $scope.selected.newSpec++;

                        $scope.$apply();
                    } else {

                        console.log("EMIT");
                        $rootScope.$emit("updatePunchlist", id);
                        $rootScope.$emit("updateStudio", id);
                        $rootScope.$emit("updatePlan", id);
                        $rootScope.$emit("updateStrategy", id);
                    }
                }



                //$scope.info = $scope.notMessage.data;
                // $scope.updateAgenda();
                // $scope.arbol = $arbol.getArbol();
                //
                // if($scope.info!=undefined){
                //   if($scope.info.id==$scope.notMessage.data.id){
                //     $scope.getSpec();
                //   }
                // }

                //console.log(JSON.stringify($scope.arbol));
                //console.log($scope.notMessage.data.id);
                // $scope.tmpNodo = $scope.searchInTree($scope.arbol,$scope.notMessage.data.id);
                // $scope.tmpNodo.sub_eje.newSpec++;

                break;

            case "updateActivity":
                // $scope.arbol = $arbol.getArbol();
                // $scope.updateAgenda();
                // $scope.tmpNodo = $scope.searchInTree($scope.arbol,$scope.notMessage.data.id);
                // console.log($scope.tmpNodo);
                // $scope.tmpNodo.sub_eje = $scope.notMessage.data;
                // console.log($scope.notMessage.data);

                break;



            case "updateNotification":


                switch ($scope.notMessage.data.tipo) {
                    case "newComment":
                        console.log("NEW COMMENT");

                        switch ($scope.notMessage.data.sub) {
                            case "private":

                                console.log("PRIVATE");

                                for (var i = 0; i < $scope.privates.length; i++) {
                                    if ($scope.privates[i].subeje.id == $scope.notMessage.data.id) {
                                        console.log("PRIVATES: " + $scope.chatNotifications.private);
                                        $scope.chatNotifications.private -= $scope.privates[i].subeje.newComment;
                                        console.log("PRIVATES: " + $scope.chatNotifications.private);

                                        $scope.privates[i].subeje.newComment = 0;


                                        for (var j = 0; j < $scope.privates[i].comments.length; j++) {
                                            $scope.privates[i].comments[j].notificaciones = 0;

                                        }

                                        console.log("ENCONTRADO");

                                        if ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private > 0) {
                                            $scope.GBoard = "(" + ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private) + ") " + "GBoard";
                                            document.title = "" + $scope.GBoard;
                                        } else {
                                            $scope.GBoard = "GBoard";
                                            document.title = "" + $scope.GBoard;
                                        }
                                        $scope.$apply();
                                        break;
                                    }
                                }





                                break;

                            case "forum":

                                for (var i = 0; i < $scope.conversations.length; i++) {
                                    if ($scope.conversations[i].subeje.id == $scope.notMessage.data.id) {
                                        $scope.chatNotifications.forum -= $scope.conversations[i].subeje.newComment;
                                        $scope.conversations[i].subeje.newComment = 0;


                                        for (var j = 0; j < $scope.conversations[i].comments.length; j++) {
                                            $scope.conversations[i].comments[j].notificaciones = 0;

                                        }

                                        break;
                                    }
                                }


                                break;

                            default:
                                break;
                        }



                        break;

                    case "newMessage":

                        for (var i = 0; i < $scope.misGrupos.length; i++) {
                            if ($scope.misGrupos[i].subeje.id == $scope.notMessage.data.id) {
                                $scope.chatNotifications.group -= $scope.misGrupos[i].subeje.newMessage;
                                $scope.misGrupos[i].newMessage = 0;


                                for (var j = 0; j < $scope.misGrupos[i].comments; j++) {
                                    $scope.misGrupos[i].comments[j].notificaciones = 0;

                                }

                                if ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private > 0) {
                                    $scope.GBoard = "(" + ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private) + ") " + "GBoard";
                                    document.title = "" + $scope.GBoard;
                                } else {
                                    $scope.GBoard = "GBoard";
                                    document.title = "" + $scope.GBoard;
                                }
                                $scope.$apply();

                                break;
                            }
                        }

                        break;

                    default:
                        break;
                }


                // $scope.updateAgenda();
                // $scope.arbol = $arbol.getArbol();
                // $scope.tmpNodo = $scope.searchInTree($scope.arbol,$scope.notMessage.data.id);
                // $http.get("php/notifications/getNotification.php?id=" + $scope.tmpNodo.sub_eje.id + "&user=" + $scope.user.nombre).success(function(data) {
                //   console.log(JSON.stringify(data));
                //   if(data.response=="OK"){
                //     console.log(data.newComment+" "+data.newSpec+" "+data.newActivity);
                //     $scope.tmpNodo.sub_eje.newComment = data.newComment;
                //     $scope.tmpNodo.sub_eje.newSpec = data.newSpec;
                //     $scope.tmpNodo.sub_eje.newActivity = data.newActivity;
                //     console.log("C: "+$scope.tmpNodo.sub_eje.newComment+" S: "+$scope.tmpNodo.sub_eje.newSpec+" A: "+$scope.tmpNodo.sub_eje.newActivity);
                //     if($scope.info!=undefined){
                //       if($scope.info.id==$scope.notMessage.data.id){
                //         $scope.getComment();
                //         $scope.getSpec();
                //       }
                //     }
                //   }
                // });

                break;

            case "id":
                //console.log("ID");
                $scope.newUser = JSON.stringify({
                    tipo: "user",
                    id: $scope.notMessage.id,
                    user: $scope.sesion.usuario,
                    origen: $scope.sesion.origen
                }); //console.log($scope.newUser);
                $scope.conn.send($scope.newUser);
                break;

            case "leaveGroup":
                // $scope.getMyGroups();
                // $scope.getMember($scope.notMessage.data.id);


                break;
            case "joinGroup":
                $scope.getMyGroups();
                break;
            case "addGroup":
                $scope.getMyGroups();
                break;
            default:

        }
    }




    $scope.bot.onmessage = function (e) {

        $scope.notMessage = JSON.parse(e.data);

        console.log("RECIBIDO Bot: " + $scope.notMessage.tipo);

        //tipos de mensaje,  newActivity, UpdateActivity
        //console.log($scope.notMessage.tipo);
        switch ($scope.notMessage.tipo) {
            case "id":
                //console.log("ID");
                $scope.newUser = JSON.stringify({
                    tipo: "user",
                    id: $scope.notMessage.id,
                    user: "Bot" + $scope.sesion.origen,
                    origen: $scope.sesion.origen
                }); //console.log($scope.newUser);
                $scope.conn.send($scope.newUser);
                break;

            case "updateActivity":
                var tmpLog = {
                    notificacion: {
                        id: $scope.notMessage.notificacion,
                        id_actividad: $scope.notMessage.data.subeje,
                        tipo: $scope.notMessage.tipo,
                        target: 0,
                        colaborador: "Bot" + $scope.sesion.origen,
                        remitente: $scope.notMessage.remitente,
                        fecha: $scope.notMessage.fecha,
                        hora: $scope.notMessage.hora,
                        estado: "unseen",
                        campo: $scope.notMessage.data.activity.campo,
                        new_value: $scope.notMessage.data.activity.new_value,
                        last_value: $scope.notMessage.data.activity.last_value
                    },

                    subeje: $scope.notMessage.data.activity

                }

                //console.log(JSON.stringify(tmpLog));
                //console.log(JSON.stringify($scope.activities[$scope.notMessage.fecha]));
                if ($scope.activities[$scope.notMessage.fecha] == undefined) {
                    $scope.activities[$scope.notMessage.fecha] == [];
                }

                if ($scope.activities[$scope.notMessage.fecha]) {
                    $scope.activities[$scope.notMessage.fecha].unshift(tmpLog);
                    console.log("PUSH 1");

                }
                //$scope.activities[$scope.notMessage.fecha]=[tmpLog];
                //console.log(JSON.stringify($scope.activities));

                break;


            case "newSpec":
                var tmpLog = {
                    notificacion: {
                        id: $scope.notMessage.notificacion,
                        id_actividad: $scope.notMessage.data.subeje,
                        tipo: $scope.notMessage.tipo,
                        target: 0,
                        colaborador: "Bot" + $scope.sesion.origen,
                        remitente: $scope.notMessage.remitente,
                        fecha: $scope.notMessage.fecha,
                        hora: $scope.notMessage.hora,
                        estado: "unseen",
                        campo: $scope.notMessage.data.activity.campo,
                        new_value: $scope.notMessage.data.activity.new_value,
                        last_value: $scope.notMessage.data.activity.last_value
                    },

                    subeje: $scope.notMessage.data.activity

                }

                console.log(JSON.stringify(tmpLog));
                //console.log(JSON.stringify($scope.activities[$scope.notMessage.fecha]));
                if ($scope.activities[$scope.notMessage.fecha] == undefined) {
                    $scope.activities[$scope.notMessage.fecha] == [];
                }
                $scope.activities[$scope.notMessage.fecha].unshift(tmpLog);
                console.log("PUSH 2");
                //$scope.activities[$scope.notMessage.fecha]=[tmpLog];
                //console.log(JSON.stringify($scope.activities));
                //$scope.punchlist = $dom.getTickets()

                break;

        }

        $scope.$apply();


    }







    /*============= Comments ===============*/


    $scope.newComment = {
        id: "",
        activity_id: "",
        autor: "",
        comment: "",
        date: "",
        hour: ""
    }
    $scope.sendComment = function (reversed, objEnviarNot, comentario) {
        // $scope.newComment.comment.replace("\n", "<br>");
        console.log(JSON.stringify(comentario));
        if (selected.panel) {
            var data = {
                activity_id: selected.id,
                autor: comentario.autor,
                comment: comentario.comment,
                date: comentario.date,
                hour: comentario.hour,
                id_respuesta: comentario.id_respuesta
            }
            // var tmpURL = $scope.server+"/php/comment/altaComment.php?activity_id=" + selected.id + "&autor=" + $scope.newComment.autor + "&comment=" + $scope.newComment.comment + "&date=" + $scope.newComment.date+ "&hour=" + $scope.newComment.hour;
        } else {
            // var tmpURL = $scope.server+"/php/comment/altaComment.php?activity_id=" + selected.subeje.id + "&autor=" + $scope.newComment.autor + "&comment=" + $scope.newComment.comment + "&date=" + $scope.newComment.date+ "&hour=" + $scope.newComment.hour;
            var data = {
                activity_id: selected.subeje.id,
                autor: comentario.autor,
                comment: comentario.comment,
                date: comentario.date,
                hour: comentario.hour,
                id_respuesta: comentario.id_respuesta

            }
        }

        // data.comment.replace("'","\'");
        //
        // data.comment.replace('"','\"');
        //
        // alert(data.comment);

        console.log("ENVIADO MSG: " + data.comment);
        $http.post($scope.server + "/php/comment/altaCommentP.php", data).
        then(function (data) {
            console.log(JSON.stringify(data));

            console.log(data.data.status);
            if (data.data.status == "OK") {
                comentario.id = data.data.newMessage;

                $timeout(function(){
                    comentario.status = "enviado"

                }, 1000);

                if (objEnviarNot !== undefined) {
                    objEnviarNot.id_mensaje = "" + data.data.newMessage;
                    console.log(objEnviarNot);
                    $dom.insertarNotificaciones(objEnviarNot).then(function (res) {
                        console.log(res);
                        objEnviarNot.ids_usersDefinidos = res.data.detail;



                        console.log($scope.ImagenesUser($scope.usuario.nombre).ver);
                        var img = "";
                        if ($scope.ImagenesUser($scope.usuario.nombre).ver) {
                            img = "" + $scope.server + $scope.ImagenesUser($scope.usuario.nombre).src;
                        } else {
                            img = "img/generic-user.png";
                        }

                        var objEnviarNot2 = {
                            type: objEnviarNot.type,
                            objEnviarNot: objEnviarNot,
                            id_user: $scope.usuario.puesto,
                            id_users: objEnviarNot.id_users,
                            titulo_act: "Hola",
                            url: "https://genniux.net/app/board/",
                            usuario: $scope.usuario.nombre,
                            encargado_ahora: "",
                            app: 'boardmiplan',
                            img: '' + img,
                            titulo_cabecera: "Board nueva mención",
                            mensaje: $scope.usuario.nombre + ' dice: ' + "" + objEnviarNot.mensaje
                        };
                        $dom.enviarNotiMulti(objEnviarNot2).then(function (res) {
                            console.log(res);
                        });
                        $scope.LimpiarUsuarios();



                    });
                };
                //  if(reversed){
                //    selected.comments.unshift($scope.newComment);
                //  }
                //  else{

                comentario.hour = comentario.tmpH;
                    

                setTimeout(function () {


                    var objDiv = document.getElementById("contentMessageBox");
                    if (objDiv) {
                        objDiv.scrollTop = objDiv.scrollHeight;
                    }

                    var objDiv = document.getElementById("comments");
                    if (objDiv) {
                        objDiv.scrollTop = objDiv.scrollHeight;
                    }
                }, 300);
                //  }


                //console.log($scope.conversation.origen);


                if (selected.origen == 'private') {
                    var targets = [selected.subeje.responsable_1, selected.subeje.responsable_2];
                    $scope.conversation.lastComment = comentario;
                } else if (selected.origen == 'forum') {

                    var autores = [];

                    console.log(JSON.stringify(selected));
                    for (var i = 0; i < selected.comments.length; i++) {
                        var tmpComment = selected.comments[i];
                        if (autores.length == 0) {
                            autores.push(tmpComment.autor)
                            //console.log(tmpComment.autor);
                        } else {
                            var encontrado = false;
                            for (var j = 0; j < autores.length; j++) {
                                if (autores[j] == tmpComment.autor) {
                                    encontrado = true;
                                    break;
                                }
                            }

                            if (!encontrado) {
                                autores.push(tmpComment.autor);
                            }
                        }
                    }

                    var targets = autores;
                }

                //console.log(JSON.stringify(targets));

                var tmpSubeje = angular.copy(selected);

                if (tmpSubeje.panel) {
                    var data = {
                        subeje: tmpSubeje.id,
                        target: comentario.id,
                        conversation: {
                            subeje: tmpSubeje,
                            origen: tmpSubeje.origen
                        },
                        comment:comentario
                    };
                    data.conversation.subeje.comments = [];
                    data.conversation.subeje.specs = [];
                } else {
                    var data = {
                        subeje: selected.subeje.id,
                        target: comentario.id,
                        conversation: {
                            subeje: selected.subeje,
                            origen: $scope.conversation.origen
                        },
                        comment: comentario
                    };
                    data.conversation.subeje.comments = [];
                    $scope.conversation.lastComment = comentario;
                }

                console.log(JSON.stringify(data));

                if (selected.origen == "forum") {
                    $scope.sendMessage("newComment", targets, data, true); //ultimos dos valores log = true grupo = false
                } else {
                    $scope.sendMessage("newComment", targets, data, false);

                }

                //  console.log(selected.lastComment);

                //console.log(selected.comments.length);

            }
        });
    }
    var selected = {};

    $scope.evaluateMessage = function (panel) {
        if ($scope.editingComment) {

            // console.log(JSON.stringify($scope.conversation));
            if ($scope.conversation.type == "group") {

                console.log("GROUP");
                $scope.editComment('group');

            } else {
                $scope.editComment('conversation');

            }
        } else {

            if (panel == null) {
                $scope.addComment($scope.conversation, true);
            } else {
                $scope.addComment();

            }
        }

    }


    $scope.LimpiarUsuarios = function () {
        $scope.contador = 0;
        for (var i in $scope.usuarios) {
            //console.log($scope.usuarios[i])
            Object.defineProperty($scope.usuarios[i], "check", {
                value: false,
                writable: true,
                enumerable: true,
                configurable: true
            });
        }

    }


    $scope.insertComment = function (conversation, text) {

        comment = {
            comment: text,
            date: "",
            hour: ""
        }

        var d = new Date();


        var month = d.getMonth() + 1;

        var day = d.getDate();

        if (month < 10) {

            month = "0" + month;
            //console.log("Added: "+$scope.newComment.date);
        }

        if (day < 10) {
            day = "0" + day;

        }

        comment.date = d.getFullYear() + "-" + month + "-" + day;
        comment.hour = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
        comment.tmpH = d.getHours() + ":" + d.getMinutes();
        comment.autor = $scope.sesion.usuario;

        var data = {
            activity_id: conversation.id,
            autor: comment.autor,
            comment: comment.comment,
            date: comment.date,
            hour: comment.hour
        }


        console.log("ENVIADO MSG: " + data.comment);
        $http.post($scope.server + "/php/comment/altaCommentP.php", data).
        then(function (data) {

            if (data.status == "OK") {


                /*         var targets = [$scope.tmp];
                        $scope.sendMessage("newComment", targets, data, true); //ultimos dos valores log = true grupo = false
                        */
            }

            console.log(JSON.stringify(data));

        });

    }
    var tmpIDComment = 0;

    $scope.addComment = function (eje, reversed) {
        //console.log(JSON.stringify(eje));

/*         console.warn(eje);
        console.warn(reversed); */
        if (eje == undefined) {
            selected = $dom.getSelected();
            selected.origen = 'forum';
            selected.panel = true;

            tmpComment = angular.copy($scope.selected.tmpComment);
            console.log(JSON.stringify(tmpComment));
            $scope.selected.tmpComment = {
                id: "",
                activity_id: "",
                autor: "",
                comment: "",
                date: "",
                hour: "",
                editado: false,
                respuesta: null,
                status: "pendiente"
            }


        } else {
            selected = eje;
            //selected.comments = eje.comments;
            selected.origen = $scope.conversation.origen;
            selected.panel = false;


            tmpComment = angular.copy($scope.conversation.tmpComment);
            console.log(JSON.stringify(tmpComment));
            //console.log($scope.conversation.tmpComment);
            $scope.conversation.tmpComment = {
                id: "",
                activity_id: "",
                autor: "",
                comment: "",
                date: "",
                hour: "",
                editado: false,
                id_respuesta: null,
                respuesta_autor: null,
                respuesta_comment: null,
                status: "pendiente"
            }

            console.log("eje");
        }
        //console.log($scope.selected);

        // console.log("Add Comment");
        //
        // console.log($scope.newComment.comment);

        tmpComment.status = "pendiente";


        if (tmpComment.comment != "") {
            var d = new Date();

            tmpComment.activity_id = selected.id;

            var month = d.getMonth() + 1;
            var day = d.getDate();
            var horas = d.getHours();
            var minutos = d.getMinutes();

            if (month < 10) {

                month = "0" + month;
                //console.log("Added: "+$scope.newComment.date);
            }

            if (day < 10) {
                day = "0" + day;

            }

            tmpComment.date = d.getFullYear() + "-" + month + "-" + day;
            if (horas < 10) {
                horas = "0" + horas;
            }

            if (minutos < 10) {
                minutos = "0" + minutos;
            }

            tmpComment.hour = horas + ":" + minutos + ":" + d.getSeconds();
            tmpComment.tmpH = horas + ":" + minutos;

            tmpComment.autor = $scope.sesion.usuario;
            // $scope.newComment.comment.replace(/(\r\n\t|\n|\r\t)/gm,"<br>");
            // console.log("BREAK "+$scope.newComment.comment);
            //console.log($scope.conversation.origen);
            if (selected.origen != 'group' && tmpComment.comment != "") {
                console.log("Add comment");
                if (reversed === undefined) {
                    var com = tmpComment.comment.split("@");
                    console.log(tmpComment.comment.split("@"));
                    var arrUserEnviar = [];
                    var arrUserEnviarFinal = [];

                    for (var i in $scope.usuarios) {
                        var n = tmpComment.comment.indexOf("@" + $scope.usuarios[i].wikiname);
                        if (n != -1) {
                            //                               console.log(n);
                            //                               console.log($scope.usuarios[i].wikiname);
                            arrUserEnviarFinal.push($scope.usuarios[i].puestoID);

                        };

                    }

                    var id_act = "";
                    var prioridad = "";
                    var titulo = "";
                    if (selected.id === undefined) {
                        id_act = selected.subeje.id;
                        prioridad = selected.subeje.prioridad;
                        titulo = selected.subeje.titulo;

                        console.log(selected.subeje);
                    } else {
                        id_act = selected.id;
                        prioridad = selected.prioridad;
                        titulo = selected.titulo;
                        console.log(selected);

                    }
                    // alert(selected.eje);
                    var miappActual = "";
                    if (selected.eje === "si" || selected.eje === "no") {
                        miappActual = "objetivo";
                    } else if (selected.eje === "Ticket") {
                        miappActual = "punchlist";

                    } else if (selected.eje === "Noticia") {
                        miappActual = "all";

                    };

                    var objEnviarNot = {
                        type: selected.type,
                        ids_usersDefinidos: [],
                        id_actividad: id_act,
                        prioridad: encodeURIComponent(prioridad),
                        titulo: encodeURIComponent(titulo),
                        id_mensaje: '',
                        mensaje: tmpComment.comment,
                        comment: tmpComment.comment,
                        id_users: arrUserEnviarFinal,
                        id_user_envio: $scope.sesion.puesto,
                        app: "" + miappActual,
                        estatus: "" + 0,
                        visto: "" + 0,
                        firma: "" + 0,
                        fecha_pub: $scope.getDateTimeActual().date,
                        hora_pub: $scope.getDateTimeActual().time,
                        fecha_visto: "0000-00-00",
                        hora_visto: "00:00"
                    };

                    /*
fecha_pub
hora_pub
fecha_visto
hora_visto
*/



                    tmpIDComment--;
                    tmpComment.id = tmpIDComment;
                    selected.comments.push(tmpComment);

                    $scope.sendComment(reversed, objEnviarNot,tmpComment);
                    // $scope.LimpiarUsuarios();
                } else {
                    tmpIDComment--;
                    tmpComment.id = tmpIDComment;
                    selected.comments.push(tmpComment);

                    $scope.sendComment(reversed,undefined,tmpComment);
                }

            } else if (selected.origen == "group" && tmpComment.comment != "") {
               
                tmpIDComment--;
                tmpComment.id = tmpIDComment;
                selected.comments.push(tmpComment);

                $scope.addMessage(tmpComment);
            }





        } else {
            console.log("Vacio");
        }


    }

    $scope.getDateTimeActual = function () {
        var d = new Date();
        return {
            time: d.getHours() + ":" + d.getMinutes(),
            date: d.getFullYear() + "-" + ('0' + parseInt(d.getMonth() + 1)).slice(-2) + "-" + ('0' + parseInt(d.getDate())).slice(-2)
        };
    }

    $scope.scrollComments = function () {
        var elem = document.getElementById('comments');
        elem.scrollTop = elem.scrollHeight;
    }


    $scope.opcionesComment = function (ev, el, origin) {
        $scope.selectedComment = el;
        $scope.selectedComment.origin = origin;
     
            ons.createPopover("comments-opciones.html", {
                parentScope: $scope
            }).then(function (d) {
                $scope.commentDialog = d;
                d.show(ev.srcElement);
            });
        
    }


    $scope.hideOpcionesComment = function () {
        $scope.commentDialog.hide();
    }

    $scope.editingComment = false;

    $scope.flagEditComment = function () {
        console.log("flag");
        $scope.editingComment = true;
        $scope.tmpComment = angular.copy($scope.selectedComment);
        $scope.tmpComment.id_respuesta = null;
        $scope.tmpComment.respuesta_autor = null;
        $scope.tmpComment.respuesta_comment = null;

        console.log(JSON.stringify($scope.tmpComment));

        if ($scope.tmpComment.origin == "panel") {
            $scope.selected.tmpComment = $scope.tmpComment;

        } else {
            $scope.conversation.tmpComment = $scope.tmpComment;

        }
        $scope.commentDialog.hide();

    }


    $scope.chageStatusComment = function (estatus) {
        var deferred = $q.defer();

        var req = {
            method: "POST",
            url: "../../../php/comment/disableComment.php",
            headers: {
                "Content-Type": undefined
            },
            data: {
                id: $scope.selectedComment.id,
                status: estatus
            }
        };

        $http(req).then(function (data) {
            console.log(JSON.stringify(data.data));
            deferred.resolve(data.data);
        });

        return deferred.promise;
    };

    $scope.disableComment = function () {
        $scope.tmpComment.editing = true;

        $scope.chageStatusComment("disable").then(function (data) {
            $scope.selectedComment.status = "disable";

            $scope.tmpComment.success = true;
            $scope.tmpComment.editing = false;
        });
    };

    $scope.enableComment = function () {
        $scope.chageStatusComment("").then(function (data) {
            $scope.selectedComment.status = "";
        });
    };


    $scope.showDeleteCommentDialog = function ($event) {
        /*         console.log(JSON.stringify(modelo))
         */
        ons
            .createPopover("removeComment.html", {
                parentScope: $scope,
                append: true
            })
            .then(function (d) {
                $scope.removeCommentModal = d;
                d.show($event.target);
            });
    };

    $scope.hideDeleteCommentDialog = function () {
        $scope.removeCommentModal.hide();
    };

    $scope.showEditCommentDialog = function ($event) {

        console.log("EDIT COMMENT");
        ons
            .createPopover("editComment.html", {
                parentScope: $scope,
                append: true
            })
            .then(function (d) {
                $scope.editCommentDialog = d;
                d.show($event.target);
            });
    };

    $scope.hideEditCommentDialog = function () {
        $scope.editCommentDialog.hide();
    };



    $scope.responderMensaje = function (tipo) {
        console.log($scope.selectedComment);

        if ($scope.selectedComment.origin == "panel") {
            $scope.selected.tmpComment.id_respuesta = $scope.selectedComment.id;
            $scope.selected.tmpComment.respuesta_autor = $scope.selectedComment.autor;
            $scope.selected.tmpComment.respuesta_comment = $scope.selectedComment.comment;


        } else {
            console.log(JSON.stringify($scope.conversation));
            // $scope.conversation.tmpComment.respuesta = angular.copy($scope.selectedComment);

            $scope.conversation.tmpComment.id_respuesta = $scope.selectedComment.id;
            $scope.conversation.tmpComment.respuesta_autor = $scope.selectedComment.autor;
            $scope.conversation.tmpComment.respuesta_comment = $scope.selectedComment.comment;

        }
    }


    $scope.cancelRespuesta = function () {

        if ($scope.selectedComment.origin == "panel") {
            $scope.selected.tmpComment.id_respuesta = null;
            $scope.selected.tmpComment.respuesta_autor = null;
            $scope.selected.tmpComment.respuesta_comment = null;
        } else {
            $scope.conversation.tmpComment.id_respuesta = null;
            $scope.conversation.tmpComment.respuesta_autor = null;
            $scope.conversation.tmpComment.respuesta_comment = null;

        }
    }

    $scope.editComment = function () {


        $scope.tmpComment.editing = true;


        console.log($scope.selectedComment.origin);
        var type = "";

        if ($scope.selectedComment.origin == "group") {
            type = "group";
        } else {
            type = "conversation";
        }

    /*     var comment = "";

        if ($scope.selectedComment.origin == "panel") {
            comment = $scope.selected.tmpComment.comment;

        } else {
            comment = $scope.conversation.tmpComment.comment;

        } */

        $http.get($scope.server + "/php/comment/edicionComment.php?id=" + $scope.selectedComment.id + "&comentario=" + $scope.tmpComment.comment + "&type=" + type).
        then(function (data) {
            console.log(JSON.stringify(data));

            $scope.tmpComment.editing = false;


            if (data.data.status == "OK") {
                $scope.selectedComment.comment = $scope.tmpComment.comment;
                $scope.selectedComment.editado = true;


                console.log($scope.selectedComment.comment);

/*                 if ($scope.selectedComment.origin == "panel") {
                    $scope.selected.tmpComment.comment = "";

                } else {
                    $scope.conversation.tmpComment.comment = "";

                } */

                $scope.tmpComment.success = true;

                $scope.editingComment = false;


                $timeout(function () {
                    $scope.hideEditCommentDialog();
                    $scope.tmpComment.success = false;
                }, 1500);
            }

        });
    }

    $scope.removeComment = function (type, $event) {
        console.log("remove");

        $scope.removeCom = true;


        $scope.avoidRemoveComment = function () {
            $scope.removeCom = false;
            $scope.addCommentList();
            toastComment.toggle();
        }

        $scope.removeCommentList = function () {
            var selected = {};

            if ($scope.selectedComment.origin == 'panel') {
                selected = $dom.getSelected();
            } else {
                selected = $scope.conversation;
            }


            for (var i = 0; i < selected.comments.length; i++) {
                if (selected.comments[i].id == $scope.selectedComment.id) {
                    selected.comments.splice(i, 1);
                    $scope.commentIndex = i;
                    $scope.$apply();
                    console.log("quitado");
                    break;
                }
            }
        }

        $scope.addCommentList = function () {

            if ($scope.selectedComment.origin == 'panel') {
                $scope.selected.comments.splice($scope.commentIndex, 0, $scope.selectedComment);

            } else {
                $scope.conversation.comments.splice($scope.commentIndex, 0, $scope.selectedComment);
            }
            //$scope.$apply();
        }


        ons.notification.confirm({
            message: '¿Borrar este comentario?',
            modifier: "flat",
            callback: function (idx) {
                switch (idx) {
                    case 0:
                        break;
                    case 1:
                        $scope.removeCommentList();
                        toastComment.toggle();

                        document.getElementById("toastComment").style.zIndex = "99999999999999999";
                        //alert("z-index");

                        setTimeout(function () {

                            if ($scope.removeCom) {
                                console.log("REMOVER");
                                toastComment.toggle();

                                $http.get($scope.server + "/php/comment/bajaComment.php?id=" + $scope.selectedComment.id + "&type=" + type).
                                then(function (data) {

                                    console.log(JSON.stringify(data));
                                    if (data.data.status == 'OK') {


                                    }
                                });
                            }
                            $scope.removeCom = true;

                        }, 4000);

                        break;


                        /*  if($scope.messageType=="group"){
        $scope.getMessage();
      }
      else if($scope.messageType=="conversation"){
      $scope.getComment();

    }*/


                        //$scope.removeNotification("newComment",id);

                        /*ons.notification.alert({
    message: "Comment sucessfully deleted"
  });*/
                }

            }

        });
        $scope.commentDialog.hide();
    }


    $scope.getCommentHistory = function (comment) {
        $http.get($scope.server + "/php/comment/getHistory.php?id=" + comment.id).then(function (data) {
            console.log(JSON.stringify(data));
            $scope.selectedComment = comment;
            $scope.selectedComment.historial = data.data.historial
            $scope.showHistory();
        });
    }


    $scope.showHistory = function () {
        ons.createDialog("history.html", {
            parentScope: $scope
        }).then(function (dialog) {
            dialog.show();
        });

    }



    $scope.getComment = function (conversation) {

        var deferred = $q.defer();
        console.log($scope.server + "/php/comment/consultaComment.php?activity_id=" + conversation.subeje.id + "&user=" + $scope.sesion.usuario + "&last=" + conversation.lastID);
        //console.log(JSON.stringify(conversation));

        var url = "";
        if (conversation.lastID != null) {
            url = $scope.server + "/php/comment/consultaComment.php?activity_id=" + conversation.subeje.id + "&user=" + $scope.sesion.usuario + "&reverse=" + true + "&last=" + conversation.lastID;

        } else {
            var url = $scope.server + "/php/comment/consultaComment.php?activity_id=" + conversation.subeje.id + "&user=" + $scope.sesion.usuario + "&reverse=" + true;

        }
        $http.get(url).then(function (data) {
            deferred.resolve(data.data);
        });
        return deferred.promise;

    };

    /*================== SPECS =====================*/



    $scope.newSpec = {
        id: "",
        estatus: "",
        descripcion: ""
    };


    $scope.removeSp = true;


    $scope.avoidRemoveSpec = function () {
        $scope.removeSp = false;
        $scope.addSpecList();
        toastSpec.toggle();
    }


    $scope.removeSpecList = function () {
        for (var i = 0; i < $scope.selected.specs.length; i++) {
            if ($scope.selected.specs[i].id == $scope.selectedSpec.id) {
                $scope.selected.specs.splice(i, 1);
                $scope.specIndex = i;
                $scope.$apply();
                console.log("quitado");
                break;
            }
        }
    }

    $scope.addSpecList = function () {
        $scope.selected.specs.splice($scope.specIndex, 0, $scope.selectedSpec);
        //$scope.$apply();
    }

    $scope.addSpec = function () {


        $scope.selected = $dom.getSelected();
        $scope.id = $scope.selected.id;

        //  console.log(JSON.stringify($scope.newSpec));
        //console.log(JSON.stringify($scope.selected));



        if ($scope.newSpec.descripcion != '') {
            console.log("../../php/specsAPI/altaSpec.php?objetivo=" + $scope.id + "&descripcion=" + $scope.newSpec.descripcion);
            $http.get("../../php/specsAPI/altaSpec.php?objetivo=" + $scope.id + "&descripcion=" + $scope.newSpec.descripcion).
            then(function (data) {
                console.log(JSON.stringify(data));

                var tmpEje = angular.copy($scope.selected);
                tmpEje.comments = [];
                tmpEje.specs = [];
                $scope.newSpec.id = data.data.newSpec;
                var data = {
                    subeje: tmpEje.id,
                    target: data.data.newSpec,
                    activity: tmpEje,
                    spec: $scope.newSpec
                };
                var targets = [];
                if (tmpEje.responsable_1 == tmpEje.responsable_2) {
                    targets = [tmpEje.responsable_1];
                } else {
                    targets = [tmpEje.responsable_1, tmpEje.responsable_2];
                }

                //alert(JSON.stringify(targets));

                $scope.sendMessage("newSpec", targets, data, true);

                $scope.selected.specs.push($scope.newSpec);
                //$scope.getSpec();
                $scope.newSpec = {
                    id: "",
                    estatus: "",
                    descripcion: ""
                };
                //$scope.cajaDesc.value = "";

                //$scope.targetUsers=[$scope.info.responsable_1,$scope.info.responsable_2];
                //$scope.getTargets();
                //$scope.info.target=data.newSpec;
                //$scope.sendMessage("newSpec",$scope.allUsers,$scope.info);

            });
        }
    }

    $scope.toggleSpec = function (spec) {

        $scope.selectedSpec = spec;
        if ($scope.selectedSpec.estatus == "Pendiente") {
            $scope.selectedSpec.estatus = "Completado";
        } else {
            $scope.selectedSpec.estatus = "Pendiente";
        }
        $http.get("../../php/specsAPI/edicionSpec.php?id=" + $scope.selectedSpec.id + "&descripcion=" + $scope.selectedSpec.descripcion + "&estatus=" + $scope.selectedSpec.estatus).
        then(function (data) {
            console.log(JSON.stringify(data));
        });
    }



    $scope.opcionesSpec = function (ev, el, ticket) {
        $scope.selectedSpec = el;
        if (ticket !== undefined) {
            $scope.selected = ticket; //CAMBIO
        };
        ons.createPopover("specs-opciones.html", {
            parentScope: $scope
        }).then(function (d) {
            $scope.specDialog = d;
            d.show(ev.srcElement);
        });

    }

    $scope.editingSpec = false;

    $scope.flagEditSpec = function () {
        console.log("flag");
        $scope.editingSpec = true;
        $scope.tmpSpec = angular.copy($scope.selectedSpec);
        $scope.newSpec = $scope.tmpSpec;
        $scope.specDialog.hide();

    }

    $scope.editSpec = function (type) {
        $http.get("../../php/specsAPI/edicionSpec.php?id=" + $scope.newSpec.id + "&descripcion=" + $scope.newSpec.descripcion + "&estatus=" + $scope.newSpec.status).
        then(function (data) {
            console.log(JSON.stringify(data));
            /*if($scope.messageType=="conversation"){
    $scope.getComment();
  }
  else if($scope.messageType=="group"){
  $scope.getMessage();
}*/

            if (data.data.status == "OK") {
                $scope.selectedSpec.descripcion = $scope.tmpSpec.descripcion;
                $scope.newSpec.descripcion = "";
                $scope.editingSpec = false;
            }

        });
    }

    $scope.removeSpec = function (type) {
        console.log("remove");

        ons.notification.confirm({
            message: 'Are you sure you want to delete "' + $scope.selectedSpec.descripcion + '" ?',
            modifier: "flat",
            callback: function (idx) {
                switch (idx) {
                    case 0:
                        break;
                    case 1:



                        $scope.removeSpecList();
                        toastSpec.toggle();
                        document.getElementById("toastSpec").style.zIndex = "99999999999999999";

                        setTimeout(function () {

                            if ($scope.removeSp) {
                                console.log("REMOVER");
                                toastSpec.toggle();

                                $http.get("../../php/specsAPI/bajaSpec.php?id=" + $scope.selectedSpec.id).
                                then(function (data) {

                                    console.log(JSON.stringify(data));
                                    if (data.data.status == 'OK') {

                                        /*  if($scope.messageType=="group"){
                $scope.getMessage();
              }
              else if($scope.messageType=="conversation"){
              $scope.getComment();

            }*/


                                        //$scope.removeNotification("newComment",id);

                                        /*ons.notification.alert({
            message: "Comment sucessfully deleted"
          });*/
                                    }
                                });
                            }
                            $scope.removeSp = true;

                        }, 4000);





                        break;
                }

            }
        });
        $scope.specDialog.hide();
    }



    /*=============== GANTT ===================*/

    //api.rows.on.move(row, oldIndex, newIndex)

    $scope.fullHeader = ['month', 'week', 'day'];
    $scope.weekHeader = ['month', 'week'];
    $scope.middleHeader = ['month', 'day'];
    $scope.minHeader = ['month'];

    $scope.headersFormats = {
        'year': 'YYYY',
        'quarter': '[Q]Q YYYY',
        month: 'MMM YYYY',
        week: 'w',
        day: 'D',
        hour: 'H',
        minute: 'H:mm',
        second: 'H:mm:ss',
        millisecond: 'H:mm:ss:SSS'
    };

    $scope.ganttRange = "1";

    $scope.showLoadGantt = function () {
        // ons.createAlertDialog("loadGantt.html",{parentScope:$scope}).then(function(alert){
        // $scope.loadDialog = alert;
        // $scope.loadDialog.show();
        //});
        //alert()
        $scope.loadingGantt = true;

        //$scope.loadingGantt=true;
    }

    $scope.hideLoadGantt = function () {
        //$scope.loadDialog.hide();
        //$scope.loadDialog.hide();
        $scope.loadingGantt = false;
    }

    $scope.showGantt = function () {
        //document.getElementById('gantt').style.display='block';
        ons.createAlertDialog("gantt.html", {
            parentScope: $scope
        }).then(function (alert) {
            $scope.ganttDialog = alert;
            $scope.ganttDialog.show();
        });

    }

    $scope.hideGantt = function () {
        $scope.gantt = {};
        $scope.ganttDialog.hide();
        $scope.ganttRange = "1";


    }

    $scope.setSelectedGanntNode = function (nodo) {
        alert("Nodo");
        console.log("SELECTED");
        console.log(JSON.stringify(nodo));
        $dom.setGanttNode(nodo);
    }

    $scope.generateGantt = function () {

        $scope.ganttNode = $dom.getGanttNode();


        console.log(JSON.stringify($scope.ganttNode));
        $scope.showGantt();
        $scope.showLoadGantt();

        //$scope.loadGanttScreen.show();
        $scope.getGantt();


    }

    $scope.reloadGantt = function (ganttRange) {
        $scope.ganttRange = ganttRange;
        console.log("RANGO: " + ganttRange);
        $scope.showLoadGantt();
        $scope.getGantt();
    }

    $scope.getGantt = function () {


        $scope.gantt = {};
        $scope.ganttSelected = {};

        console.log("../../php/gantt/create.php?cuenta=" + $scope.sesion.origen + "&board=" + $scope.ganttNode.id + "&months=" + $scope.ganttRange);
        $http.get("../../php/gantt/create.php?cuenta=" + $scope.sesion.origen + "&board=" + $scope.ganttNode.id + "&months=" + $scope.ganttRange).
        then(function (data) {
            console.log(JSON.stringify(data.data));
            $scope.gantt = data.data.detail;
            $scope.gantt.tam = data.data.tam;
            $scope.gantt.minDate = Date.parse(data.data.minDate);
            $scope.gantt.maxDate = Date.parse(data.data.maxDate);
            //console.log("GANTT: "+$scope.data.length);
            if ($scope.ganttRange == "1") {
                $scope.actualHeader = $scope.middleHeader;

            } else {
                $scope.actualHeader = $scope.weekHeader;

            }

            var difMonth = data.data.difMonth;
            var difYear = data.data.difYear;



            if (difYear == 0) {
                if (difMonth > 3) {
                    $scope.actualHeader = $scope.weekHeader;

                }
                if (difMonth > 6) {
                    $scope.actualHeader = $scope.minHeader;
                }
                if (difMonth < 3) {
                    $scope.actualHeader = $scope.middleHeader;
                }

            } else {
                $scope.actualHeader = $scope.minHeader;
            }

            //alert($scope.ganttRange+" - "+$scope.actualHeader);
            $scope.hideLoadGantt();

        });
    }


    $scope.getAxisInfo = function (toggle, board) {
        var boardID = "";
        var panel = "";
        if (toggle == "show") {
            boardID = board;
            panel = "izquierdo";
        } else {
            boardID = $scope.currentTask.id;
            panel = "derecho";
        }
        //alert(JSON.stringify(board));
        console.log("../../php/gantt/getActivity.php?cuenta=" + $scope.sesion.origen + "&board=" + boardID + "&user=" + $scope.sesion.usuario);
        $http.get("../../php/gantt/getActivity.php?cuenta=" + $scope.sesion.origen + "&board=" + boardID + "&user=" + $scope.sesion.usuario).
        then(function (data) {



            $scope.ganttSelected = data.data.eje;

            $scope.toggleDerecho($scope.ganttSelected);
            if (panel == "derecho") {
                if ($scope.currentTask != undefined) {
                    var inicioD = new Date($scope.currentTask.from);
                    var finD = new Date($scope.currentTask.to);

                    $scope.ganttSelected.fecha_inicio = inicioD.getFullYear() + "-" + (inicioD.getMonth() + 1) + "-" + inicioD.getDate();
                    $scope.ganttSelected.fecha_fin = finD.getFullYear() + "-" + (finD.getMonth() + 1) + "-" + finD.getDate();

                    $scope.updateOnServer("fecha_inicio", $scope.ganttSelected.fecha_inicio, $scope.ganttSelected.id);
                    $scope.updateOnServer("fecha_fin", $scope.ganttSelected.fecha_fin, $scope.ganttSelected.id);

                }


            }






            $scope.InfoRight(null, $scope.ganttSelected);

            if (toggle == "show") {
                $scope.togglePanel(toggle);
            }

        });




    }


    $scope.getSelectedGantt = function (id) {
        //alert(id);
        var encontrado = false;
        var finalGantt = "";
        for (var i = 0; i < $scope.gantt.length; i++) {
            if (encontrado) {
                break;
            } else {
                console.log($scope.gantt[i].id + " - " + id);
                if ($scope.gantt[i].id == id) {
                    finalGantt = $scope.gantt[i];
                    console.log("FOUND " + id);
                    encontrado = true;
                    break;
                } else {
                    var actualGantt = $scope.gantt[i].tasks;

                    for (var j = 0; j < actualGantt.length; j++) {
                        console.log(actualGantt[j].id + " - " + id);

                        if (actualGantt[j].id == id) {
                            finalGantt = actualGantt[j];
                            console.log("FOUND " + id);
                            encontrado = true;
                            break;
                        }
                    }
                }
            }


        }

        return finalGantt;
    }




    $scope.registerApi = function (api) {
        api.core.on.ready($scope, function () {

        });

        api.tasks.on.change($scope, function (task) {
            //alert("change");
            //$scope.currentTask = gantt.getTask(task);;
            console.log(JSON.stringify(task.model));
            $scope.currentTask = task.model;
            $scope.getAxisInfo('hide');


            //task.content ="<span>:v</span>";

        });

        /*api.tasks.on.rowChange($scope,function(task, oldRow){
  alert(task.model.id+" - "+oldRow.model.id);
});*/

        api.tasks.on.beforeRowChange($scope, function (task, newRow) {
            //alert(task.model.titulo+" - "+newRow.model.titulo);
            //  $scope.updateOnServer("padre",newRow.model.id,task.model.id);

        });
        //api.tasks.on.moveEnd(task)

    }



    /*=================================== CHAT =======================================*/



    /*====================== Chat ========================================= */



    $scope.chatContacts = "fondoClaro";
    $scope.chatForum = "fondo-azul";
    $scope.activeTab = 'forum';
    $scope.members = $scope.usuarios;
    $scope.conversations = {};

    $scope.selectedFC = "private";

    $scope.chatNotifications = {
        private: 0,
        group: 0,
        forum: 0
    };


    $scope.setSelectedFC = function (type) {
        $scope.selectedFC = type;
    }

    $scope.showContacts = false;

    $scope.showMembersBar = function () {

        if ($scope.showContacts == false) {
            $scope.getMember($scope.conversation.subeje.id).then(function (data) {

                $scope.showContacts = true;

            });

        } else {
            $scope.showContacts = false;
        }

        console.log($scope.showContacts);
    }

    $scope.hideMembersBar = function () {
        $scope.showContacts = false;
    }





    $scope.getConversations = function () {

        $http.get($scope.server + "/php/comment/getConversation.php?colaborador=" + $scope.sesion.usuario + "&origen=" + $scope.sesion.origen).then(function (data) {
            //console.log(JSON.stringify(data.data));
            if (data.data.Status == "OK") {
                $scope.conversations = data.data.detail;
                $scope.chatNotifications.forum = data.data.notificaciones;
                if ($scope.chatNotifications != null && $scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private > 0) {
                    $scope.GBoard = "(" + ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private) + ") " + "GBoard";
                    document.title = "" + $scope.GBoard;
                } else {
                    $scope.GBoard = "GBoard";
                    document.title = "" + $scope.GBoard;
                }
            }

        });
    }



    $scope.searchInConversation = function (id) {
        console.log(id);
        var conversation = undefined;
        //console.log(JSON.stringify($scope.conversations));
        for (var i = 0; i < $scope.conversations.length; i++) {

            console.log($scope.conversations[i].subeje.id);
            if ($scope.conversations[i].subeje.id == id) {
                console.log(JSON.stringify($scope.conversations[i]));
                conversation = $scope.conversations[i];
            }
        }

        if (conversation == undefined) {
            for (var i = 0; i < $scope.privates.length; i++) {

                //console.log($scope.privates[i].subeje.id);
                if ($scope.privates[i].subeje.id == id) {
                    console.log(JSON.stringify($scope.privates[i]));
                    conversation = $scope.privates[i];
                }
            }
        }

        return conversation;


    }


    $scope.searchInGroup = function (id) {
        var grupo = undefined;
        console.log(id);
        for (var i = 0; i < $scope.misGrupos.length; i++) {
            console.log(id + " - " + $scope.misGrupos[i].subeje.id);
            if ($scope.misGrupos[i].subeje.id == id) {
                grupo = $scope.misGrupos[i];
                break;
            }
        }

        return grupo;
    }



    $scope.messageTypeSub = ""

    $scope.setCurrentConversation = function (conversation, origen) {
        conversation.origen = origen;
        $scope.conversation = conversation;

        if ($scope.conversation.tmpComment == null) {
            $scope.conversation.tmpComment = {
                id: "",
                activity_id: "",
                autor: "",
                comment: "",
                date: "",
                hour: "",
                editado: false,
                id_respuesta: null,
                respuesta_autor: null,
                respuesta_comment: null,
                status: "pendiente"
            }
        }

        console.log(JSON.stringify($scope.conversation));


        //info.setInfo($scope.conversation.subeje);

        //if($scope.conversation.comments.length==0){
        //  $scope.getComment();
        //  }


    }

    /*
    $scope.setCurrentGroup=function(group,origen){


      group.origen=origen;
      $scope.conversation = group;

      $scope.getMessage($scope.conversation).then(function(data){

        if($scope.conversation.lastID == null){
          console.log("Reload Messages");
          if(data.response=="OK"){
            $scope.conversation.comments = data.detail;
            $scope.goBottom();
          }
        }
        else{
          $scope.conversation.comments.unshift(data.detail);
        }


        $scope.conversation.lastID = data.detail[0].id;

      });

    }
    */


    $scope.setCurrentGroup = function (group, origen) {


        group.origen = origen;
        // $scope.togglePanel("hide");
        // $scope.conversation = {
        //   subeje:{
        //     id:group.grupo,
        //     titulo:group.grupoN,
        //     newMessage:group.newMessage
        //   },
        //   origen: group.origen,
        //   comments:{},
        //   lastComment:{},
        //   miembros:group.miembros
        // };

        $scope.conversation = group;

        if ($scope.conversation.tmpComment == null) {
            $scope.conversation.tmpComment = {
                id: "",
                activity_id: "",
                autor: "",
                comment: "",
                date: "",
                hour: "",
                editado: false,
                id_respuesta: null,
                respuesta_autor: null,
                respuesta_comment: null,
                status: "pendiente"
            }
        }

        // $scope.info=$scope.conversation.subeje;
        // $scope.currentGroup=group;
        // $scope.selectedGroup=group.grupo;

        //  console.log(JSON.stringify($scope.conversation));

        // if($scope.conversation.comments.length==0){



        if ($scope.conversation.lastID == null) {
            $scope.getMessage($scope.conversation).then(function (data) {

                console.log("Reload Messages");
                if (data.response == "OK") {
                    $scope.conversation.comments = data.detail;
                    $scope.goBottom();
                    $scope.conversation.lastID = $scope.conversation.comments[0].id;
                }

            });
        }

        // }
        // else{
        //   console.log("Keep Messages");
        //   $scope.goBottom();
        // }

    }

    $scope.toggleChatClass = function (select) {
        if (select == "contacts") {
            $scope.chatContacts = "fondo-azul";
            $scope.chatForum = "fondoClaro";
            console.log("Set Contacts");
            $scope.activeTab = 'conversation';
        } else {
            $scope.chatContacts = "fondoClaro";
            $scope.chatForum = "fondo-azul";
            $scope.activeTab = 'forum';
            console.log("Set Forum");
        }
    }

    $scope.conversation = undefined;


    /*
    $scope.setCurrentPrivate = function(privateChat,origen){

      $scope.messageType="conversation";
      $scope.messageTypeSub="private";

      privateChat.origen = origen;
      $scope.conversation=privateChat;
      console.log(JSON.stringify($scope.conversation));

      console.log("Reload Messages");

      $scope.getComment(privateChat).then(function(data){
        console.log(JSON.stringify(data));
        if($scope.conversation.lastID == null){
          $scope.conversation.comments=data.detail;
          var tmpLast = $scope.conversation.comments[0];

        }
        else{
          $scope.conversation.comments.unshift(data.detail);

        }
        $scope.conversation.lastID = data.detail[0].id;

        console.log("LAST ID: " + $scope.conversation.lastID);

      });

    };*/


    $scope.setCurrentPrivate = function (privateChat, origen) {

        $scope.messageType = "conversation";
        $scope.messageTypeSub = "private";

        privateChat.origen = origen;
        $scope.conversation = privateChat;
        // console.log(JSON.stringify($scope.conversation));


        if ($scope.conversation.tmpComment == null) {
            $scope.conversation.tmpComment = {
                id: "",
                activity_id: "",
                autor: "",
                comment: "",
                date: "",
                hour: "",
                editado: false,
                id_respuesta: null,
                respuesta_autor: null,
                respuesta_comment: null,
                status: "pendiente"
            }
        }

        if ($scope.conversation.lastID == null) {
            console.log("Reload Messages");

            $scope.getComment(privateChat).then(function (data) {
                console.log(JSON.stringify(data));
                $scope.conversation.comments = data.detail;
                $scope.goBottom();

                $scope.conversation.lastID = $scope.conversation.comments[0].id;

                console.log("LAST ID: " + $scope.conversation.lastID);

            });
        }

    };
    $scope.getPrivateChat = function () {


        $http.get($scope.server + "/php/comment/getPrivateConversation.php?user=" + $scope.sesion.usuario + "&origen=" + $scope.sesion.origen)
            .then(function (data) {
                //console.log($scope.server+"/php/comment/getPrivateConversation.php?user="+$scope.sesion.puesto+"&origen="+$scope.sesion.origen);
                $scope.privates = data.data.detail;
                //  console.log(JSON.stringify($scope.privates));
                $scope.chatNotifications.private = data.data.notificaciones;
                //console.log(JSON.stringify(data.data));

                if ($scope.chatNotifications != null && $scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private > 0) {
                    $scope.GBoard = "(" + ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private) + ") " + "GBoard";
                    document.title = "" + $scope.GBoard;
                } else {
                    $scope.GBoard = "GBoard";
                    document.title = "" + $scope.GBoard;
                }

            });

    };



    $scope.newPrivateChat = function (nombre) {

        $scope.newPrivate = {
            titulo: "",
            descripcion: "",
            topico: "",
            estatus: "",
            avance: "",
            prioridad: "",
            prioridad_num: "",
            fecha_inicio: $scope.dates.currentDate,
            fecha_fin: "",
            fecha_real: "",
            metrica: "",
            next_step: "",
            responsable_1: "" + $scope.user.nombre,
            responsable_2: "" + nombre,
            encargado_ahora: "",
            padre: "",
            padre_titulo: "",
            num_hijos: 0,
            eje: "grupo",
            cuenta: $scope.user.origen,
            hour: "",
            time: "",
            link: "",
            estimacion: "",
            timing: "TBD"
        }

        var defered = $q.defer();
        var promise = defered.promise;

        $http({
                method: 'POST',
                url: 'php/pap/insert_sub.php',
                data: $scope.newPrivate
            }).success(function (data) {

                defered.resolve(data);
            })
            .error(function (err) {
                console.log("failed " + JSON.stringify(response));
                defered.reject(err)
            });

        return promise;

    };


    $scope.addMessage = function (comentario) {
        //alert($scope.conversation.origen);

        var data = {
            destinatario: $scope.conversation.subeje.id,
            remitente: $scope.sesion.usuario,
            mensaje: comentario.comment,
            fecha: comentario.date,
            hora: comentario.hour,
            id_respuesta: comentario.id_respuesta
        };

        $http.post($scope.server + "/php/comment/addMessage.php", data)
            .then(function (data) {
                console.log(JSON.stringify(data.data));
                if (data.data.response == "OK") {
                    // $scope.getMessage();

                    comentario.id = data.data.newMessage;


                                        $timeout(function(){
                        comentario.status = "enviado";

                    }, 1000);

                    // console.log("ADD MESSAGE");

                    comentario.hour = comentario.tmpH;

                    $scope.conversation.lastComment = comentario;

                    setTimeout(function () {
                        var objDiv = document.getElementById("contentMessageBox");
                        if (objDiv) {
                            objDiv.scrollTop = objDiv.scrollHeight;
                        }
                    }, 300);
                    // console.log(JSON.stringify($scope.conversation));

                    var targets = [];
                    for (var i = 0; i < $scope.conversation.miembros.length; i++) {
                        targets.push($scope.conversation.miembros[i].wikiname);
                    }

                    // console.log(JSON.stringify(targets));

                    var group = angular.copy($scope.conversation.subeje);
                    group.comments = [];
                    var data = {
                        subeje: $scope.conversation.subeje.id,
                        target: comentario.id,
                        conversation: {
                            subeje: group,
                            origen: $scope.conversation.origen,
                            miembros: $scope.conversation.miembros
                        },
                        comment: comentario
                    };

                    // console.log(JSON.stringify(data));
                    $scope.sendMessage("newMessage", targets, data, false);

     
                    // $scope.conversation.subeje.target=data.newMessage;
                    // $scope.sendMessage("newMessage",$scope.conversation.miembros,$scope.conversation.subeje);
                }

            });
    }

    $scope.getMessage = function (group) {
        var url = $scope.server + "/php/comment/getMessage.php?destinatario=" + group.subeje.id + "&user=" + $scope.sesion.usuario;
        if (group.lastID != null) {
            url = $scope.server + "/php/comment/getMessage.php?destinatario=" + group.subeje.id + "&user=" + $scope.sesion.usuario + "&last=" + group.lastID;

        } else {
            var url = $scope.server + "/php/comment/getMessage.php?destinatario=" + group.subeje.id + "&user=" + $scope.sesion.usuario;

        }

        var deferred = $q.defer();
        $http.get(url).then(function (data) {
            //console.log(JSON.stringify(data));
            deferred.resolve(data.data);
        });
        return deferred.promise;
    }





    /*===================== Notificaciones =================================*/


    $scope.editNotification = function (origen, conversation, tipo) {

        // tipo de notificación newSpec, newComment, newMessage
        var id = "";
        if (origen == "bubble") {
            if (conversation.origen == "group") {
                tipo = "newMessage";
            } else {
                tipo = "newComment";
            }
            id = conversation.subeje.id;
        } else {
            id = conversation.id;
        }

        // if($scope.info[tipo]==undefined){
        //
        //   $scope.info[tipo]=1;
        //
        // }
        //if($scope.info[tipo]>0){




        $http.get($scope.server + "/php/notifications/editNotification.php?id=" + id + "&user=" + $scope.sesion.usuario + "&tipo=" + tipo)
            .then(function (data) {
                console.log(JSON.stringify(data.data));
                if (data.data.status == "OK") {


                    if (origen == "bubble") {
                        switch (conversation.origen) {
                            case "private":
                                $scope.chatNotifications.private -= conversation.subeje.newComment;
                                break;
                            case "group":
                                $scope.chatNotifications.group -= conversation.subeje.newMessage;
                                break;
                            case "forum":
                                $scope.chatNotifications.forum -= conversation.subeje.newComment;
                                break;
                            default:
                        }

                        conversation.subeje.newComment = 0;
                        conversation.subeje.newMessage = 0;

                        for (var i = 0; i < conversation.comments.length; i++) {
                            conversation.comments[i].notificaciones = 0;
                        }

                        console.log("UPDATE NOTIFICATION");

                        console.log(JSON.stringify(["updateNotification", $scope.sesion.usuario, {
                            "id": conversation.subeje.id,
                            "tipo": tipo,
                            "sub": conversation.origen
                        }]));
                        $scope.sendMessage("updateNotification", [$scope.sesion.usuario], {
                            "id": conversation.subeje.id,
                            "tipo": tipo,
                            "sub": conversation.origen
                        });
                    } else {
                        switch (tipo) {
                            case "newComment":
                                conversation.newComment = 0;

                                for (var i = 0; i < conversation.comments.length; i++) {
                                    conversation.comments[i].notificaciones = 0;
                                }
                                break;


                            case "newSpec":
                                conversation.newSpec = 0;
                                for (var i = 0; i < conversation.specs.length; i++) {
                                    conversation.specs[i].notificaciones = 0;
                                }
                            default:

                        }
                    }


                    //$scope.info[tipo]=0;
                    //console.log("A:"+$scope.info.newActivity+" C:"+$scope.info.newComment+" S:"+$scope.info.newSpec);
                    //$scope.updateAgenda();

                    // if($scope.messageType=="group"){
                    //   $scope.getMessage();
                    //   $scope.currentGroup.newMessage=0;
                    //   $scope.chatNotifications.group=0;
                    // }
                    // else if($scope.messageType=="conversation"){
                    //   $scope.chatNotifications[$scope.messageTypeSub]=0;
                    //   console.log($scope.messageTypeSub+" - "+$scope.chatNotifications[$scope.messageTypeSub]);
                    // }

                    // if(tipo=="newComment"){
                    //   $scope.getComment();
                    // }
                    // else if(tipo=="newSpec"){
                    //   $scope.getSpec();
                    // }

                    if ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private > 0) {
                        $scope.GBoard = "(" + ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private) + ") " + "GBoard";
                        document.title = "" + $scope.GBoard;
                    } else {
                        $scope.GBoard = "GBoard";
                        document.title = "" + $scope.GBoard;
                    }
                }

            });

    };

    $scope.removeNotification = function (tipo, target) {
        $http.get("php/notifications/removeNotification.php?tipo=" + tipo + "&target=" + target).success(function (data) {
            if (data.response == "OK") {
                $scope.info.target = 0;

                $scope.sendMessage("updateNotification", $scope.allUsers, $scope.info);
            }
        });
    }


    /*=======================================      GROUPS       ===============================================*/
    $scope.misGrupos = [];
    $scope.groupMembers = [];
    $scope.groupName = "";

    $scope.getMember = function (id) {
        //$scope.groupName = nombre;
        var deferred = $q.defer();
        $scope.selectedGroup = id;
        $http.get($scope.server + "/php/group/getMembers.php?grupo=" + id).then(function (data) {
            $scope.groupMembers = data.detail;
            deferred.resolve(data.detail);
        });
        return deferred.promise;
    }

    $scope.getMyGroups = function () {
        $http.get($scope.server + "/php/group/myNewGroups.php?user=" + $scope.sesion.usuario + "&cuenta=" + $scope.sesion.origen).then(function (data) {
            $scope.misGrupos = data.data.detail;
            $scope.chatNotifications.group = data.data.notificaciones;

            if ($scope.chatNotifications != null && $scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private > 0) {
                $scope.GBoard = "(" + ($scope.chatNotifications.group + $scope.chatNotifications.forum + $scope.chatNotifications.private) + ") " + "GBoard";
                document.title = "" + $scope.GBoard;
            } else {
                $scope.GBoard = "GBoard";
                document.title = "" + $scope.GBoard;
            }
            //console.log(JSON.stringify(data.data.detail));
            if ($scope.misGrupos.length > 0) {
                $scope.getMember($scope.misGrupos[0].grupo);
                $scope.groupName = $scope.misGrupos[0].grupoN;
            }
        });
    }

    $scope.leaveGroup = function (id) {
        var url = $scope.server + "/php/group/removeMember.php";
        var data = {
            "id": id
        };
        $http({
            method: 'POST',
            url: url,
            data: data
        }).then(function successCallback(response) {
            // this callback will be called asynchronously
            // when the response is available

            console.log(JSON.stringify(response.data.status));
            if (response.data.status == "OK") {
                //$scope.getMember($scope.selectedGroup);

                //  console.log(JSON.stringify($scope.selectedGroup));
                for (var i = 0; i < $scope.conversation.miembros.length; i++) {
                    if ($scope.conversation.miembros[i].id == id) {
                        $scope.conversation.miembros.splice(i, 1);
                    }
                }
                //$scope.sendMessage("leaveGroup",$scope.conversation.miembros,$scope.conversation.subeje);
            } else {
                console.log("error");
            }


        }, function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            console.log(JSON.stringify(response));

        });
    }


    $scope.removeGroup = function (id) {

        var data = {
            id: id
        };
        ons.notification.confirm({
            message: '¿Borrar este grupo?',
            modifier: "flat",
            callback: function (idx) {
                switch (idx) {
                    case 0:
                        break;
                    case 1:
                        $http.post($scope.server + "/php/group/removeGroup.php", data).then(function (data) {
                            if (data.data.status == "OK") {
                                console.log("removed");
                                $scope.removeGroupFromList(id);
                                $scope.hideEditGroupDialog();
                                $scope.hideMessageBox();
                                $scope.removeBubble();
                            }
                        })
                        break;

                }

            }

        });
    };


    $scope.removeGroupFromList = function (id) {
        for (var i = 0; i < $scope.misGrupos.length; i++) {
            if ($scope.misGrupos[i].subeje.id == id) {
                $scope.misGrupos.splice(i, 1);
                break;
            }
        }
    };



    $scope.tryResp = function (beacon) {
        var num = parseInt(beacon);
        var resp = {
            n: num,
            name: ""
        };
        if (num > 0) {
            for (var i = 0; i < $scope.misGrupos.length; i++) {
                if ($scope.misGrupos[i].grupo == num) {
                    resp.name = $scope.misGrupos[i].grupoN;
                }
            }
        } else {
            resp.n = 0;
        }
        return resp;
    };

    $scope.showAddGroup = function () {
        $scope.newGroupMessage = "";
        ons.createDialog("addGroup.html", {
            parentScope: $scope
        }).then(function (dialog) {
            $scope.addGroupDialog = dialog;
            $scope.addGroupDialog.show();
        });

    }

    $scope.hideAddGroup = function () {
        $scope.addGroupDialog.hide();
    }

    $scope.tagMembers = [];
    $scope.newGroup = {
        name: ""
    }

    $scope.tmpGroup = {
        nombre: ""
    };

    $scope.showEditGroupDialog = function (ev) {

        //if ($scope.conversation.creador == $scope.sesion.usuario) {
        $scope.tmpGroup.nombre = $scope.conversation.subeje.titulo;
        ons.createDialog("editGroup.html", {
            parentScope: $scope
        }).then(function (d) {
            $scope.editGroupDialog = d;
            $scope.editGroupDialog.show(ev.srcElement);
        });
        //}
    }

    $scope.hideEditGroupDialog = function () {
        $scope.editGroupDialog.hide();
        $scope.tagMembers = [];

    }


    $scope.editGroupName = function () {
        var data = {
            campo: "nombre",
            valor: $scope.tmpGroup.nombre,
            id: $scope.conversation.subeje.id
        };

        $http.post($scope.server + "/php/group/editGroup.php", data).then(function (data) {
            if (data.data.status == "OK") {
                $scope.conversation.subeje.titulo = $scope.tmpGroup.nombre;
                $scope.activeBubble.nombre = $scope.conversation.subeje.titulo;
            }

            console.log(JSON.stringify(data.data));
        });
    }


    $scope.addMembers = function () {
        if ($scope.tagMembers.length > 0) {
            var url = $scope.server + "/php/group/addMember.php";
            var newMembers = [];
            for (var i = 0; i < $scope.tagMembers.length; i++) {
                newMembers.push($scope.tagMembers[i].wikiname);
            }
            var data = {
                "name": $scope.conversation.subeje.id,
                "members": newMembers
            };

            console.log(JSON.stringify(data));
            $http({
                method: 'POST',
                url: url,
                data: data
            }).then(function (response) {
                // this callback will be called asynchronously
                // when the response is available
                console.log(JSON.stringify(response.data));
                if (response.data.status == "OK") {
                    // $scope.hideAddMembers();
                    // $scope.getMember($scope.selectedGroup);
                    // $scope.sendMessage("joinGroup",$scope.groupWikinames(),$scope.conversation.subeje);
                    console.log(JSON.stringify(response.data));

                    for (var i = 0; i < response.data.members.length; i++) {
                        console.log(JSON.stringify(response.data.members[i]));
                        $scope.conversation.miembros.push(response.data.members[i]);
                    }
                    $scope.tagMembers = [];
                    //$scope.misGrupos.push({wikiname: $scope.user2,grupoN:response.data.detail.group.name, grupo:response.data.detail.group.id});
                } else {
                    console.log("error");
                }

            });
        } else {

        }
    }


    $scope.addGroup = function () {
        if ($scope.newGroup.name != "" && $scope.tagMembers.length > 0) {
            var url = $scope.server + "/php/group/addGroup.php";
            // console.log(url);
            $scope.tagMembers.push({
                wikiname: $scope.sesion.usuario,
                email: $scope.sesion.email,
                picture: $scope.usuarios[$scope.sesion.usuario].picture
            });
            // console.log(JSON.stringify($scope.tagMembers));
            var data = {
                "name": $scope.newGroup.name,
                "origen": $scope.sesion.origen,
                "members": $scope.tagMembers,
                'creador': $scope.sesion.usuario
            };
            $scope.newGroupMessage = "";
            console.log(JSON.stringify(data));

            $http.post(url, {
                name: $scope.newGroup.name,
                origen: $scope.sesion.origen,
                members: $scope.tagMembers,
                creador: $scope.sesion.usuario
            }).then(function (response) {
                console.log(JSON.stringify(response.data));
                if (response.data.status == "OK") {
                    $scope.newGroupMessage = "Grupo creado";
                    $scope.newGroupClass = "groupSuccess";

                    //$scope.getMyInfo();

                    $scope.conversation.target = 0;
                    $scope.misGrupos.push({
                        subeje: {
                            id: response.data.detail.group.id,
                            titulo: response.data.detail.group.name,
                            newMessage: 0
                        },
                        comments: [],
                        miembros: $scope.tagMembers,
                        creador: $scope.sesion.usuario
                    });

                    $scope.$apply();

                    // $scope.sendMessage("addGroup",$scope.groupWikinames(),$scope.conversation);
                    $scope.newGroup.name = "";
                    $scope.tagMembers = [];
                } else {
                    $scope.newGroupMessage = "Hubo un problema al crear el grupo ";
                    $scope.newGroupClass = "groupError";
                }


            });
        } else {
            $scope.newGroupMessage = "One or more fields are empty";
            $scope.newGroupClass = "groupError";
        }
    }

    $scope.isInGroup = function (wikiname, edit) {
        isInGroup = false;
        //alert(edit);
        if (!edit) {

            return false;
        } else {
            for (var i = 0; i < $scope.conversation.miembros.length; i++) {
                if ($scope.conversation.miembros[i].wikiname == wikiname) {
                    isInGroup = true;
                    break;
                }
            }
            return isInGroup;
        }

    }

    $scope.loadWikinames = function ($query, edit) {
        var listUsers = [];
        for (var key in $scope.members) {
            if ($scope.members[key].wikiname != "Bot" + $scope.sesion.origen && $scope.members[key].wikiname != $scope.sesion.usuario && !$scope.isInGroup($scope.members[key].wikiname, edit)) {
                listUsers.push({
                    wikiname: $scope.members[key].wikiname,
                    puesto: $scope.members[key].puesto,
                    puestoID: $scope.members[key].puesto,
                    picture: $scope.members[key].picture
                });
            }
        }


        //console.log(JSON.stringify(listUsers));
        return listUsers.filter(function (member) {
            return member.wikiname.toLowerCase().indexOf($query.toLowerCase()) != -1;
        });
    };


    $scope.groupWikinames = function () {
        var groupWikinames = [];
        for (var i = 0; i < $scope.tagMembers.length; i++) {
            groupWikinames.push($scope.tagMembers[i].wikiname)
        }
        return groupWikinames;
    }





    /* =============== Nuevos Mensajes =============== */

    $scope.searchConversation = '';
    $scope.selectedCType = 'time';
    $scope.newConversationDialog = false;
    $scope.searchPlaceholder = "Buscar una conversación";
    $scope.oldCType = "";

    $scope.setCType = function (type) {


        $scope.oldCType = $scope.selectedCType;
        $scope.selectedCType = type;


        switch (type) {
            case "private":
                $scope.searchPlaceholder = "Buscar una conversación";
                break;
            case "group":
                $scope.searchPlaceholder = "Buscar un grupo";
                break;
            default:
                $scope.searchPlaceholder = "Buscar una conversación";

        }
    }



    $scope.marginMessage = "0px";
    $scope.indexBubble = 0;
    $scope.bubbles = [];
    $scope.lastPage = '';


    $scope.showFullChat = function () {
        $scope.lastPage = $scope.page;
        $scope.navegar('chat');
    }

    $scope.hideFullChat = function () {
        $scope.navegar($scope.lastPage);
        $scope.setMessageBox('0');
        $scope.showMessageBox();
    }

    $scope.showNewConversation = function () {
        $scope.newConversationDialog = true;
        $scope.searchPlaceholder = "Buscar un contacto";

    }

    $scope.hideNewConversation = function () {
        $scope.newConversationDialog = false;
        $scope.searchPlaceholder = "Buscar una conversación";

    }


    $scope.setMessageBox = function (index) {

        console.log($scope.indexBubble + " - " + index + "\n");
        if ($scope.indexBubble == index) {
            $scope.sameBubble = true;
        } else {
            $scope.sameBubble = false;

            $scope.marginMessage = (125 * index) + "px";
            $scope.indexBubble = index;
        }

    }

    $scope.checkPrivate = function (user) {
        console.log(user);
        console.log($scope.server + "/php/comment/checkPrivate.php?user1=" + $scope.sesion.puesto + "&user2=" + user);
        $http.get($scope.server + "/php/comment/checkPrivate.php?user1=" + $scope.sesion.puesto + "&user2=" + user).then(function (data) {
            console.log(JSON.stringify(data));
            if (data.data.message == "SI") {
                console.log($scope.server + "/php/comment/getPrivateConversation.php?user=" + $scope.sesion.puesto + "&origen=" + $scope.sesion.origen + "&id=" + data.data.detail);
                $http.get($scope.server + "/php/comment/getPrivateConversation.php?user=" + $scope.sesion.puesto + "&origen=" + $scope.sesion.origen + "&id=" + data.data.detail).then(function (data) {

                    $scope.addBubble(data.data.detail[0], 'private');
                    $scope.setCurrentPrivate(data.data.detail[0], 'private');

                });
            } else {
                console.log($scope.server + "/php/comment/addPrivate.php?user1=" + $scope.sesion.puesto + "&user2=" + user + "&origen=" + $scope.sesion.origen);
                $http.get($scope.server + "/php/comment/addPrivate.php?user1=" + $scope.sesion.puesto + "&user2=" + user + "&origen=" + $scope.sesion.origen).then(function (data) {
                    if (data.data.response == "OK") {
                        console.log($scope.server + "/php/comment/getPrivateConversation.php?user=" + $scope.sesion.puesto + "&origen=" + $scope.sesion.origen + "&id=" + data.data.detail);
                        $http.get($scope.server + "/php/comment/getPrivateConversation.php?user=" + $scope.sesion.puesto + "&origen=" + $scope.sesion.origen + "&id=" + data.data.detail).then(function (data) {
                            console.log(JSON.stringify(data.data));
                            $scope.addBubble(data.data.detail[0], 'private');
                            $scope.setCurrentPrivate(data.data.detail[0], 'private');

                        });

                    }


                });
            }
        });


    }

    //$scope.navegar('chat');
    console.log("CHAT");
    $scope.addBubble = function (conversation, origen) {

        //  console.log(JSON.stringify(conversation));
        conversation.nombre = conversation.subeje.titulo;
        console.log(origen);
        if (origen == "private" || origen == "forum") {
            console.log("Private");
            conversation.type = "private";
        } else if (origen == "group") {
            console.log("Grupo");
            conversation.type = "group";
        }
        conversation.origen = origen;
        //alert(conversation.origen);

        //  console.log(conversation.type);

        console.log(JSON.stringify(conversation));

        if ($scope.bubbles.indexOf(conversation) == -1) {
            $scope.bubbles.unshift(conversation);

            if ($scope.bubbles.length > 3) {
                $scope.bubbles.pop($scope.bubbles[$scope.bubbles.length - 1]);
            }
        }


    }

    $scope.setActiveBubble = function (bubble) {
        $scope.activeBubble = bubble;
        //console.log(JSON.stringify($scope.activeBubble));
        $scope.goBottom();
    }

    $scope.goBottom = function (delay) {


        if (delay != null) {

            var objDiv = document.getElementById("contentMessageBox");
            objDiv.scrollTop = objDiv.scrollHeight;

        } else {
            setTimeout(function () {
                var objDiv = document.getElementById("contentMessageBox");
                objDiv.scrollTop = objDiv.scrollHeight;
            }, 1000);
        }

        angular.element(document.querySelector('.contentMessageBox')).bind('scroll', function () {

            var objDiv = document.getElementById("contentMessageBox");
            //console.log( objDiv.scrollTop + " - " + objDiv.scrollHeight);

            if (objDiv.scrollTop == 0 && !$scope.conversation.busy) {

                $scope.lastHeight = objDiv.scrollHeight;

                $scope.conversation.busy = true;
                console.log("TOP");

                console.log($scope.conversation.subeje.id);

                if ($scope.conversation.type == "group") {
                    $scope.conversation.function = $scope.getMessage;

                } else {
                    $scope.conversation.function = $scope.getComment;

                }

                console.log("TIPO: " + $scope.conversation.type);




                $scope.conversation.function($scope.conversation).then(function (data) {

                    // console.log(JSON.stringify(data));



                    console.log($scope.conversation.lastID);


                    if ($scope.conversation.lastID == null) {
                        $scope.conversation.comments = data.detail;

                    } else {
                        console.log("UNSHIFT");
                        if (data.status == "OK" || data.response == "OK") {

                            if (data.detail.length == 0) {
                                $scope.conversation.busy = true;
                                $scope.conversation.end = true;

                            } else {
                                // objDiv.scrollTop = 100;
                                console.log($scope.conversation.lastID);
                                var elmnt = document.getElementById($scope.conversation.lastID);


                                // objDiv.scrollTop = 10;
                                for (var i = 0; i < data.detail.length; i++) {
                                    $scope.conversation.comments.unshift(data.detail[data.detail.length - (i + 1)]);

                                    $scope.newHeight = objDiv.scrollHeight;
                                    objDiv.scrollTop = $scope.newHeight - $scope.lastHeight + 10;

                                }

                                console.log(elmnt);
                                // elmnt.scrollIntoView();


                                // window.location.href = "#"+$scope.conversation.lastID;

                                $scope.conversation.lastID = data.detail[0].id;
                                $scope.conversation.busy = false;
                            }

                            if (data.detail.length < 30) {


                                $scope.conversation.end = true;
                                $scope.conversation.busy = true;


                            }



                        } else {
                            console.log("errorCallback");
                            console.log(JSON.stringify(data));
                        }
                        // console.log(JSON.stringify($scope.conversation.comments));
                    }
                });
            }

            if (objDiv.scrollTop < (objDiv.scrollHeight - objDiv.offsetHeight - 100)) {


                document.getElementById("chatBottom").style.opacity = 0.6;
                // console.log("NEL");

            } else {
                document.getElementById("chatBottom").style.opacity = 0;

            }


        })

        // $scope.$apply();
    }




    $scope.hideMessageBox = function () {
        $scope.showBox = false;
    }

    // $scope.showMessageBox = function(){
    //
    //   if ($scope.sameBubble && $scope.showBox == true) {
    //     $scope.showBox = false;
    //   }
    //   else{
    //     $scope.showBox = true;
    //   }
    //
    //   var objDiv = document.getElementById("contentMessageBox");
    //   if (objDiv) {
    //     objDiv.scrollTop = objDiv.scrollHeight;
    //
    //   }
    //
    // }

    $scope.showBox = false;

    $scope.showMessageBox = function (toggle) {

        console.log("TOGGLE: " + toggle);

        if (toggle == null) {
            console.log("TRUE");
            if ($scope.sameBubble && $scope.showBox == true) {
                $scope.showBox = false;
            } else {
                $scope.showBox = true;
            }
        } else {
            console.log("FALSE");

            if ($scope.showBox == false) {
                $scope.showBox = true;

            } else if ($scope.oldCType == $scope.selectedCType) {
                $scope.showBox = false;

            }


            console.log($scope.showBox);

        }



        var objDiv = document.getElementById("contentMessageBox");
        if (objDiv) {
            objDiv.scrollTop = objDiv.scrollHeight;

        }

    }

    $scope.removeBubble = function () {
        for (var i = 0; i < $scope.bubbles.length; i++) {
            if (i == ($scope.indexBubble - 1)) {
                $scope.bubbles.splice(i, 1);
            }
        }
    }

    $scope.showFullMessage = function (id) {

        var x = document.getElementById(id);
        if (x.className.indexOf("w3-show") == -1) {
            x.className += " w3-show";
        } else {
            x.className = x.className.replace(" w3-show", "");
        }

    }

    $scope.toggleReply = function (conversation) {
        console.log(conversation.showReply + " - " + !conversation.showReply);
        conversation.showReply = !conversation.showReply;
    }




    /*=================== Left Bar ============================*/


    $scope.leftBar = "home";

    $scope.setLeftBar = function (select) {
        $scope.leftBar = select;
    }



    /*================= Activity Log ==================*/


    var date = new Date();

    $scope.searchLog = {
        fechaInicio: date,
        fechaFin: date
    }



    $scope.getLog = function () {

        // if($scope.compareDates($scope.logDateStart,$scope.logDateEnd)){
        //   var tmpDate = $scope.logDateEnd;
        //   $scope.logDateEnd = $scope.logDateStart;
        //   $scope.logDateStart = tmpDate;
        // }

        var fechaInicio = $scope.searchLog.fechaInicio.getFullYear() + "-" + ($scope.searchLog.fechaInicio.getMonth() + 1) + "-" + $scope.searchLog.fechaInicio.getDate();
        var fechaFin = $scope.searchLog.fechaFin.getFullYear() + "-" + ($scope.searchLog.fechaFin.getMonth() + 1) + "-" + $scope.searchLog.fechaFin.getDate();


        console.log($scope.server + "/php/notifications/getLog.php?fechaInicio=" + fechaInicio + "&fechaFin=" + fechaFin + "&origen=" + $scope.sesion.origen);
        $http.get($scope.server + "/php/notifications/getLog.php?fechaInicio=" + fechaInicio + "&fechaFin=" + fechaFin + "&origen=" + $scope.sesion.origen)
            .then(function (data) {
                //console.log(JSON.stringify(data.data));
                $scope.activities = data.data;
                $scope.noDays = Object.keys($scope.activities).length;
            });


    }

    $scope.priority = [
        "Urgent",
        "Critical",
        "High",
        "Medium",
        "Low"
    ];

    $scope.priorityNumber = {
        "Urgent": 1,
        "Critical": 2,
        "High": 3,
        "Medium": 4,
        "Low": 5
    };

    $scope.fields = {
        "titulo": "title",
        "descripcion": "description",
        "padre": "parent objective",
        "next_step": "next steps",
        "link": "link",
        "responsable_1": "captain",
        "responsable_2": "runner",
        "prioridad": "priority",
        "estatus": "status",
        "timing": "timing",
        "duration": "duration",
        "type": "type",
        "fecha_inicio": "date of creation",
        "fecha_fin": "estimated date",
        "autoriza": "Persona que autoriza",
        "presupuesto": "presupuesto",
        "total": "total",
        "autorizacion": "autorizacion",
        "condiciones": "condiciones de compra",
        "proveedor": "proveedor",
        "entrega_estimada": "entrega estimada",
        "entrega_real": "entrega",
        "entrega_solicitante": "entrega solicitante"
    }


    $scope.campos = {
        "title": "título",
        "description": "descripción",
        "parent objective": "padre",
        "next steps": "siguientes pasos",
        "link": "link",
        "captain": "captain",
        "runner": "runner",
        "priority": "prioridad",
        "status": "estatus",
        "timing": "timing",
        "duration": "duración",
        "type": "tipo",
        "date of creation": "fecha de creación",
        "estimated date": "fecha estimada",
        "Persona que autoriza": "Persona que autoriza",
        "presupuesto": "presupuesto",
        "total": "total",
        "autorizacion": "autorizacion",
        "condiciones de compra": "condiciones de compra",
        "proveedor": "proveedor",
        "entrega estimada": "entrega estimada",
        "entrega": "entrega",
        "entrega solicitante": "entrega solicitante"
    }




    $scope.timing = [{
        text: "Today",
        value: "TD"
    }, {
        text: "This Week",
        value: "TW"
    }, {
        text: "Next Week",
        value: "NW"
    }, {
        text: "This Month",
        value: "TM"
    }, {
        text: "This Year",
        value: "TY"
    }, {
        text: "Finished",
        value: "OK"
    }, {
        text: "To Be Determinated",
        value: "TBD"
    }];

    $scope.statusOptions = {
        "1-ToStart": {
            value: "1-ToStart",
            text: "ToStart"
        },
        "2-Pending": {

            value: "2-Pending",
            text: "Pending"

        },
        "3-WOI": {

            value: "3-WOI",
            text: "WOI"

        },
        "4-Review": {
            value: "4-Review",
            text: "Review"

        },
        "5-Testing": {

            value: "5-Testing",
            text: "Testing"

        },
        "6-Decision": {

            value: "6-Decision",
            text: "Decision"

        },
        "7-Done": {

            value: "7-Done",
            text: "Done"

        },
        "8-Stucked": {

            value: "8-Stucked",
            text: "Stucked"

        },
        "9-Archived": {

            value: "9-Archived",
            text: "Archived"

        }
    };

    $scope.etapasOptions = {
        "1-Autorizacion": {
            value: "1-Autorizacion",
            text: "Autorizacion"
        },
        "2-Cotizacion": {

            value: "2-Cotizacion",
            text: "Cotizacion"

        },
        "3-Presupuesto": {

            value: "3-Presupuesto",
            text: "Presupuesto"

        },
        "4-Facturacion": {
            value: "4-Facturacion",
            text: "Facturación"

        },
        "5-Pago": {

            value: "5-Pago",
            text: "Pago"

        },
        "6-Entrega": {

            value: "6-Entrega",
            text: "Entrega Almc."

        },
        "7-Logistica": {

            value: "7-Logistica",
            text: "Logistica"

        },
        "8-Almacen": {

            value: "8-Almacen",
            text: "Almacen"

        },
        "9-Entrega": {

            value: "9-Entrega",
            text: "Entrega Solic."

        }
    };

    $scope.noticias = [];
    $scope.getNews = function ($event) {

        $scope.noticiasPop.show($event.srcElement);
        var req = {
            //url: $dom.getServer() + "/php/news/getNews.php",
            url: "https://genniux.net" + "/php/news/getNews.php",
            method: "POST",
            data: {
                cuenta: $dom.getUser().origen,
                user: $dom.getUser().nombre
            },
            headers: {
                "Content-Type": undefined
            },
        }
        $http(req).then(function (data) {
            console.log(data);
            if (data.data.status == "OK") {
                $scope.noticias = data.data.detail;
            }
        });
    }


    /* APARTADO DE LAS FECHAS */
    var myDate = new Date();
    $scope.calendarOptionsFi = {
        defaultDate: myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate(),
        minDate: new Date([myDate.getFullYear(), myDate.getMonth() + 1, myDate.getDate()]),
        maxDate: new Date([2020, 12, 31]),
        dayNamesLength: 1, // How to display weekdays (1 for "M", 2 for "Mo", 3 for "Mon"; 9 will show full day names; default is 1)
        multiEventDates: true, // Set the calendar to render multiple events in the same day or only one event, default is false
        maxEventsPerDay: 1, // Set how many events should the calendar display before showing the 'More Events' message, default is 3;
        eventClick: function (ev) {
            console.log(ev);
            console.log($scope.newValue.fecha_inicio);
            $scope.calendarOptionsFi.defaultDate = ev.year + "-" + (ev.month + 1) + "-" + ev.day;
            $scope.newValue.fecha_inicio = ev.year + "-" + ("0" + (ev.month + 1)).slice(-2) + "-" + ("0" + (ev.day)).slice(-2);
            console.log($scope.newValue.fecha_inicio);
        },
        dateClick: function (ev) {
            console.log(ev);

        }
    };
    $scope.eventsFi = [];
    $scope.calendarOptionsFf = {
        defaultDate: myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate(),
        minDate: new Date([myDate.getFullYear(), myDate.getMonth() + 1, myDate.getDate()]),
        maxDate: new Date([2020, 12, 31]),
        dayNamesLength: 1, // How to display weekdays (1 for "M", 2 for "Mo", 3 for "Mon"; 9 will show full day names; default is 1)
        multiEventDates: true, // Set the calendar to render multiple events in the same day or only one event, default is false
        maxEventsPerDay: 1, // Set how many events should the calendar display before showing the 'More Events' message, default is 3;
        eventClick: function (ev) {
            console.log(ev);
            console.log($scope.newValue.fecha_fin);
            $scope.calendarOptionsFf.defaultDate = ev.year + "-" + (ev.month + 1) + "-" + ev.day;
            $scope.newValue.fecha_fin = ev.year + "-" + ("0" + (ev.month + 1)).slice(-2) + "-" + ("0" + (ev.day)).slice(-2);
            console.log($scope.newValue.fecha_fin);
        },
        dateClick: function (ev) {
            console.log(ev);

        }
    };
    $scope.eventsFf = [];
    /* FIN DEL APARTADO DE LAS FECHAS (Alex) */


















    $scope.notificacionesBell = [];
    $scope.getnotificacionesBell = function ($event) {

        $scope.notificacionesBellPop.show($event.srcElement);
        var objN = {
            id_user: $scope.sesion.puesto
        };
        $dom.getNotificacionesContadores(objN).then(function (res) {
            console.log(res);
            $scope.totalNotiPunch = res.data.detail;
            $dom.getNotificaciones(objN).then(function (res2) {
                console.log(res2);
                $scope.notificacionesBell = res2.data.detail;
            });
        });
    }
    $scope.getnotificacionesBell2 = function ($event) {
        $scope.notificacionesBellPop.show($event.srcElement);
    }

    $scope.MostrarNotiUnica = function (obj, sobreeje) {
        var objEnviar = {
            id: obj.id,
            visto: 1
        };
        console.warn(obj);
        var rutaAbrir = "";
        if (obj.app.indexOf("punchlist") != (-1)) {
            $scope.tipoVista = "Ticket";
        };
        if (obj.app.indexOf("objetivo") != (-1)) {
            $scope.tipoVista = "Objetivo";
        };
        if (obj.app.indexOf("all") != (-1)) {
            $scope.tipoVista = "Noticia";
        };
        if (obj.app.indexOf("operation") != (-1)) {
            $scope.tipoVista = "Ruta";
            //rutaAbrir="https://genniux.net/app/board/#!?tipo="+$scope.tipoVista+"&id="+obj.id_actividad_entregable;
            $location.search({
                tipo: "" + $scope.tipoVista,
                id: obj.id_actividad_entregable
            });
        } else {
            //rutaAbrir="https://genniux.net/app/board/#!?tipo="+$scope.tipoVista+"&id="+obj.id_actividad;
            $location.search({
                tipo: "" + $scope.tipoVista,
                id: obj.id_actividad
            });
        }
        var objShowNoti = {
            tipo: "" + $location.search().tipo,
            id: "" + $location.search().id
        };
        console.warn(objShowNoti);


        if (sobreeje === undefined) {
            $scope.hideNotificationApp("Arranque");
        };
        $scope.showNotificationApp(objShowNoti);

        // window.open(rutaAbrir);
        if (obj.visto === 0 || obj.visto === '0') {
            $dom.updateNotificacionEstatus(objEnviar).then(function (res) {
                console.log(res);
                $scope.totalNotiPunch = $scope.totalNotiPunch - 1;
                obj.visto = 1;

            });
        }
    }


    $scope.showNotificationApp = function (obj) {
        if ($scope.popVistaNotiApp !== undefined) {
            $scope.popVistaNotiApp.hide();
        };
        console.warn(obj);
        $scope.loadModalVista.show();
        $scope.VerPermisos(obj).then(function (res) {
            $scope.loadModalVista.hide();
            console.error(res);
            if (res) {
                $scope.loadModalVista.show();

                if (obj.tipo === "Ticket") {
                    ons.createAlertDialog("notiPunsh.html", {
                        parentScope: $scope
                    }).then(function (alert) {
                        $scope.notiDialog = alert;
                        $scope.notiDialog.show();
                    });
                } else
                if (obj.tipo === "Objetivo") {
                    ons.createAlertDialog("notiPunsh.html", {
                        parentScope: $scope
                    }).then(function (alert) {
                        $scope.notiDialog = alert;
                        $scope.notiDialog.show();
                    });
                } else
                if (obj.tipo === "Noticia") {
                    ons.createAlertDialog("notiNoticias.html", {
                        parentScope: $scope
                    }).then(function (alert) {
                        $scope.notiDialog = alert;
                        $scope.notiDialog.show();
                    });
                } else
                if (obj.tipo === "Ruta") {
                    ons.createAlertDialog("notiRuta.html", {
                        parentScope: $scope
                    }).then(function (alert) {
                        $scope.notiDialog = alert;
                        $scope.notiDialog.show();
                    });
                }
            } else {
                ons.notification.alert('Actividad invalida ', {
                    title: "Alerta",
                    buttonLabels: "Confirmar"
                });
                $scope.hideNotificationApp();
            }
        });



    }







    $scope.VerPermisos = function (obj) {
        var deferred = $q.defer();
        obj.origen = $scope.sesion.origen;
        $scope.tituloRutaObjetivo = "";
        $scope.valPer = false;
        $dom.getpermisos(obj).then(function (res) {
            console.warn(res);
            if (obj.tipo === "Objetivo") {
                if (res.data.permiso) {
                    $scope.valPer = true;
                    $scope.tituloRutaObjetivo = res.data.tituloRutaObjetivo;
                };
            } else
            if (res.data.row_cnt > 0) {
                console.warn(res.data.arrUsersPrincipales[0]);
                $scope.usersPrincipales = res.data.arrUsersPrincipales[0];
                $scope.usersNoti = res.data.arrUsersNoti;
                if ($scope.usersPrincipales.eje === "Noticia" && ($scope.usersPrincipales.type === "Alerta" || $scope.usersPrincipales.type === "Comunicado")) {
                    $scope.valPer = true;
                };

                if (res.data.eje === "Ruta") {
                    if ($scope.sesion.puesto === $scope.usersPrincipales.encargado_ahora || $scope.sesion.puesto === $scope.usersPrincipales.responsable_1 || $scope.sesion.puesto === $scope.usersPrincipales.responsable_2 || $scope.sesion.puesto === $scope.usersPrincipales.actividad_resp1 || $scope.sesion.puesto === $scope.usersPrincipales.actividad_resp2 || $scope.sesion.puesto === $scope.usersPrincipales.actividad_resp3) {
                        $scope.valPer = true;
                    }

                };

                if ($scope.sesion.puesto === $scope.usersPrincipales.encargado_ahora || $scope.sesion.puesto === $scope.usersPrincipales.responsable_1 || $scope.sesion.puesto === $scope.usersPrincipales.responsable_2) {
                    $scope.valPer = true;
                    // Si tiene permiso como encargado_ahora, responsable_1 o/y responsable_2
                } else if (!$scope.valPer) {
                    console.warn($scope.usersNoti);
                    for (var i = 0; i < $scope.usersNoti.length; i++) {
                        if ($scope.sesion.puesto === $scope.usersNoti[i].id_user) {
                            $scope.valPer = true;
                            break;
                        }
                    }
                    if ($scope.valPer) {
                        //Permisos como usuario agregado en comentario
                    };
                }

            } else { //No existe ticket
            }
            deferred.resolve($scope.valPer);
        });
        return deferred.promise;
    }







    $scope.hideNotificationApp = function (tipo) {
        if (tipo === undefined) {
            $location.search({});

        };
        if ($scope.notiDialog !== undefined) {
            $scope.notiDialog.hide();

        };
        if ($scope.popVistaNotiApp2 !== undefined) {
            $scope.popVistaNotiApp2.hide();

        };
    }

    $scope.buscarTituloNoti = "";
    $scope.buscarTipoNoti = "";

    $scope.FiltrosNoti = false;

    $scope.MostrarFiltrosNoti = function (FiltrosNoti) {
        if (FiltrosNoti) {
            $scope.FiltrosNoti = false;

        } else {
            $scope.FiltrosNoti = true;

        }

    }


    $scope.abrirNuevaVentana = function (ruta) {
        $window.open("" + ruta);
    }



});

app.controller('Notificaciones', function ($scope) {
    ons.ready(function () {

    });

});

app.controller('VistaNotiApp', function ($scope, $location, $window, $q, $dom, $http) {
    $scope.Preview = "Ticket";
    $scope.mobile = false;

    $scope.fw = "0";
    var w = $window.innerWidth;
    if (w > 0 && w < 550) $scope.fw = "100%";
    if (w > 549 && w < 850) $scope.fw = "50%";
    if (w > 849 && w < 1480) $scope.fw = "33%";
    if (w > 1479) $scope.fw = "20%";

    angular.element($window).on("resize", function () {
        console.log($window.innerWidth);
        var w = $window.innerWidth;
        if ($scope.tipoVista == 'Noticia') $scope.fw = "100%";
        if (w > 0 && w < 550) $scope.fw = "100%";
        if ((w > 549 && w < 850)) $scope.fw = "50%";
        if (w > 849 && w < 1480) $scope.fw = "33%";
        if (w > 1479) $scope.fw = "20%";
        if ($scope.tipoVista == 'Noticia') $scope.fw = "100%";

        $scope.$apply();
    });
    ons.ready(function () {
        if (ons.platform.isIOS() || ons.platform.isAndroid()) {
            $scope.mobile = true;
            console.log($scope.mobile);

        }
        $scope.loadModalVista.show();
        if (Cookies.get("usuario2") !== undefined) {
            $scope.sesion = JSON.parse(Cookies.get("usuario2"));
            $scope.server = $dom.getServer();
            console.log($scope.sesion);
            $scope.members = $scope.usuarios;
            $scope.sesion.puestoNombre = $scope.usuarios[$scope.sesion.usuario].puestoNombre;
            $dom.setUser($scope.sesion);
            $scope.user.status = true;
            $scope.loadModalVista.hide();
            $scope.getPrivateChat();
            $scope.getConversations();


            $scope.getMyGroups();
            $scope.getLog();
            $scope.usuario = $dom.getUser();

            $scope.tipoVista = $location.search().tipo;
            $scope.idVista = $location.search().id;
            //alert($scope.tipoVista);
            if ($scope.tipoVista === "Ticket" || $scope.tipoVista === "Objetivo") {
                $http.get($dom.getServer() + "/php/support/getTicket.php?id=" + $scope.idVista + "&cuenta=" + $dom.getUser().origen).then(function (data) {
                    $scope.loadModalVista.hide();
                    //console.log(data.data.detail);
                    if (data.data.detail.length > 0) {
                        var sel = data.data.detail[0];
                        $scope.Preview = sel.titulo;
                        var s = sel;
                        $scope.server = $dom.getServer();
                        var server = $dom.getServer();
                        var user = $dom.getUser();
                        $dom.setSelected(sel).then(function (res) {
                            $scope.ticket = res;
                            console.warn(res);
                        });
                    } else {
                        $scope.notFound = true;
                    }
                });
            } else if ($scope.tipoVista === "Noticia") {
                $http.get($dom.getServer() + "/php/notificaciones/getNewsVistaBoard.php?id=" + $scope.idVista + "&puesto=" + $scope.usuario.puesto).then(function (data) {
                    $scope.loadModalVista.hide();
                    //console.log(data.data.detail);
                    if (data.data.detail.length > 0) {
                        var sel = data.data.detail[0];
                        $scope.Preview = sel.titulo;
                        var s = sel;
                        $scope.server = $dom.getServer();
                        var server = $dom.getServer();
                        var user = $dom.getUser();
                        $dom.setSelected(sel).then(function (res) {
                            $scope.ticket = res;
                            console.warn(res);
                        });
                    } else {
                        $scope.notFound = true;
                    }
                });
            } else if ($scope.tipoVista === "Ruta") {
                $http.post($dom.getServer() + "/php/notificaciones/getMiPlanVistaBoard.php", {
                    id_entregable: $scope.idVista
                }).then(function (data) {
                    $scope.loadModalVista.hide();
                    console.warn(data);
                    $scope.ticket = data.data.detail;
                    $scope.selected.comments = $scope.ticket.comments;
                });
            }

        } else {
            $scope.loadModal.hide();
        }
    });



    $scope.removeSave = function (noticia) {

        console.log("REMOVE");

        $scope.user = $dom.getUser();

        $scope.removeFromSave(noticia.id);


        var req = {
            method: 'POST',
            url: $dom.getServer() + "/php/news/removeSave.php",
            headers: {
                'Content-Type': undefined
            },
            data: {
                id: noticia.id,
                user: $scope.user.puesto
            }
        }

        $http(req).then(function (data) {
            console.log(JSON.stringify(data.data));

            if (data.data.status == "OK") {
                noticia.userMark = false;
            }
        });

    }



    $scope.saveNew = function (noticia) {

        $scope.user = $dom.getUser();


        var req = {
            method: 'POST',
            url: $dom.getServer() + "/php/news/saveNew.php",
            headers: {
                'Content-Type': undefined
            },
            data: {
                id: noticia.id,
                user: $scope.user.puesto
            }
        }

        $http(req).then(function (data) {
            console.log(JSON.stringify(data.data));

            if (data.data.status == "OK") {
                noticia.userMark = true;
            }
        });

    }





    $scope.validateLike = function (noticia) {
        $scope.user = $dom.getUser();


        var req = {
            method: 'POST',
            url: $dom.getServer() + "/php/news/getLikes.php",
            headers: {
                'Content-Type': undefined
            },
            data: {
                id: noticia.id
            }
        }

        $http(req).then(function (data) {

            console.log(JSON.stringify(data.data));
            if (data.data.status == "OK") {
                noticia.likes = data.data.detail;

                var id = "";
                for (var i = 0; i < noticia.likes.length; i++) {
                    if (noticia.likes[i].usuario == $scope.user.usuario) {
                        id = noticia.likes[i].id;
                        break;
                    }
                }

                if (id == "") {
                    $scope.like(noticia);
                } else {
                    $scope.unlike(noticia);
                }
            }
        });

    }




    $scope.like = function (noticia) {
        $scope.user = $dom.getUser();

        var req = {
            method: 'POST',
            url: $dom.getServer() + "/php/news/like.php",
            headers: {
                'Content-Type': undefined
            },
            data: {
                user: $scope.user.puesto,
                actividad: noticia.id
            }
        }


        var audio = new Audio('audio/pop.mp3');
        audio.play();
        noticia.numLikes++;
        noticia.userLike = true;

        $http(req).then(function (data) {

            console.log(JSON.stringify(data.data));
            if (data.data.status != "OK") {
                noticia.numLikes--;
                noticia.userLike = false;
            } else {

                var tmpLike = {
                    id: data.data.detail,
                    usuario: $scope.user.usuario
                }
                noticia.likes.push(tmpLike);
            }
        });

    }

    $scope.unlike = function (noticia) {

        var id = "";

        for (var i = 0; i < noticia.likes.length; i++) {
            if (noticia.likes[i].usuario == $scope.user.usuario) {

                id = noticia.likes[i].id;
                noticia.likes.splice(i, 1);

            }
        }

        var req = {
            method: 'POST',
            url: $dom.getServer() + "/php/news/removeLike.php",
            headers: {
                'Content-Type': undefined
            },
            data: {
                id: id
            }
        }

        if (id != "") {

            $http(req).then(function (data) {

                console.log(JSON.stringify(data.data));
                if (data.data.status == "OK") {
                    noticia.numLikes--;
                    noticia.userLike = false;
                }
            });

        }


    }




    $scope.showViews = function (noticia) {

        //console.log(JSON.stringify(noticia));
        $scope.server = $dom.getServer();
        //$scope.usuarios=$dom.getUsuarios();


        var req = {
            method: 'POST',
            url: $dom.getServer() + "/php/news/getViews.php",
            headers: {
                'Content-Type': undefined
            },
            data: {
                id: noticia.id
            }
        }

        $http(req).then(function (data) {
            console.warn(data);
            console.warn(JSON.stringify(data.data));
            if (data.data.status == "OK") {

                noticia.views = data.data.detail

                $scope.notiViews = noticia;

                console.log(JSON.stringify($scope.notiViews));
                // ons.createDialog("likes.html",{parentScope:$scope}).then(function(dialog) {
                //   dialog.show();
                // });
                if ($scope.notiViews.views.length > 0) {
                    ons.createAlertDialog("views.html", {
                        parentScope: $scope
                    }).then(function (alert) {
                        $scope.notiDialog2 = alert;
                        $scope.notiDialog2.show();
                    });
                }

            }
        });


    };

    /*
     $scope.hideNotificationApp = function () {
        $location.search({});
        $scope.notiDialog.hide();
        $scope.notiDialog2.hide();
      }*/
    $scope.addSpec = function (s) {
        $http.get($scope.server + "/php/specsAPI/altaSpec.php?objetivo=" + $scope.ticket.id + "&descripcion=" + s).
        then(function (data) {
            console.log(data.data);
            $scope.ticket.specs.unshift({
                id: data.data.detail,
                descripcion: s,
                estatus: "Pendiente"
            });
            $scope.nuevo.spec = "";
        });
    }
    $scope.check = function (c) {
        $http.post($scope.server + "/php2alex/pap/update.php", {
            tabla: "especificacion",
            campo: "estatus",
            valor: c.estatus == "Completado" ? "Pendiente" : "Completado",
            campoObjetivo: "id",
            valorObjetivo: c.id
        }).then(function (data) {
            console.log(JSON.stringify(data.data));

        });
    }
    $scope.fileArray = [];
    $scope.processfile = function (f, index) {
        var deferred = $q.defer();
        reader = new FileReader();

        try {
            reader.readAsDataURL(f);
        } catch (error) {
            console.log('Error: ', error);
        }

        reader.onload = function () {

        };
        reader.onerror = function (error) {
            console.log('Error: ', error);
        };

        reader.onprogress = function (data) {
            console.log(data);

        };
        reader.onprogress = function (data) {
            //console.log(data);

        };
        reader.onloadend = function (data) {
            deferred.resolve({
                b64: reader.result,
                index: index
            });
        }
        return deferred.promise;
    }
    $scope.upload = function (i) {
        console.warn($scope.fileArray);
        $scope.processfile($scope.fileArray[i], i).then(function (data) {
            console.log(data);
            var id = $scope.ticket.id;
            $http.post($scope.server + "/php2alex/files/b64.php", {
                id: id,
                file: data.b64,
                name: {
                    name: $scope.fileArray[i].name
                }
            }).then(function (df) {
                $http.get($scope.server + "/php2alex/files/getFiles.php?id=" + id).then(function (df) {
                    $scope.ticket.files = df.data;
                    if ((data.index + 1) < $scope.fileArray.length) {
                        $scope.upload(data.index + 1);
                    } else {
                        console.log($scope.fileArray);
                    }
                });
                //console.log(df);

            });

        });
    }
    $scope.deleteFile = function (file, nombre) {
        console.log(file);
        ons.notification.confirm({
            message: "¿Seguro que deseas eliminar este archivo?",
            callback: function (resp) {
                if (resp > 0) {
                    $http.get($scope.server + "/php2alex/files/deleteFile.php?file=" + ($scope.ticket.id + "/" + nombre)).
                    then(function (data) {
                        for (var i = 0; i < $scope.ticket.files.length; i++) {
                            console.log($scope.ticket.files[i].archivo);
                            if ($scope.ticket.files[i].archivo == nombre) {
                                $scope.ticket.files.splice(i, 1);
                            }
                        }
                    });
                }
            }
        });
    }


    $scope.devolverFecha = function (fecha) {
        var meses = new Array("", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
        var rightNow = new Date(fecha);
        var respuesta = rightNow.toISOString().slice(0, 10).replace(/-/g, "-");
        var resArray = respuesta.split('-');
        var mes = resArray[1].split('0');
        if (mes.length > 1) {
            mes.splice(0, 1);
        };
        return (resArray[2] + " de " + meses[mes] + " de " + resArray[0]);
    }


    $scope.CambiarEstatusSpecIndivuRuta = function (obj) {
        if (obj.check) {
            obj.check = false;
        } else {
            obj.check = true;
        }
        var objEnviar = {
            id_spec: obj.id,
            actividad_estatus: obj.check
        };

        $dom.updateCheckSpec(objEnviar).then(function (res) {
            console.warn(res);
        });

    }




    $scope.agregarNuevoComentario = function () {
        console.log($scope.usuario);
        console.log($scope.usuarios);
        console.log($scope.ticket);
        var d = new Date();
        $scope.nuevoCom = {
            id: "",
            comment: "" + $scope.newComment.comment,
            autor: "" + $scope.usuario.usuario,
            date: d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate(),
            hour: d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()

        };
        console.log($scope.nuevoCom);
        var dataPost = {
            entregable_id: $scope.ticket.id,
            comment: "" + $scope.newComment.comment,
            autor: $scope.usuario.usuario,
            date: d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate(),
            hour: d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()
        }
        console.log(
            dataPost
        );


        var arrUserEnviarFinal = [];

        arrUserEnviarFinal.push($scope.usuario.puesto);

        for (var i in $scope.usuarios) {
            var n = $scope.newComment.comment.indexOf("@" + $scope.usuarios[i].wikiname);
            if (n != -1 && $scope.usuarios[i].puestoID !== $scope.usuario.puesto) {
                arrUserEnviarFinal.push($scope.usuarios[i].puestoID);

            };

        }



        var req = {
            url: $dom.getServer() + "/php/comment/altaCommentTrabajadores.php",
            method: "POST",
            data: dataPost,
            headers: {
                "Content-Type": undefined
            },
        }
        $http(req).then(function (data) {
            console.warn(data);
            if (data.data.status == "OK") {
                $scope.nuevoCom.id = "" + data.data.newMessage;

                console.log(data.data.newMessage);
                $scope.ticket.comments.push($scope.nuevoCom);
                console.warn($scope.usuario);

                if (arrUserEnviarFinal.length > 0) {
                    var objEnviarNotPush = {
                        id_actividad: $scope.ticket.id_pap,
                        id_mensaje: '' + $scope.nuevoCom.id,
                        id_user_envio: $scope.usuario.puesto,
                        app: 'operation',
                        type: 'e',
                        nombreUserEnvia: '' + $scope.usuario.usuario,
                        fecha_pub: $scope.getDateTimeActual().date,
                        hora_pub: $scope.getDateTimeActual().time,
                        id_actividad_entregable: $scope.ticket.id,
                        misusuarios: arrUserEnviarFinal,
                        visto: '0',
                        fecha_visto: "0000-00-00",
                        hora_visto: "00:00",
                        firma: '0',
                        prioridad: '' + $scope.ticket.prioridad,
                        titulo: '' + $scope.ticket.titulo
                    };
                    console.warn(objEnviarNotPush);
                    $dom.insertarNotificacionesMiPlanABoard(objEnviarNotPush).then(function (res) {
                        console.log(res);
                        // $scope.LimpiarUsuarios();
                    });

                };









                $scope.newComment.comment = "";

            }
        });


    }


    $scope.buscarUser = "";

    $scope.convertirObjectUserArray = function () {
        var ary = [];
        angular.forEach($scope.usuarios, function (val, key) {
            ary.push(val);
        });
        return ary;
    };

    $scope.CambiarEstadoSpec = function (obj) {
        if (obj.check == true) {
            obj.check = false;
        } else if (obj.check == false) {
            obj.check = true;
        }
    }

    $scope.AddUserComment = function (cadena) {
        console.log($scope.newComment.comment);
        $scope.newComment.comment = $scope.newComment.comment.substring(0, $scope.newComment.comment.length - 1);
        console.log($scope.newComment.comment);

        for (var i in $scope.usuarios) {
            if ($scope.usuarios[i].check) {

                $scope.newComment.comment += " @" + $scope.usuarios[i].wikiname;
            };
            //console.log($scope.usuarios[i])


        }
        $scope.dialogusuariosAddVistaNoti.hide();
    }
    $scope.contador = 0;

    $scope.LimpiarUsuarios = function () {
        $scope.contador = 0;
        for (var i in $scope.usuarios) {
            // console.log($scope.usuarios[i])
            Object.defineProperty($scope.usuarios[i], "check", {
                value: false,
                writable: true,
                enumerable: true,
                configurable: true
            });
        }

    }

    $scope.FocusContadores = function (cadena) {
        $scope.LimpiarUsuarios();
        $scope.contador = cadena.split("@").length - 1;
        console.log($scope.contador);
    }

    $scope.VerificarArroba = function (cadena, $event, contador) {

        console.log(contador);
        console.log(cadena.split("@").length - 1);
        console.log($scope.contador);
        if ($scope.contador < cadena.split("@").length - 1) {
            // alert("la letra @ encontrada");
            console.log("suma");
            $scope.buscarUser = "";

            $scope.contador++;
            /*
          ons.createDialog("history.html", {
      parentScope: $scope
    }).then(function (dialog) {
      dialog.show();
    });
*/
            ons.createDialog("usuariosAddVistaNoti.html", {
                parentScope: $scope
            }).then(function (dialog) {
                dialog.show();
            });

            /*
                    ons.createPopover("usuariosAddVistaNoti.html", {parentScope: $scope}).then(function(d){
                      d.show($event);
                    });*/
        } else if ($scope.contador > cadena.split("@").length - 1) {
            // alert("la letra @ encontrada");
            console.log("resta");
            $scope.contador--;

        } else {
            console.log("No esta");
        }

    }








});