CooWorkApp.factory('g', function ($sce,cooConfig,rest,ngDialog) {

    var g = {};
    var fs = require('fs');
    var rq = require('request');

    g.initPTypes=function()
    {
        cooConfig.pTypes = [];
        cooConfig.pTypes.push({ id: 1, name: '布尔型' });
        cooConfig.pTypes.push({ id: 2, name: '枚举型' });
        cooConfig.pTypes.push({ id: 3, name: '整数型' });
        cooConfig.pTypes.push({ id: 4, name: '小数型' });
        cooConfig.pTypes.push({ id: 5, name: '字符串' });
        cooConfig.pTypes.push({ id: 6, name: '时间日期' });
        cooConfig.pTypes.push({ id: 7, name: '长文本' });
        cooConfig.pTypes.push({ id: 10, name: '多附件' });
        cooConfig.pTypes.push({ id: 11, name: '单图片附件' });
        cooConfig.pTypes.push({ id: 12, name: '用户权限列' });
        cooConfig.pTypes.push({ id: 13, name: '流程权限列' });
        cooConfig.pTypes.push({ id: 16, name: '自动编号' });
        cooConfig.pTypes.push({ id: 17, name: '多角色标签' });
        cooConfig.pTypes.push({ id: 18, name: '继承列' });
        cooConfig.pTypes.push({ id: 19, name: '多用户列' });
        cooConfig.pTypes.push({ id: 20, name: '多状态列' });
        cooConfig.pTypes.push({ id: 21, name: '权限公开列' });


        cooConfig.pageTypes = [];
        cooConfig.pageTypes.push({ id: 2, name: '编辑页' });
        cooConfig.pageTypes.push({ id: 3, name: '单列状态编辑' });
        cooConfig.pageTypes.push({ id: 5, name: '批量导入' });
        cooConfig.pageTypes.push({ id: 6, name: '批量编辑' });
        cooConfig.pageTypes.push({ id: 7, name: '数据导出' });
        cooConfig.pageTypes.push({ id: 8, name: '展示页' });
        cooConfig.pageTypes.push({ id: 9, name: '流程控制' });
        cooConfig.pageTypes.push({ id: 10, name: '列表搜索页' });
        cooConfig.pageTypes.push({ id: 11, name: '搜索-列表搜索页' });
        cooConfig.pageTypes.push({ id: 12, name: '排序-列表搜索页' });
        cooConfig.pageTypes.push({ id: 13, name: '统计-列表搜索页' });
        cooConfig.pageTypes.push({ id: 14, name: '列表-列表搜索页' });
        cooConfig.pageTypes.push({ id: 15, name: '新建页' });
        cooConfig.pageTypes.push({ id: 16, name: '报表页' });
        cooConfig.pageTypes.push({ id: 17, name: '搜索-报表页' });
        cooConfig.pageTypes.push({ id: 18, name: '分组统计-报表页' });
        cooConfig.pageTypes.push({ id: 19, name: '列表创建页' });
        cooConfig.pageTypes.push({ id: 20, name: '列表编辑页' });
        cooConfig.pageTypes.push({ id: 22, name: '列表查看页' });
        cooConfig.pageTypes.push({ id: 99, name: '组合创建页' });
        cooConfig.pageTypes.push({ id: 100, name: '组合编辑页' });
        cooConfig.pageTypes.push({ id: 101, name: '组合查看页' });


        cooConfig.eventTypes = [];
        cooConfig.eventTypes.push({ id: 1, name: '加载(client)' });
        cooConfig.eventTypes.push({ id: 2, name: '提交' });
        cooConfig.eventTypes.push({ id: 3, name: '服务端' });
    }

    g.initPTypes();


    g.dateFormat = function (v) {
        if (v!=undefined)
        {
            return v.toString().replace(/(T|\s).+$/ig, '');
        }
        else {
            return '';
        }
    };
    

    g.filterListById = function ($list,$id) {
        return $list.filter(function (v) {
            return v.ID == $id;
        });
    };

    g.filterPatternByCategoryId = function ($patterns, $categoryId) {
        return $patterns.filter(function (v) {
            return v.categoryId == $categoryId;
        });
    };

    g.filterPatternByCategoryIdPType = function ($patterns, $categoryId,$ptype) {
        return $patterns.filter(function (v) {
            return v.categoryId == $categoryId && v.pTypeId==$ptype;
        });
    };


    g.filterPageByCategoryId = function ($pages,$categoryId) {
        return $pages.filter(function (v) {
            return v.categoryId == $categoryId;
        });
    };

    g.filterPattenByCategoryIdSelect = function ($patterns,$categoryId) {
        return $patterns.filter(function (v) {
            return v.categoryId == $categoryId && (v.pTypeId == 2 || v.pTypeId==12 ||v.pTypeId==13 ||v.pTypeId==19||v.pTypeId==20);
        });
    };

    g.filterPattenByCategoryIdSelect2 = function ($patterns, $categoryId) {
        return $patterns.filter(function (v) {
            return v.categoryId == $categoryId && (v.pTypeId == 2 || v.pTypeId == 20);
        });
    };

    g.lscFilterByPattern = function ($lsc, $patternId) {
        return $lsc.filter(function (v) {
            return v.patternId == $patternId;
        });

    };

    g.roleFilterByRoleId = function ($roles, $roleId) {
        return $roles.filter(function (v) {
            return v.RoleId == $roleId;
        });
    };

    g.userFilterByUserId = function ($users, $userId) {
        return $users.filter(function (v) {
            return v.UserId == $userId;
        });
    };


    g.getCategoryById = function ($id) {
        return cooConfig.allcategory.filter(function (v) {
            return v.ID == $id;
        });
    };

    g.roleFilterByRoleIds = function ($roles,$roleIds) {
        return $roles.filter(function (v) {
            return $roleIds.toLowerCase().indexOf(v.RoleId.toLowerCase()) > -1;
        });
    };



    g.userFilterByUserIds = function ($userIds) {
        return cooConfig.alluser.filter(function (v) {
            return $userIds.toLowerCase().indexOf(v.UserId.toLowerCase()) > -1; 
        });
    };


    g.userFilterByRoleId = function ($roleId) {
        return cooConfig.alluser.filter(function (v) {
            return v.RoleIds.toLowerCase().indexOf($roleId.toLowerCase()) > -1
        });
    };


    g.statusFilterByPattern = function ($patternId) {
        return cooConfig.allstatus.filter(function (v) {
            return v.patternId == $patternId;
        });
    };


   g.statusFilterByPatternAndId = function ($patternId, $statusIds) {
        return cooConfig.allstatus.filter(function (v) {
            return v.patternId == $patternId && jQuery.inArray(v.ID, $statusIds) != -1;
        });
    };


   g.statusFilterByIds = function ($statusIds,$patternId) {
       return  cooConfig.allstatus.filter(function (v) {
           return jQuery.inArray(v.ID, $statusIds) != -1 && v.patternId == $patternId;
       });
   };



   g.pageFilterByCategoryType = function ($categoryId, $typeId) {

       return  cooConfig.allpage.filter(function (v) {
           return v.categoryId == $categoryId && v.pageType == $typeId;
       });


   };

   g.pageFilterById = function ($id) {
       return cooConfig.allpage.filter(function (v) {
           return v.ID == $id;
       });
   };

    g.pageFilterByCategory = function ($categoryId) {
        return cooConfig.allpage.filter(function (v) {
            return v.categoryId == $categoryId;
        });
    };

    g.pageFilter = function ($val, $parentId) {
        return cooConfig.allpage.filter(function (v) {
            return v.pageType == $val && v.parentId == $parentId;
        });
    };


    g.elementFilterByPage = function ($pageId) {
        return cooConfig.allelement.filter(function (v) {
            return v.pageId == $pageId;
        });
    };
    

    g.elementFilterByPagePattern = function ($pageId, $patternIds) {
        return cooConfig.allelement.filter(function (v) {
            return v.pageId == $pageId && jQuery.inArray(v.patternId, $patternIds) != -1;
        });
    };



    g.patternFilterById = function ($Id) {
        return cooConfig.allpattern.filter(function (v) {
            return v.ID == $Id;
        });
    };


    g.patternFilterByElements = function ($elementIds) {
        return cooConfig.allpattern.filter(function (v) {
            return jQuery.inArray(v.ID, $elementIds) != -1;
        });
    };


    g.patternFilterByPage = function ($pageId) {
        var elements = g.elementFilterByPage($pageId);
        var eles = [];
        var eleOrder = [];
        $(elements).each(function (i, item) {
            eles.push(item.patternId);
            eleOrder[item.patternId] = item.eorder;
        });
        var pats = g.patternFilterByElements(eles);

        pats.sort(function (a, b) {
            if (eleOrder[a.ID] < eleOrder[b.ID]) return -1;
            if (eleOrder[a.ID] > eleOrder[b.ID]) return 1;
            return 0;
        });
        return pats;
    };


    g.patternFilterByIndexId = function ($categoryId) {
        return cooConfig.allpattern.filter(function (v) {
            return v.categoryId == $categoryId && v.pTypeId == 16;
        });
    };

    g.patternFilterByType = function ($categoryId,$typeId) {
        return cooConfig.allpattern.filter(function (v) {
            return v.categoryId == $categoryId && v.pTypeId == $typeId;
        });
    };

    g.patternFilterByCategory = function ($categoryId) {
        return cooConfig.allpattern.filter(function (v) {
            return v.categoryId == $categoryId;
        });
    };


    g.userElementFilterByPage = function ($pageId) {
        return cooConfig.alluserelement.filter(function (v) {
            return v.pageId == $pageId;
        });
    };



    g.userPatternFilterByPage = function ($pageId) {
        var elements = g.userElementFilterByPage($pageId);
        var eles = [];
        var eleOrder = [];
        $(elements).each(function (i, item) {
            eles.push(item.patternId);
            eleOrder[item.patternId] = item.eorder;
        });
        var pats = g.patternFilterByElements(eles);

        pats.sort(function (a, b) {
            if (eleOrder[a.ID] < eleOrder[b.ID]) return -1;
            if (eleOrder[a.ID] > eleOrder[b.ID]) return 1;
            return 0;
        });

        return pats;
    };

    


    g.workFlowFilterByCategory = function ($categoryId) {
        return cooConfig.allworkflow.filter(function (v) {
            return v.categoryId == $categoryId;
        });
    };
   

    g.joinFilterByAB = function ($a, $b) {
        return cooConfig.alljoin.filter(function (v) {
            return v.categoryId == $a && v.joinCategoryId == $b;
        });

    };




    g.makeSource = function (pattern) {

        var source = [];
        var sls = [];
        switch (pattern.pTypeId)
        {
            case 12:
            case 19:
                source = g.statusFilterByPattern(pattern.ID);
                sls.push({ label: '请选择', value: '' });
                if (source.length > 0) {
                    var users = g.userFilterByRoleId(source[0].statusName);
                    $(users).each(function (i, item) {
                        var op = { label: item.XingMing, value: item.UserId };
                        sls.push(op);
                    });
                }
               // console.log(sls);
                break;
            case 2:
            case 13:
            case 20:
                source = g.statusFilterByPattern(pattern.ID);
                sls.push({ label: '请选择', value: '' });
                $(source).each(function (i, item) {
                    var op = { label: item.statusName, value: item.ID };
                    sls.push(op);
                });

                break;
        }

        return sls;
    };


    g.postFile = function (formData)
    {
        var dtd = $.Deferred();
        rq.post({ url: cooConfig.configObj.url + 'file/jcreate', formData: formData }, function (err, httpResponse, body) {

     //       var obj = JSON.parse('[]');
            console.log(body);
            var obj = JSON.parse(body);        
            dtd.resolve(obj);
        });
        return dtd.promise();
    }

    g.updateTemplate = function (ID,filename) {

        if (fs.existsSync('custom/'+cooConfig.configObj.companyId+'/'+filename)) {

            var formData = {
                // Pass a simple key-value pair
                key: cooConfig.configObj.uploadKey,
                ID: ID,
                // Pass data via Streams
                my_file: fs.createReadStream('custom/' + cooConfig.configObj.companyId + '/' + filename)
                // Pass multiple values /w an Array              
            };


            rq.post({ url: cooConfig.configObj.url + 'file/tcreate', formData: formData }, function (err, httpResponse, body) {
                var obj = JSON.parse(body);
                console.log(obj);
            });
        }
    };




    g.dragFile = function(id, itemId, categoryId) {   
        

        var holder = document.getElementById("__img" + id);
        holder.ondragover = function () { $("#__img" + id).addClass("draghover"); return false; };
        holder.ondragend = function () { $("#__img" + id).removeClass("draghover"); return false; };
        holder.ondrop = function (e) {
            e.preventDefault();
        
            for (var i = 0; i < e.dataTransfer.files.length; ++i) {
            
            
                var formData = {
                    // Pass a simple key-value pair
                    key: cooConfig.configObj.uploadKey,
                    itemId: itemId,
                    cateId : categoryId,   
                    // Pass data via Streams
                    my_file: fs.createReadStream(e.dataTransfer.files[i].path)
                    // Pass multiple values /w an Array              
                };           
            
            
                rq.post({ url: cooConfig.configObj.url + 'file/jcreate', formData: formData }, function (err, httpResponse, body) {               
                 
                    var obj = JSON.parse(body);
                    $("#__img" + id + " ul").html("<li tag='" + obj.ID + "'><img src='" + obj.FilePath + "' width='100px' /><span>  </span><a href='javascript:void(0);' class='del' pat='" + id + "' att='" + obj.ID + "' cat='" + categoryId + "' >删除 </a></li>")
                    $("#__c" + id).val(obj.ID);
                    $("#__c" + id).attr("v", "e");
                
                    console.log(obj);
                });
            
                console.log(e.dataTransfer.files[i].path);
            }
            return false;
        };

    }


    g.multiDragFile = function(id, itemId, categoryId) {
    
        var holder = document.getElementById("__img" + id);
        holder.ondragover = function () { $("#__img" + id).addClass("draghover"); return false; };
        holder.ondragend = function () { $("#__img" + id).removeClass("draghover"); return false; };
        holder.ondrop = function (e) {
            e.preventDefault();
        
            for (var i = 0; i < e.dataTransfer.files.length; ++i) {
            
            
                var formData = {
                    // Pass a simple key-value pair
                    key:  cooConfig.configObj.uploadKey,
                    itemId: itemId,
                    cateId: categoryId,
                    // Pass data via Streams
                    my_file: fs.createReadStream(e.dataTransfer.files[i].path)
                    // Pass multiple values /w an Array              
                };
            
            
            
                rq.post({ url: cooConfig.configObj.url + 'file/jcreate', formData: formData }, function (err, httpResponse, body) {
                
                    var objv = "<a href='" + obj.FilePath + "' >" + obj.Filename + "</a>";
                    var imgReg = /\.(bmp|jpg|jpeg|gif|png)$/ig;
                    if (imgReg.test(obj.FilePath)) {
                        objv = "<img src='" + obj.FilePath + "' width='100px' />";
                    }

                    var obj = JSON.parse(body);
                    $("#__img" + id).append("<li tag='" + obj.ID + "'>" + objv + "<br/><a href='javascript:void(0);' class='del' pat='" + id + "' att='" + obj.ID + "' cat='" + categoryId + "' >delete </a></li>")
                
                    var val = $("#__c" + id).val();
                    if (val != "") val += ",";
                    val += obj.ID;
                    $("#__c" + id).val(val);
                    $("#__c" + id).attr("v", "e");
                
                    console.log(obj);

                });
            
                console.log(e.dataTransfer.files[i].path);
            }
            return false;
        };

    }







    g.prepareVal = function (val, pattern) {

        var v = val["__c" + pattern.ID];

       if (v == null || v == 'null') v = '';

       switch (pattern.pTypeId) {
           case 6:
               v = g.dateFormat(v);
               break;
           case 1:
           case 21:
               v = v ? "是" : "";
               break;
               break;
           case 10:
               $(v).each(function (i, t) {
                   if (t.FilePath) t['RawFilePath'] = t.FilePath.replace('/100', '');
               });
               break;
           case 11:
               if (v.FilePath == undefined || v.FilePath == null || v.FilePath == '') v.FilePath = 'images/default.png';
               if (v.FilePath) {
                   v['RawFilePath'] = v.FilePath.replace('/100', '');
               }
               break;
           case 7:
               v = $sce.trustAsHtml(v);
           //    v = v.replace(/<[^>]+>/ig, '');
               break;
           case 2:
           case 13:
               var vlist = [];
               vlist.push(v);
               var plist = g.statusFilterByPatternAndId(pattern.ID, vlist);
               if (plist.length > 0) v = plist[0];
               break;
           case 19:
               stat = g.userFilterByUserIds(v);
               v = stat;
               break;
           case 20:
               if (v != 'null') {
                   var v20 = $.parseJSON('[' + v + ']');
                   v = g.statusFilterByPatternAndId(pattern.ID, v20);
               }
               break;
           default: break;
       }

       return v;

    }



    g.getPaging = function (total, current) {    

        var paging = {};

        paging.first = { txt: '前一页', n: 0 };
        paging.last = { txt: total , n: total };
        paging.next = { txt: '后一页', n: 0 };
        paging.list = [];


        if (current > 1) paging.first.n = current - 1;
    
        for (var m = 1; m < total ; m++) {

            if (total > 6)
            {
                if (m < current - 4 && m != 1) continue;
                if (m > current + 4 ) continue;
            }
            var pp = { txt: m, n: m };
            paging.list.push(pp);
        }

        if (current < total &&total!=1) paging.next.n = current + 1;
        return paging;

    };






   g.getSearchCondition = function(prefix,sElements) {

        var lsc = [];

        $(prefix+"[multiple='multiple']").each(function (i, tb) {

            var id = $(this).attr("id");
            var val = "";

            var p = g.patternFilterById(parseInt(id.substring(3)));
            var seleds = $(prefix + "#" + id + " option:selected");

            $(seleds).each(function () {
                val += "," + $(this).val();
            });


            if (seleds.length > 0) {
                var sc = {
                    patternId: p[0].ID,
                    val1: val.replace(/^,/ig, ""),
                    pTypeId: p[0].pTypeId,
                    operation: 5
                };
                lsc.push(sc);
            }
        }
        );


        var kv = [];


        var kvFilter = function ($key) {
            return kv.filter(function (v) {
                return v._Key == $key;
            });

        };

        $(prefix +  "[tag='edit']").each(function (i, tb) {

            var val = $.trim($(this).val());


            if ($(this).is(':checkbox'))
                val = $(this).is(":checked");

            if (val != "") {
                var ikv =
                    {
                        _Key: $(this).attr("id"),
                        _Value: val
                    };
                kv.push(ikv);
            }

        });



        $(sElements).each(function (i, item) {

            switch (item.pTypeId) {
                case 1:
                    $(kv).each(function (i, o) {
                        if ("__c" + item.ID == o._Key) {
                            var op = 1;
                            if (o._Value.toLowerCase() != "true") op = 4;

                            var sc = {
                                patternId: item.ID,
                                val1: o._Value,
                                pTypeId: item.pTypeId,
                                operation: op
                            };
                            lsc.push(sc);
                        }
                    });
                    break;
                case 5:
                case 7:
                    $(kv).each(function (i, o) {
                        if ("__c" + item.ID == o._Key) {
                            var sc = {
                                patternId: item.ID,
                                val1: o._Value,
                                pTypeId: item.pTypeId,
                                operation: 6
                            };
                            lsc.push(sc);
                        }
                    });

                    break;
                case 3:
                case 4:
                case 6:
                    $(kv).each(function (i, o) {

                        if ("__c" + item.ID + "x1" == o._Key) {
                            var sc = {
                                patternId: item.ID,
                                val1: o._Value,
                                pTypeId: item.pTypeId,
                                operation: 7
                            };

                            lsc.push(sc);

                        }
                        if ("__c" + item.ID + "x2" == o._Key) {
                            var sc = {
                                patternId: item.ID,
                                val1: o._Value,
                                pTypeId: item.pTypeId,
                                operation: 8
                            };
                            lsc.push(sc);
                        }
                    });
                    break;
                case 16:

                    var v16_o = kvFilter('__c' + item.ID + '_o');
                    var v16 = kvFilter('__c' + item.ID);
                    if (v16.length == 0) return;
                    var val = $.trim(v16[0]._Value);

                    var r = /\D/ig;
                    var rd = /\d+/ig;
                    if (r.test(val)) {
                        var matches = [], found;
                        while (found = rd.exec(val)) {
                            matches.push(found[0]);
                        }
                        val = matches.join(',');
                    }

                    if (v16_o.length > 0 && v16.length > 0) {
                        var sc = {
                            patternId: item.ID,
                            val1: val,
                            pTypeId: item.pTypeId,
                            operation: v16_o[0]._Value
                        };
                        lsc.push(sc);
                    }
                    //todo                  

                    break;
                case 18:
                    //    console.log(kv);

                    var v18_o = kvFilter('__c' + item.ID);
                    var v18_1 = kvFilter('__c' + item.ID + 'x1');
                    var v18_2 = kvFilter('__c' + item.ID + 'x2');

                    if (v18_o.length > 0) {
                        var val2 = "";

                        if (v18_1.length > 0 && v18_1[0]._Value > 0) {
                            val2 = v18_1[0]._Value + ',';
                        }
                        else {
                            val2 = '0,';
                        }
                        if (v18_2.length > 0 && v18_2[0]._Value >= 0) {
                            val2 = val2 + v18_2[0]._Value;
                        }


                        var sc = {
                            patternId: item.ID,
                            val2: val2,
                            pTypeId: item.pTypeId,
                            operation: 1
                        };
                        lsc.push(sc);

                    }
                    //todo
                    break;
                default: break;
            }

        });


        var backup = kvFilter('_sys_status');
        if (backup.length > 0 && backup[0]._Value) {
            var sc = {
                pTypeId: 15,
                operation: 1,
                val1: 0
            };
            lsc.push(sc);
        }




        var vorder = kvFilter('_order');
        if (vorder.length > 0 && vorder[0]._Value != "0") {



            var rorder = /__c(\d+)/ig;

            var t = rorder.exec(vorder[0]._Value);

            if (t.length > 0) {

                var valOrder = g.lscFilterByPattern(lsc, parseInt(t[1]));

                if (valOrder.length > 0) {
                    valOrder[0].orderBy = parseInt(vorder[0]._Value.charAt(vorder[0]._Value.length - 1));
                }
                else {

                    var pat = g.patternFilterById(t[1]);
                    var sc =
                    {
                        patternId: t[1],
                        orderBy: parseInt(vorder[0]._Value.charAt(vorder[0]._Value.length - 1)),
                        pTypeId: pat[0].pTypeId

                    };
                    lsc.push(sc);
                }
            }

        }


        return lsc;

   };


   g.dfnScript = function (script) {

       $(document).ready(function () {

           $('.script').replaceWith("<div class=\"script\"><script type=\"text/javascript\">"+script+"</script></div>"   );

       });
   };



   g.navInit = function () {



       $("body").on("mouseover", ".submenu", function () {
           $(this).children(".nav-content").show();
         //  $(this).children(".nav-content").addClass("block");
       });

       $("body").on("mouseleave", ".submenu", function () {
           $(this).children(".nav-content").hide();
       });

   };



   g.initButton = function () {
       

       $(function () {
           var shrinkHeader = 300
           if ($(".menu_lev3").length != 0) {
               shrinkHeader = $(".menu_lev3").offset().top;
           }           			
           $(window).scroll(function () {
               var scroll = getCurrentScroll();
               if (scroll >= shrinkHeader) {
                   $('.menu_lev3').addClass('shrink');
                   $('.menu_lev3').css("margin", "0");
               }
               else {
                   $('.menu_lev3').removeClass('shrink');
                   $('.menu_lev3').css("margin", "8px 0 0 10px");
               }
           });
           function getCurrentScroll() {
               return window.pageYOffset || document.documentElement.scrollTop;
           }
       });











       $("body").on("mouseover", ".menusel", function () {
           $(this).children(".position1").children("ul").removeClass();
           $(this).children(".position1").children("ul").addClass("clearfix typeul block");
       });

       $("body").on("mouseout", ".menusel", function () {
           $(this).children(".position1").children("ul").removeClass();
           $(this).children(".position1").children("ul").addClass("typeul");
       });
       


       $("body").on("mouseover", ".typeul > li", function () {         
               $(this).children("ul").removeClass();
               $(this).children("ul").addClass("block");         
       });

       $("body").on("mouseout", ".typeul > li", function () {
           $(this).children("ul").removeClass();        
       });
        

   };

  
   g.checkValid = function (prefix,p,indexId) {
       var v = $.trim($(prefix+' #__c' + p.ID).val());

       if (p.validator != null && p.validator != '') {

           var regStr = p.validator;
           if (regStr.indexOf('%') > -1) regStr = decodeURIComponent(regStr);
           if (regStr.indexOf('%') > -1) regStr = decodeURIComponent(regStr);

           var regx = new RegExp(regStr);
           if (!regx.test(v)) {
               $(prefix + ' #__c' + p.ID).addClass("fieldInvalid");
           }
           else {
               $(prefix + ' #__c' + p.ID).removeClass("fieldInvalid");
           }
       }

     

       if (p.required && v == '') {
           $(prefix + ' #__c' + p.ID).addClass("fieldInvalid3");
       }
       else {
           $(prefix + ' #__c' + p.ID).removeClass("fieldInvalid3");
       }
       var etor = {
           val: v,
           name: '__c' + p.ID,
           itemId: indexId
       };

       if (p.isUnique) {
           g.checkUQ(prefix, etor);
       }
   };


   g.checkUQ= function(prefix , etor)
   {
       $.when(rest.uniqueCheck(etor)).done(function (data) {
           console.log(etor);

           var rd = /\d/ig;
           if (data != '' && rd.test(data)) {
               $(prefix + ' #' + etor.name).addClass("fieldInvalid");
           }
           else {
               $(prefix + ' #' + etor.name).removeClass("fieldInvalid");
           }
       });
   }

   g.jqueryInit = function (prefix,indexId) {


       $(document).ready(function () {

           //$("body").on("blur", prefix+" [tag='edit']", function () {

           //    console.log('blur');

           //    if ($(this).attr("vad") && $(this).val() != '' && $(this).attr("vad") != 'null' && $(this).attr("vad") != '') {
           //        var regx = new RegExp(decodeURIComponent($(this).attr("vad")));
           //        if (!regx.test($.trim($(this).val()))) {
           //            $(this).addClass("fieldInvalid");
           //        }
           //        else {
           //            $(this).removeClass("fieldInvalid");
           //        }
           //    }
           //});

           //$("body").on("blur", prefix + " [unq='true']", function () {

           //    if ($(this).val() != '') {                  

           //        var etor = {
           //            val: $(this).val(),
           //            name: $(this).attr('id'),
           //            itemId: indexId
           //        };

           //        $.when(rest.uniqueCheck(etor)).done(function (data) {
           //            console.log(etor);

           //            var rd =/\d/ig;
           //            if (data != '' && rd.test(data) ) {
           //                $(prefix +' #' + etor.name).addClass("fieldInvalid");                               
           //            }
           //            else
           //            {                        
           //                $(prefix + ' #' + etor.name).removeClass("fieldInvalid");
           //            }
           //        });
           //    }
           //});


           //$("body").on("blur", prefix + " [req='true']", function () {
           //    if ($(this).val() == '') {
           //        $(this).addClass("fieldInvalid3");
           //    }
           //    else {
           //        $(this).removeClass("fieldInvalid3");
           //    }
           //});


           $("body").on("click","#sub .remove", function () {              
               var di = $(this).parent('td').parent('tr');
               var p=  di.find('.index').val();
               if (p != undefined && p != '')
               {
                   var ex = $('#rowdel').val();
                   ex += ',' + p;
                   $('#rowdel').val(ex);
               }
               var rows = parseInt($("#rowcount").val());               
               rows = rows - 1;
               $("#rowcount").val(rows);
               di.remove();
           });



           $("body").on('click', '.del', function () {

               var attId = $(this).attr('att');
               var cateId = $(this).attr('cat');
               var pat = $(this).attr('pat');

               $.when(rest.delFile(parseInt(cateId), parseInt(attId))).done(function () {
                   $('li[tag="' + attId + '"]').remove();
                   $('#__c' + pat).val('');
               });
           });



           $(document).on('change', "[tag='edit']", function () {
               $(this).attr("v", "e");
           });





       });





   };

   g.disable = function (prefix) {
       $(prefix + ' #submitEdit').css('display', 'none').css('background-color', '#cccccc');
       $(prefix).css('background-color', '#cccccc');
       //$(prefix + " input").prop('disabled', true).css('background-color','#cccccc');
       //$(prefix + " select").prop('disabled', true).css('background-color', '#cccccc');
       //$(prefix + " .jqtxt").prop('disabled', true).css('background-color', '#cccccc');
   };


   g.importInit = function () {


       $(document).on('click', "#importb div[contenteditable='true']", function () {
           $(this).css("background-color", "#cc9933");
       });


       $(document).on('click', "#importb tr td", function () {
           var a = $(this).find("div").eq(0).html();
           if ($.trim(a) == "") {
               $(this).find("div").html("&nbsp; ");
           }
       });

       $(document).on('click', ".btn_01 .remove", function () {

           $('[name="mainCheckBox"]:checked').each(function () {

               $(this).parent('td').parent('tr').remove();

           });
       });


       $(document).on('mouseout', "#importb  div[contenteditable='true']", function () {
           var a = $.trim($(this).html());
           if (a == "") {
               $(this).html("");
           }
           else {
               var id = $(this).parent("td").index() + 1;

               var vad = decodeURIComponent($("#importb tr th:nth-child(" + id + ")").attr("vad"));
               var regx = new RegExp(vad);

               if (vad != "" && vad != "null") {
                   if (!regx.test(a)) {
                       $(this).parent("td").css("background-color", "red");
                   }
                   else {
                       $(this).parent("td").css("background-color", " #e8edff");
                   }
               }
           }
           $(this).css("background-color", "#e8edff");
       });

   };



   g.resetUserInput = function (prefix) {

       $(prefix+'[v="e"]').each(function (i, item) {
           $(this).val('');
           $(this).attr('v', '');
           if ($(this).is("div"))
               $(this).html('');

           if ($(this).is("select"))
               $(this).val($("#"+$(this).attr('id')+" option:first").val());

           if ($(this).is(':checkbox'))
               $(this).prop("checked", false);

       });

       $(prefix +".jqtxt").each(function (i) {
           $(this).jqteVal('');
       });

       $(prefix +"[multiple='multiple']").each(function (i) {
       
           $(this).find("option:selected").prop("selected", false)
           $(this).multiselect('refresh');
       });

       $(prefix + ' .holder ul li').remove();


   };























    return g;

});

