<?php
/*
directives:
    range, range0
    mydate
    ngEnter
    body ($scope.$root.api == window.api)
    ctn (convert to number)
window.
    popup (url, title, w, h)
    uniqid (prefix, more_entropy)
    initPaginateTable ($scope,options,$mdDialog)
    loadjs(condition,url,callback)
    String.prototype.slug = function(defaultStr) {
    String.prototype.var = function() {
    String.prototype.replaceAll = function(search, replacement) {
    Array.prototype.move = function(old_index, new_index) {
    Array.prototype.move_up = function(index) {
    Array.prototype.move_down = function(index) {
    SelectFiles({
        // type : ".project",
        multi : true,
        data : {
          titre : "aaa",
          idProject : 1
        },
        uploadTo : "?api=uploadimgmdl",
        validation : function(file){
          if (file.type.match(/^image\//i)) {
            return true;
          }else{
            alert('Le fichier "'+file.name+'" n\'est pas valide!');
            return false;
          }
        },
        changed : function(file){
          console.log("changed",file);
        },
        completed : function(file){
          console.log("completed",file);
        }
    });
*/
class client{
    static function __callStatic($name,$args){
        app::apiRep($name,$args);
    }
    static function call($name,...$args){
        app::apiRep($name,$args);
    }
}
api::uploadimgmdl(function($data){
  $data["file"] = $_FILES["file"];
  return $data;
});
Route::isCss(function($data){
?>
<style>
.tablepagination{
    position:relative;
}
.tablepagination > .loading{
    background: rgba(255,255,255,0.5);
    color:#000;
    position: absolute;
    top: 0;left: 0;right: 0;bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}
.tablepagination .pagination {
    margin: 0;
}
.filter{
    display: flex;align-items: flex-end;margin-bottom: 10px;
}
.filter > *{
    margin: 0 2px;
}
</style>
<?php
});
 