CooWorkApp.factory('userSetting', function (locdbServices,cooConfig, g) {

    var us = {};




    us.pageConfig = function (sElements, tag, pageId) {

        var dtd = $.Deferred();

        var checkboxPrefix = '__' + tag;
        var checkboxClass = tag + 'c';

        // openDatabase();

        var sElementsStr = ',';
        $(sElements).each(function (i, o) {
            sElementsStr += o.ID + ',';
        });


        var removeIds = [];
        var addIds = [];

        $(sElements).each(function (i, item) {
            if (!$("#" + checkboxPrefix + item.ID).is(':checked')) {
                removeIds.push(item.ID);
            }
        });


    //    console.log(sElementsStr);

        $("." + checkboxClass + ":checked").each(function (i, item) {
            var cid = "," + $(this).attr("id").replace(/\D/ig, "") + ",";
            if (sElementsStr.indexOf(cid) == -1) {
                addIds.push(parseInt($(this).attr("id").toString().replace(/\D/ig, "")));
            }
        });


        if (addIds.length > 0 && removeIds.length > 0) {
            var addElement = g.elementFilterByPagePattern(pageId, addIds);
            $.when(locdbServices.pushTable(cooConfig.USERELEMENTTABLENAME, addElement), locdbServices.bulkDeleteByPatternId(cooConfig.USERELEMENTTABLENAME, removeIds, pageId)).done(function () {

                $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                    cooConfig.alluserelement = result;
                    dtd.resolve(true);
                });
            });
        }
        else {
            if (addIds.length > 0) {

                var addElement = g.elementFilterByPagePattern(pageId, addIds);
                $.when(locdbServices.pushTable(cooConfig.USERELEMENTTABLENAME, addElement)).done(function () {

                    $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                        cooConfig.alluserelement = result;
                        dtd.resolve(true);
                    });
                });
            } else if (removeIds.length > 0) {



                $.when(locdbServices.bulkDeleteByPatternId(cooConfig.USERELEMENTTABLENAME, removeIds, pageId)).done(function () {

                    console.log(removeIds);

                    $.when(locdbServices.fetchAllUserElements()).done(function (result) {                      
                        cooConfig.alluserelement = result;
                        dtd.resolve(true);
                    });
                });
            }
            else
            {
                dtd.resolve(false);
            }
        }

        return dtd.promise();


    }












    us.getSettingElementByPage = function ($pageId) {

        var dtd = $.Deferred();

      //  var pats = g.patternFilterByPage($pageId);
        var userPats = g.userPatternFilterByPage($pageId);

        if (userPats.length==0)
        {
            var pats = g.patternFilterByPage($pageId);
            var eles = g.elementFilterByPage($pageId);
            
            $.when(locdbServices.pushTable(cooConfig.USERELEMENTTABLENAME, eles)).done(function () {

                $.when(locdbServices.fetchAllUserElements()).done(function (result) {

                    cooConfig.alluserelement = result;
                    dtd.resolve(pats);
                });     

            });
        }
        else
        {
            dtd.resolve(userPats);
        }
        return dtd.promise();   
    }; 







    return us;
});