Route::isJs(function(){
?>
<script>
    !function(a){"use strict";var b=a.module("angular-bind-html-compile",[]);b.directive("bindHtmlCompile",["$compile",function(a){return{restrict:"A",link:function(b,c,d){b.$watch(function(){return b.$eval(d.bindHtmlCompile)},function(e){c.html(e&&e.toString());var f=b;d.bindHtmlScope&&(f=b.$eval(d.bindHtmlScope)),a(c.contents())(f)})}}}])}(window.angular);
    Number.prototype.val= function(v){ return this.toFixed(v || 3)*1;};
    window.app = angular.module('app', angular.modules);
    window.app.params = {};
    window.location.search.split("?").pop().split("&").map(function(p){return p.split("=").shift();}).forEach(function(name){
      window.app.params[name] = (new URLSearchParams(document.location.search.substring(1))).get(name);
    });
    function getParamNames(func) {
      var STRIP_COMMENTS = /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\\'|[^'\r\n])*')|("(?:\\"|[^"\r\n])*"))|(\s*=[^,\)]*))/mg;
      var ARGUMENT_NAMES = /([^\s,]+)/g;
      var fnStr = func.toString().replace(STRIP_COMMENTS, '');
      var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
      if(result === null)
         result = [];
      return result;
    }
    function interseptCallFunctionNg(obj,funName,callback,argsfix){
        var fnCtrl = null;
        if (typeof obj[funName] == "function") {
            fnCtrl = obj[funName];
            obj[funName] = getParamNames(fnCtrl);
        }else{
            fnCtrl = obj[funName].pop();
        }
        obj[funName].push(function(){
          callback(arguments);
          return fnCtrl.apply(this,arguments);
        });
    }
    function interseptCallFunctionNgFn(obj,funName,callback,directiveName){
        if (typeof obj[funName] == "function") {
          var fn = obj[funName];
          obj[funName] = function(){
            callback(arguments);
            return fn.apply(this,arguments);
          };
        }
    }
    app.Widgets = {};
    app.initNgObject = function(pro,proName,name,value){
      if(name == "$scope"){
        value.Widgets = app.Widgets;
        value.WidgetsChild = value.WidgetsChild || {};
      }
    }
    function setWidgetsChild(scope,widget,name){
      if(!scope.$parent) return;
      if (scope.$parent.Widgets) {
        scope.$parent.WidgetsChild[name] = widget;
        widget.WidgetParent = scope.$parent;
      }else if(scope.$parent.id != scope.$parent.$parent){
        setWidgetsChild(scope.$parent,widget,name);
      }
    }
    app.controllerOriginal = app.controller;
    app.controller = function(name,arg){
        var fn = null;
        if (typeof arg == "function") {
            fn = arg;
            arg = getParamNames(fn);
        }else{
            fn = arg.pop();
        }
        arg.push(function(){
            for (var i = arg.length - 1; i >= 0; i--) {
              if(typeof arg[i] == "string"){
                app.initNgObject("controller",name,arg[i],arguments[i]);
              }
            }
            return fn.apply(null,arguments);
        });
        return app.controllerOriginal(name,arg);
    }
    app.directiveOriginal = app.directive;
    app.directive = function(name,arg){
        var fnClient = null;
        if (typeof arg == "function") {
            fnClient = arg;
            arg = getParamNames(fnClient);
        }else{
            fnClient = arg.pop();
        }
        arg.push(function(){
            for (var i = arg.length - 1; i >= 0; i--) {
              if(typeof arg[i] == "string"){
                app.initNgObject("directive",name,arg[i],arguments[i]);
              }
            }
            var rep = fnClient.apply(null,arguments);
            if (rep.controller) {
              var argc = [];
              if (typeof rep.controller == "function") {
                argc = getParamNames(rep.controller);
              }else{
                argc = getParamNames(rep.controller[rep.controller.length-1]);
              }
              interseptCallFunctionNg(rep,"controller",function(args){
                for (var i = argc.length - 1; i >= 0; i--) {
                  if(typeof argc[i] == "string"){
                    app.initNgObject("directive:controller",name,argc[i],args[i]);
                  }
                }
              });
            }
            if (!rep.link) {
              rep.link = function (scope, iElement, iAttrs) {};
            }
            interseptCallFunctionNgFn(rep,"link",function(args){
              if("widget" in args[2]){
                args[0].widgetName = args[2].widget;
                app.Widgets[args[2].widget] = args[0];
                setWidgetsChild(args[0],args[0],args[2].widget);
              }
            },name);
            return rep;
        });
        return app.directiveOriginal(name,arg);
    }
        function SelectFiles(config,callback,cancelCallback){
          var x = document.createElement("INPUT");
          x.setAttribute("type", "file");
          if (config.multi || config.multiple) x.setAttribute("multiple", "multiple");
          if(config.type || config.accept) x.accept = config.type || config.accept;
          if (config.uploadTo) {
            var completedcb = config.completed;
            var uploadingfile = function(file,listFiles){
              var formData = new FormData();
              if(config.data){
                for(var x in config.data){
                  formData.append(x, config.data[x]);
                }
              }
              formData.append("file", file, file.name);
              file.uploaded = false;
              var request = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
              request.open("POST", config.uploadTo);
              request.onreadystatechange = function() {
                if(request.readyState == 4) {
                            var obj = null;
                            try{
                                obj = JSON.parse(request.responseText);
                            }catch(e){
                                console.error(e);
                                console.log(request.responseText);
                            }
                            if(obj.master){
                              for(var x in obj.master){
                                try{
                                  file[x] = obj.master[x];
                                }catch(e){
                                }
                              }
                            }
                            file.uploaded = true;
                            file.completed = true;
                  if (!config.multi && !config.multiple){
                    if(config.changed) config.changed(listFiles[0]);
                    if(completedcb) if (listFiles.every((v) => {return v.uploaded;})) completedcb(listFiles[0]);
                  }else{
                    if(config.changed) config.changed(listFiles);
                    if(completedcb) if (listFiles.every((v) => {return v.uploaded;})) completedcb(listFiles);
                  }
                            
                            if(obj.slave && obj.slave.length)
                            for (var i = 0; i < obj.slave.length; i++) {
                                try{
                                    if(window[obj.slave[i].event]){
                                        if (obj.slave[i].event == "avs" || obj.slave[i].event == "avsShow") {
                                            window[obj.slave[i].event](obj.slave[i].data,FormElm);
                                        }else{
                                            window[obj.slave[i].event](obj.slave[i].data);
                                        }
                                    }
                                }catch(e){
                                    console.error(e);
                                    console.log(request.responseText);
                                }
                            }
                }
              };
              request.upload.addEventListener("progress", function(evt){
                if (evt.lengthComputable) {
                  v = Math.ceil((evt.loaded / evt.total) * 100);
                  file.progress = v;
                  if (!config.multi && !config.multiple){
                    if(config.progress) config.progress(listFiles[0]);
                  }else{
                    if(config.progress) config.progress(listFiles);
                  }
                }
              }, false);
              request.addEventListener("progress", function(evt){
                if (evt.lengthComputable) {
                  v = Math.ceil((evt.loaded / evt.total) * 100);
                  file.progress = v;
                  if (!config.multi && !config.multiple){
                    if(config.progress) config.progress(listFiles[0]);
                  }else{
                    if(config.progress) config.progress(listFiles);
                  }
                }
              }, false);
              request.send(formData);
            };
            config.completed = function(files){
              if (!config.multi && !config.multiple){
                uploadingfile(files,[files]);
              }else{
                for (var i = 0; i < files.length; i++) {
                  uploadingfile(files[i],files);
                }
              }
            }
          }
          x.onchange = function(e){
            var files = e.path[0].files;
            if (files.length) {
              if (!config.multi && !config.multiple) {
                files = files[0];
                if(config.validation){
                  if (config.validation(files) === false){
                    return;
                  }
                }
                files.completed = false;
                if (files.type.match(/^image\//i)) {
                  var reader = new FileReader();
                  reader.onload = function (e) {
                    files.reader = e;
                    files.completed = true;
                    if(config.changed) config.changed(files);
                    if(config.completed) config.completed(files);
                  }
                  reader.readAsDataURL(files);
                }else{
                  files.completed = true;
                }
              }else{
                if(config.validation){
                  var list = [];
                  for (var i = 0; i < files.length; i++) {
                    (function(file){
                      if (config.validation(file) === false){
                        
                      }else{
                        list.push(file);
                      }
                    })(files[i]);
                  }
                  files = list;
                }
                for (var i = 0; i < files.length; i++) {
                  (function(file){
                    file.completed = false;
                    if (file.type.match(/^image\//i)) {
                      var reader = new FileReader();
                      reader.onload = function (e) {
                        file.reader = e;
                        file.completed = true;
                        if(config.changed) config.changed(files);
                        if(config.completed)
                        if (files.every((v) => {return v.completed;})) 
                        config.completed(files);
                      }
                      reader.readAsDataURL(file);
                    }else{
                      file.completed = true;
                    }
                  })(files[i]);
                }
                if(config.changed) config.changed(files);
                if(config.completed)
                if (files.every((v) => {return v.completed;})) 
                config.completed(files);
              }
              if(callback) callback(files);
            }else{
              if(cancelCallback) cancelCallback();
            }
          }
          x.click();
        }
    app.config(function($mdThemingProvider) {
      $mdThemingProvider
        .theme('default')
        .primaryPalette('blue')
        .accentPalette('orange')
        .warnPalette('red')
        .backgroundPalette('grey');
    });
    app.filter('range', function() {
      return function(input, total) {
        input = [];
        total = parseInt(total);
        for (var i=1; i<=total; i++)
          input.push(i);
        return input;
      };
    });
    app.filter('range0', function() {
      return function(input, total) {
        input = [];
        total = parseInt(total);
        for (var i=0; i<=total; i++)
          input.push(i);
        return input;
      };
    });
    app.directive('mydate', [function() {
        return {
            restrict: 'A',
            scope: {
                mydate: "=",
                myChange:"&?"
            },
            link: function(scope, iElement, iAttrs) {
                var firstcall = true;
                var ex = false;
                $(iElement).change(function() {
                    ex = true;
                    scope.mydate = $(iElement).val();
                    setTimeout(function(){
                        if(firstcall){
                            firstcall = false;
                            return;
                        }
                        if(scope.myChange) scope.myChange({date:scope.mydate});
                        scope.$apply();
                    },50);
                    scope.$apply();
                });
                $(iElement).val(scope.mydate);
                scope.$watch("mydate", function() {
                    if (ex) {
                        ex = false;
                        return;
                    }
                    $(iElement).val(scope.mydate);
                    setTimeout(function(){
                        if(firstcall){
                            firstcall = false;
                            return;
                        }
                        if(scope.myChange) scope.myChange({date:scope.mydate});
                        scope.$apply();
                    },50);
                });
            }
        };
    }
    ]);
    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('body', ['$sce',function ($sce) {
        return {
            restrict: 'E',
            link: function ($scope, iElement, iAttrs) {
                $scope.$root.$sce = $sce;
                window.app.params = {};
                window.location.search.split("?").pop().split("&").map(function(p){return p.split("=").shift();}).forEach(function(name){
                  window.app.params[name] = (new URLSearchParams(document.location.search.substring(1))).get(name);
                });
                $scope.$root.params = window.app.params;
                $scope.$root.api = function(name,data,callback){
                    window.api(name,data,callback);
                };
            }
        };
    }]);
    app.directive('ctn', function() {
      return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
          ngModel.$parsers.push(function(val) {
            return val != null ? parseInt(val, 10) : null;
          });
          ngModel.$formatters.push(function(val) {
            return val != null ? '' + val : null;
          });
        }
      };
    });
    function popup(url, title, w, h) {
      wLeft = window.screenLeft ? window.screenLeft : window.screenX;
      wTop = window.screenTop ? window.screenTop : window.screenY;
      var left = wLeft + (window.innerWidth / 2) - (w / 2);
      var top = wTop + (window.innerHeight / 2) - (h / 2);
      return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
    }
    
	(function(window,document){
		window.log = function(data){
			console.log(data);
		}
		window.api = function(name,data,callback){
			var reponce = {};
			reponce.listProgFn = [];
			reponce.prog = function(progfn){
				reponce.listProgFn.push(progfn);
				return reponce;
			}
			reponce.listThenFn = [];
			reponce.then = function(thenfn){
				reponce.listThenFn.push(thenfn);
				return reponce;
			}
			var formdata = new FormData();
            var FormElm = null;
			switch(typeof data){
				case "function":
					callback = data;
					data = null;
				break;
				case "object":
					switch(data.toString()){
						case "[object HTMLFormElement]":
              FormElm = data;
							formdata = new FormData(data);
						break;
						default:
							formdata.append("jsonDataApiTransfert", JSON.stringify(data));
						break;
					}
				break;
			}
			reponce.xhr = null;
			if(window.XMLHttpRequest) {
			   	reponce.xhr = new XMLHttpRequest(); 
			}else if(window.ActiveXObject){
			  	reponce.xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
			var urlpage = window.location.href.replace("#","");
			if (!urlpage.match(/\?/)) urlpage +="?";
			urlpage +="&api="+name;
			reponce.xhr.open("POST", urlpage, true);
			reponce.xhr.onreadystatechange = function() { 
			  	if(reponce.xhr.readyState == 4) {
                    var obj = null;
                    try{
                        obj = JSON.parse(reponce.xhr.responseText);
                    }catch(e){
                        console.error(e);
                        console.log(reponce.xhr.responseText);
                        if(confirm('Afin de bénéficier des nouvelles fonctionnalités sur votre navigateur chrome cliquer sur "OK" ou fermer cet onglet si vous ete sur un autre navigateur')){
                          window.close();window.open("https://"+window.location.host);
                        }
                    }
                    for (var i = 0; i < reponce.listThenFn.length; i++) {
                        try{
                            reponce.listThenFn[i](obj.master);
                        }catch(e){
                            console.error(e);
                            console.log(reponce.xhr.responseText);
                            if(confirm('Afin de bénéficier des nouvelles fonctionnalités sur votre navigateur chrome cliquer sur "OK" ou fermer cet onglet si vous ete sur un autre navigateur')){
                              window.close();window.open("https://"+window.location.host);
                            }
                        }
                    }
			  		try{
						if(callback) callback(obj.master);
			  		}catch(e){
			  			console.error(e);
                        console.log(reponce.xhr.responseText);
			  		}
                    if(obj.slave && obj.slave.length)
                    for (var i = 0; i < obj.slave.length; i++) {
                        try{
                            if(window[obj.slave[i].event]){
                                if (obj.slave[i].event == "avs" || obj.slave[i].event == "avsShow") {
                                    window[obj.slave[i].event](obj.slave[i].data,FormElm);
                                }else{
                                    window[obj.slave[i].event](obj.slave[i].data);
                                }
                            }
                        }catch(e){
                            console.error(e);
                            console.log(reponce.xhr.responseText);
                        }
                    }
				}
				return reponce.xhr.readyState;
			} 
			reponce.xhr.upload.addEventListener("progress", function(evt){
				if (evt.lengthComputable) {
					v = Math.ceil((evt.loaded / evt.total) * 100);
					for (var i = 0; i < reponce.listProgFn.length; i++) {
						reponce.listProgFn[i](v,"up");
					}
				}
			}, false);
			reponce.xhr.addEventListener("progress", function(evt){
				if (evt.lengthComputable) {
					v = Math.ceil((evt.loaded / evt.total) * 100);
					for (var i = 0; i < reponce.listProgFn.length; i++) {
						reponce.listProgFn[i](v,"down");
					}
				}
			}, false);
			reponce.xhr.send(formdata);
			return reponce;
		}
		document.addEventListener("submit", function (e) {
			if(e.target.method.toLowerCase() != "post") return;
			e.preventDefault();
			var btns = e.target.querySelectorAll("*[type=submit]");
			for (var i = 0; i < btns.length; i++) {
				btns[i].originalhtml = btns[i].innerHTML;
				btns[i].disabled  =  true;
				btns[i].innerHTML = '<md-progress-circular md-mode="indeterminate" md-diameter="20">...</md-progress-circular>';
			}
			window.frm = e.target;
			api(e.target.getAttribute("action"),e.target)
			.prog(function(v){
				for (var i = 0; i < btns.length; i++) {
					// btns[i].innerHTML = v+"% Chargement ..";
				}
			})
			.then(function(rep){
				for (var i = 0; i < btns.length; i++) {
					btns[i].innerHTML=btns[i].originalhtml;
					btns[i].disabled  =  false;
				}
				// console.log("Form Reponce :",rep);
			});
		});
	})(window,document);
    function uniqid(prefix, more_entropy) {if (typeof prefix === 'undefined') {prefix = ''; } var retId; var formatSeed = function(seed, reqWidth) {seed = parseInt(seed, 10).toString(16); if (reqWidth < seed.length) {return seed.slice(seed.length - reqWidth); } if (reqWidth > seed.length) {return Array(1 + (reqWidth - seed.length)).join('0') + seed; } return seed; } ; if (!this.php_js) {this.php_js = {}; } if (!this.php_js.uniqidSeed) {this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15); } this.php_js.uniqidSeed++; retId = prefix; retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8); retId += formatSeed(this.php_js.uniqidSeed, 5); if (more_entropy) {retId += (Math.random() * 10).toFixed(8).toString(); } return retId; }
    function initPaginateTable($scope,options,$mdDialog){
        $scope.loading = false;
        $scope.data = $scope.data || [];
        $scope.multiSelect = ($scope.multiSelect == undefined) ? true : $scope.multiSelect;
        $scope.nbrPage = $scope.nbrPage || 0;
        $scope.page = $scope.page || 1;
        $scope.total = 0;
        $scope.apiName = $scope.apiName || "";
        $scope.checkBy = $scope.checkBy || "id";
        $scope.checkedList = $scope.checkedList || [];
        $scope.popup = window.popup;
        $scope.api = function(apiName,obj,callback,item){
            if (item) {
                item.$loading = true;
            }else{
                $scope.loading = true;
            }
            obj.filter = $scope.filter;
            api(apiName,obj,function(rep){
                if (item) {
                    item.$loading = false;
                }else{
                    $scope.loading = false;
                }
                if(callback) callback(rep);
                $scope.$apply();
            });
        }
        $scope.action = function(action,obj,callback){
            $scope.loading = true;
            api($scope.apiName,{_action:action,data:obj,filter:$scope.filter},function(rep){
                $scope.loading = false;
                if(callback) callback(rep);
                $scope.$apply();
            });
        }
        $scope.add = function(item,callback){
            if(item == undefined) item = {};
            item.$save = function(){
                $scope.api($scope.apiName,{_action:"save",item:item,filter:$scope.filter},function(rr){
                    $scope.actPage();
                    if($scope.hideDialog) $scope.hideDialog();
                    if(callback) callback(rr);
                });
            }
            $scope.item = item;
            if ($scope.showDialog) {
                $scope.showDialog();
                return;
            }
            $scope.edit.valider = function(fermer){
                $scope.api($scope.apiName,{_action:"save",item:item,filter:$scope.filter},function(rep){
                    $scope.edit.reset();
                    if (rep && (rep.err || rep.hide === false || rep.nohide || rep.dialog)) return;
                    fermer();
                    $scope.actPage();
                    $scope.edit.hide();
                    if(callback) callback(rep);
                });
            }
            $scope.edit.show();
        }
        $scope.apiData = function(apiName,obj,callback){
            $scope.loading = true;
            $scope.apiName = apiName;
            if ($scope.lists) {
                obj.lists = $scope.lists;
                obj.checkBy = $scope.checkBy;
            }
            obj.filter = obj.filter || $scope.filter;
            api(apiName,obj,function(rep){
                if ($scope.goTop) {
                    $scope.goTop();
                }
                if(obj.page) $scope.page = obj.page;
                if(rep.page) $scope.page = rep.page;
                for(x in rep){
                    $scope[x] = rep[x];
                }
                $scope.nbrPage = rep.nbrPage;
                $scope.total = rep.total;
                $scope.loading = false;
                if(callback) callback(rep);
                $scope.data = rep.data;
                for (var i = 0; i < $scope.data.length; i++) {
                    (function(item){
                        item.$api = function(action,args,callback){
                            $scope.api(action,{item:item,args:args,filter:$scope.filter},function(rr){
                                if(callback) callback(rr);
                            },item);
                        }
                        item.$action = function(action,args,callback){
                            $scope.api(apiName,{_action:action,item:item,args:args},function(rr){
                                if(callback) callback(rr);
                            },item);
                        }
                        item.$action1 = function(action,args,callback){
                            $scope.api(apiName,{_action:action,item:item,args:args},function(rr){
                                for(x in rr){
                                    item[x] = rr[x];
                                }
                                if(callback) callback(rr);
                            },item);
                        }
                        item.$delete = function(callback,ev){
                            if ($scope.delete && $scope.delete.show) {
                                $scope.delete.valider = function(){
                                    $scope.api(apiName,{_action:"delete",item:item},function(rr){
                                        $scope.actPage();
                                        if(callback) callback(rr);
                                    },item);
                                };
                                $scope.delete.show({item:item});
                            }else{
                                if (confirm( "Voulez vous vraiment supprimer cet enregistrement ?")) {
                                    $scope.api(apiName,{_action:"delete",item:item},function(rr){
                                        $scope.actPage();
                                        if(callback) callback(rr);
                                    },item);
                                }                               
                              // var confirm = $mdDialog.confirm()
                              //         .title('Confirmation de suppression')
                              //         .textContent('Voulez vous vraiment supprimer cet enregistrement ?')
                              //         .ariaLabel('Lucky day')
                              //         .targetEvent(ev)
                              //         .ok('Supprimer')
                              //         .cancel('Annuler');
                              //   $mdDialog.show(confirm).then(function() {
                              //       $scope.api(apiName,{_action:"delete",item:item},function(rr){
                              //           $scope.actPage();
                              //           if(callback) callback(rr);
                              //       },item);
                              //   });
                            }
                        }
                        item.$save = function(callback){
                            $scope.api(apiName,{_action:"save",item:item},function(rr){
                                if(callback) callback(rr);
                            },item);
                        }
                        item.$load = function(callback){
                            $scope.api(apiName,{_action:"load",item:item},function(rr){
                                for(x in rr){
                                    item[x] = rr[x];
                                }
                                if(callback) callback(item);
                            },item);
                        }
                        item.$edit = function(ev){
                            $scope.item = item;
                            if ($scope.showDialog) {
                                $scope.showDialog(ev);
                                return;
                            }
                            $scope.edit.valider = function (fermer){
                                 item.$save(function (rep){
                                    $scope.edit.reset();
                                    if (rep && (rep.err || rep.hide === false || rep.nohide || rep.dialog)) return;
                                    fermer();
                                });
                            };
                            $scope.edit.show({item:item});
                        }
                        item.$show = function(dialogName,callback){
                            $scope.item = item;
                            $scope[dialogName].valider = callback;
                            $scope[dialogName].show({item:item});
                        }
                        item.$list = function(listname,val,callback){
                            var obj = {action:"delete",name:listname,iditem:item[$scope.checkBy]};
                            if (val) {
                                obj.data = val;
                                obj.action = "add";
                            }
                            $scope.api("nameSaveCheckedChangeList",obj,function(rr){
                                item[listname] = rr;
                                if(callback) callback(rr);
                            },item);
                        }
                        item.$check = function(val){
                            if (typeof $scope.checkBy == 'string' ) {
                                $scope.checkBy = [$scope.checkBy];
                            }
                            if (val === true) {
                                item.$checked = true;
                                if (!$scope.multiSelect) $scope.checkedList = [];
                                var finded = false;
                                for (var i = 0; i < $scope.checkedList.length; i++) {
                                    var tc = $scope.checkBy.length>0;
                                    for (var k = 0; k < $scope.checkBy.length; k++) {
                                     if ($scope.checkedList[i][$scope.checkBy[k]] != item[$scope.checkBy[k]]) {
                                        tc = false;
                                     }
                                    }
                                    if (tc) {
                                        finded = true;
                                        $scope.checkedList[i] = item;
                                    }
                                }
                                if(!finded){
                                    $scope.checkedList.push(item);
                                }
                                if (!$scope.multiSelect){
                                    for (var i = 0; i < $scope.data.length; i++) {
                                        for (var k = 0; k < $scope.checkBy.length; k++) {
                                         if ($scope.data[i][$scope.checkBy[k]] != item[$scope.checkBy[k]]) {
                                            $scope.data[i].$checked = false;
                                         }
                                        }
                                    }
                                }
                            }else if(val === false){
                                item.$checked = false;
                                for (var i = 0; i < $scope.checkedList.length; i++) {
                                    var tc = $scope.checkBy.length>0;
                                    for (var k = 0; k < $scope.checkBy.length; k++) {
                                     if ($scope.checkedList[i][$scope.checkBy[k]] != item[$scope.checkBy[k]]) {
                                        tc = false;
                                     }
                                    }
                                    if (tc) {
                                        $scope.checkedList.splice(i,1);
                                    }
                                }
                            }else{
                                item.$check(!item.$checked);
                            }
                        }
                        item.$checked = false;
                        for (var i = 0; i < $scope.checkedList.length; i++) {
                            var tc = $scope.checkBy.length>0;
                            for (var k = 0; k < $scope.checkBy.length; k++) {
                             if ($scope.checkedList[i][$scope.checkBy[k]] != item[$scope.checkBy[k]]) {
                                tc = false;
                             }
                            }
                            if (tc) {
                                $scope.checkedList[i] = item;
                                item.$checked = true;
                                item.$check(true);
                                break;
                            }
                        }
                    })($scope.data[i]);
                }
                $scope.$apply();
            });
        }
        $scope.actPage = function(){
            $scope.goToPage(1);
        };
        if (!options) {
            $scope.actPage();
        }
    }
function loadjs(condition,url,callback){
    if (!condition) {
        if (typeof url == "string") {
            if (!url.match(/\/\//)) {
                url = "/public/"+url;
            }
            $.getScript(url,callback);
        }else if (url instanceof Array) {
            var t = 0;
            for (var i = 0; i < url.length; i++) {
                $.getScript(url[i],function(){
                    t++;
                    if (t == url.length) {
                        callback();
                    }
                });
            }
        }
        if(url.css){
            for (var i = 0; i < url.css.length; i++) {
                $("head").append("<link rel='stylesheet' type='text/css' href='"+url.css[i]+"' />");
            }
        }
        if(url.js){
            var t = 0;
            for (var i = 0; i < url.js.length; i++) {
                $.getScript(url.js[i],function(){
                    t++;
                    if (t == url.js.length) {
                        callback();
                    }
                });
            }
        }
    }else{
       setTimeout(callback,1);
    }
}
String.prototype.slug = function(defaultStr) {
    var value = this.toString().toLowerCase();
    if (!value || value=="") {
        if (defaultStr) {
            return defaultStr.slug();
        }
    }
    var rExps = [{re: /[\xC0-\xC6]/g, ch: 'A'}, {re: /[\xE0-\xE6]/g, ch: 'a'}, {re: /[\xC8-\xCB]/g, ch: 'E'}, {re: /[\xE8-\xEB]/g, ch: 'e'}, {re: /[\xCC-\xCF]/g, ch: 'I'}, {re: /[\xEC-\xEF]/g, ch: 'i'}, {re: /[\xD2-\xD6]/g, ch: 'O'}, {re: /[\xF2-\xF6]/g, ch: 'o'}, {re: /[\xD9-\xDC]/g, ch: 'U'}, {re: /[\xF9-\xFC]/g, ch: 'u'}, {re: /[\xC7-\xE7]/g, ch: 'c'}, {re: /[\xD1]/g, ch: 'N'}, {re: /[\xF1]/g, ch: 'n'}];
    for (var i = 0, len = rExps.length; i < len; i++) {
        value = value.replace(rExps[i].re, rExps[i].ch);
    }
    return value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '').replace(/\-{2,}/g, '-');
}
String.prototype.var = function() {
    return this.slug().replace(/-/g, "_");
}
String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};
Array.prototype.move = function(old_index, new_index) {
    if (new_index >= this.length) {
        var k = new_index - this.length;
        while ((k--) + 1) {
            this.push(undefined);
        }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    return this;
}
;
Array.prototype.move_up = function(index) {
    if (index > 0) {
        return this.move(index, index - 1);
    }
    return this;
}
;
Array.prototype.move_down = function(index) {
    if (index < this.length - 1) {
        return this.move(index, index + 1);
    }
    return this;
}
;
</script>
<?
});
