CooWorkApp.controller('centerController', function ($rootScope,$scope, $location, $sce, locdbServices, cooConfig, g) {

    var fs = require('fs');

    $rootScope.title = '北极光v1.03 - 首页';

   
    var html = '';

    console.log(cooConfig.configObj.isLogin+' - login');


    $.when(locdbServices.start()).done(function (isAuto) {

        if (isAuto) {
 
            if (fs.existsSync('custom/'+cooConfig.configObj.companyId+'/center.html'))
            {
                $scope.centerSrc = 'custom/' + cooConfig.configObj.companyId + '/center.html';
            }
            else
            {
                $scope.centerSrc = 'custom/center.html';
            }



            $scope.$$phase || $scope.$apply();
        }
        else {
 
    
            cooConfig.configObj.isLogin = false;
            cooConfig.configObj.isStart = false;
            window.location.href = location.protocol + '//' + location.host + location.pathname + '#/login';
        }

    });

  
    //g.pageFilterByCategory


});



CooWorkApp.controller('dialogController', function ($rootScope,$scope, $location, $routeParams, $sce, locdbServices, userSetting, cooConfig, g, rest,ngDialog) {

    $scope.closeSome = function (id) {

        console.log(id);

        ngDialog.close(id.id);
    };
    

});





CooWorkApp.controller('listController', function ($rootScope,$scope, $location, $routeParams, $sce, locdbServices, userSetting, cooConfig, g, rest, _ ,ngDialog) {
    
    var openAlert = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/alert.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };
       
    var openConfirm = function (msg) {
        $scope.message = msg;
        $scope.cDlgId = ngDialog.open({
            template: 'tmpl/confirm.html',
            className: 'ngdialog-theme-default-dialog',
            controller: 'dialogController',
            overlay: false,
            scope: $scope
        });
    };

    




    Date.firstDayOfWeek = 0;
    Date.format = 'yyyy-mm-dd';

    var fs = require('fs');
  

    var categoryId = $routeParams.categoryId;
    var pageId = $routeParams.pageId;

    var currentPage = g.pageFilterById(pageId)[0];
    $rootScope.title = currentPage.UIname + ' - 列表';



    var p11 = g.pageFilter(11, pageId);
    var p14 = g.pageFilter(14, pageId);

    var rec = [];
    $scope.sElements = [];
    $scope.vElements = [];
    var lsc = [];
    var stat = [];

    $scope.searchConfigElements = [];
    $scope.listConfigElements = [];

    //menu
    $scope.workfls = [];
    $scope.editpages = [];
    $scope.stateditpages = [];
    $scope.bulkcreatepages = [];
    $scope.exportpages = [];
    $scope.isadmin = cooConfig.configObj.isAdmin;
    $scope.viewdetailpages = [];
    //menu


    var osElements = g.patternFilterByPage(p11[0].ID);
    var ovElements = g.patternFilterByPage(p14[0].ID);

    var indexPattern = g.patternFilterByIndexId(categoryId);
  
   
    $scope.s = '2';
    $scope.vdata = [];
    $scope.paging = {};
    $scope.startIndex = 1;
    $scope.pageSize = 15; 


    $scope.pages = [{ ID: 6, Title: '6' }, { ID: 10, Title: '10' }, { ID: 15, Title: '15' }, { ID: 20, Title: '20' }, { ID: 30, Title: '30' }, { ID: 100, Title: '100' } ];






    var renderList = function () {

        $.when(rest.search(categoryId, pageId, lsc, $scope.startIndex, $scope.pageSize)).done(function (result) {
      
            //todo server
            var r = /pageNumber\((\d+)\)/ig;
            var matches = [], found;
            while (found = r.exec(result.p)) {
                matches.push(parseInt(found[1]));
            }
            var total = 1;
            if (matches.length>0) total = Math.max.apply(Math, matches);
            //todo
          
            $scope.paging = g.getPaging(total, $scope.startIndex);
          //  console.log(result.data);

            if (result.s != undefined) $scope.s = result.s.replace(/<[^>]+>/ig, '');

            $scope.s = $scope.s.replace(/(\.\d\d)(\d+)/ig, '$1');

            var pIndex = g.patternFilterByIndexId(categoryId);
            var vdata = [];
            $(result.data).each(function (j, val) {

                var row = [];
                for (var k = 0; k < rec.length; k++) {

                    var v = g.prepareVal(val, rec[k]);

                    var ctor = { ID: rec[k].ID, pTypeId: rec[k].pTypeId, val: v };

                    row.push(ctor);
                    row['index'] = val['__c' + pIndex[0].ID];
                    row['depth'] = val.depth;
                };

                vdata.push(row);

            });
            $scope.vdata = vdata;

            var qlink = '<div class="qlink"></div>';  //todo
            //if (p2.length > 0) {
            //    qlink += '<div><a title="' + p2[0].UIname + '" onclick="editPopi(' + categoryId + ',' + p2[0].ID + ',' + val['__c' + pIndex[0].ID] + ')">' + p2[0].UIname.substring(0, 2) + '</a></div>';
            //}
            //if (p8.length > 0) {
            //    qlink += '<div><li><a title="' + p8[0].UIname + '" onclick="pviewPopi(' + categoryId + ',' + p8[0].ID + ',' + val['__c' + pIndex[0].ID] + ')">' + p8[0].UIname.substring(0, 2) + '</a></div>';
            //}
            //qlink += '</div>';

            $scope.$apply();


        });
    };


    var getChecked = function () {
        var checkboxes = document.getElementsByName("mainCheckBox");
        var vals = "";
        for (var i = 0, n = checkboxes.length; i < n; i++) {
            if (checkboxes[i].checked)
                vals += "," + checkboxes[i].id.replace("checkbox_", "");
        }
        vals = vals.length > 0 ? vals.substring(1) : "";
        return vals;
    }
   



    $.when(userSetting.getSettingElementByPage(p11[0].ID), userSetting.getSettingElementByPage(p14[0].ID)).done(function (a, b) {

 

        $scope.sElements = a;
        $scope.vElements = b;
        

        //config
        var eleStr = ',';
        $($scope.sElements).each(function (i,item) {
            eleStr += item.ID +',';
        });

        var veleStr = ',';
        $($scope.vElements).each(function (i, item) {
            veleStr += item.ID + ',';
        });


        $(ovElements).each(function (i, o) {
            if (veleStr.indexOf(',' + o.ID.toString() + ',') > -1)
            {
                $scope.listConfigElements.push({item:o,select:true});
            }
            else
            {
                $scope.listConfigElements.push({ item: o, select: false });              
            }
        });     

        
        $(osElements).each(function (j, obj) {

            if (obj.pTypeId != 10 && obj.pTypeId != 11) {

                if (eleStr.indexOf(',' + obj.ID.toString() + ',') > -1) {
                    $scope.searchConfigElements.push({ item: obj, select: true });
                }
                else {
                    $scope.searchConfigElements.push({ item: obj, select: false });
                }
            }
        });
        //config;




        //menu
        var workfls = g.workFlowFilterByCategory(categoryId);

    

        var p9 = g.pageFilterByCategoryType(categoryId, 9);
        var pattern13 = g.patternFilterByType(categoryId, 13);
              
        g.initButton();
        if (workfls.length > 0 && p9.length > 0 && pattern13.length>0) {
            var ids = [];
            $(workfls).each(function (k, w) {
                ids.push(w.tagId2);
            });      
            $scope.workfls = g.statusFilterByIds(ids, pattern13[0].ID);            
        }

            


        var p2 = g.pageFilterByCategoryType(categoryId, 2);
        var p100 = g.pageFilterByCategoryType(categoryId, 100);
        $(p2).each(function (i, o) {
             $scope.editpages.push(o);
        });

        $(p100).each(function (i, o) {
            $scope.editpages.push(o);
        });

     
        var p3 = g.pageFilterByCategoryType(categoryId, 3);
        $(p3).each(function (i, p) {      

            var ele = g.elementFilterByPage(p.ID);
            if (ele.length>0)
            {
                var stat=[];
                var ppp= _.find(cooConfig.allpattern,function(p){ return p.ID==ele[0].patternId});
                if (ppp.pTypeId == 2 ||ppp.pTypeId==20)
                {
                     stat = g.statusFilterByPattern(ele[0].patternId);
                }
                else if (ppp.pTypeId==12||ppp.pTypeId==19)
                {
                    var srole = _.find(cooConfig.allstatus, function (s) { return s.patternId == ele[0].patternId && s.categoryId == categoryId });
                    var susers = _.filter(cooConfig.alluser, function (u) { return u.RoleIds.toLowerCase().indexOf(srole.statusName.toLowerCase()) > -1; });

                    $(susers).each(function (i,u) {
                        stat.push({ ID: u.UserId, statusName: u.XingMing });
                    });                    

                }

                

               
                $scope.stateditpages.push({ page: p, source: stat });
            }
        });


        $scope.joinpages = [];

        var anyj = _.filter(cooConfig.alljoin, function (j) { return j.categoryId==categoryId && (j.nRelation ==1 || j.nRelation==2) });

        if (anyj.length > 0)
        {
            var allc =[];

            $(anyj).each(function (i, o) {
                var subj = _.filter(cooConfig.alljoin, function (j) { return j.categoryId == o.joinCategoryId && (j.nRelation == 1 || j.nRelation == 3) &&j.joinCategoryId==categoryId });
                if (subj.length > 0) allc.push(o.joinCategoryId);
            });


         //   var allc = _.pluck(anyj, 'joinCategoryId');           
            
            $scope.joinpages = _.filter(cooConfig.allpage, function (p) { return _.contains(allc, p.categoryId) && p.pageType == 15; });

        }


        


        $scope.createpages = g.pageFilterByCategoryType(categoryId, 15);
        $scope.hasParentPage = _.filter(cooConfig.allpattern, function (p) { return p.categoryId==categoryId&&p.pTypeId==18; });

        $scope.bulkcreatepages = g.pageFilterByCategoryType(categoryId, 5);
         
        $scope.exportpages = g.pageFilterByCategoryType(categoryId, 7);
        
        $scope.viewdetailpages = g.pageFilterByCategoryType(categoryId, 8);

        $scope.viewdetailpages = _.union($scope.viewdetailpages, g.pageFilterByCategoryType(categoryId, 101));
        //menu

        var iSearchConditions = 0;
        var stat = [];       

    
       
        var r = 0;
        for (; r < $scope.vElements.length; r++) {
            if (r >= cooConfig.maxListColumns) break;
            rec.push($scope.vElements[r]);
        }

     //   $scope.vElements = rec;     
        $scope.pageId = pageId;

        renderList();


        $scope.dosearch = function () {
            lsc = g.getSearchCondition('',$scope.sElements);
            $scope.startIndex = 0;
            renderList();                          
        };

        $scope.pageSizeChange = function (p) {           
            $scope.startIndex = 0;
            renderList();
        };


        $scope.searchClear = function () {         

        
          //   openAlert('ok!');
            window.location.href = window.location.href + '/';

        };
           

        $scope.clearListConfig = function () {
         
            $('.ovc').prop('checked', false);

        };




        $scope.dosm = function () {
            $('#saomadiv').show();
        };

        $scope.saomacancel = function () {
            $('#saomadiv').hide();
        };

        $scope.saomasubmit = function () {
            var val = $("#idlist").val();
            var r = /[0-9]+/g;
            var matches = [], found;
            while (found = r.exec(val)) {
                matches.push(found[0]);
            }

           var tt = matches.toString();
            if (tt == "") tt = "0";
            

            $('#__c' + indexPattern[0].ID).val(tt);
            $('#__c' + indexPattern[0].ID+'_o').val(5);

            lsc = g.getSearchCondition('',$scope.sElements);
            $scope.startIndex = 0;
            renderList();

            $("#saomadiv").hide();
        };



        $scope.pageNumber = function (i) {        
            $scope.startIndex = i;
            renderList();
        };


        $scope.closeConfirm =function(id,flag)
        {
            ngDialog.close(id);
            if (flag)
            {
                var vals = getChecked();
                if (vals == "") return openAlert('未选中！');

                var etor = {
                    ids: vals,
                    categoryId: categoryId
                };

                $.when(rest.adminDel(etor)).done(function (f) {
                    if (f) { renderList(); } else { openAlert('删除失败！'); };
                });
            }
        }


        $scope.adminDel = function (h) {

            openConfirm("确认删除?");
                   
        };

        $scope.fakeDel = function (h) {       
            var vals = getChecked();
            if (vals == "") return openAlert('未选中！');

            var etor = {
                ids: vals,
                categoryId: categoryId,
                del: h
            };

            $.when(rest.fakeDel(etor)).done(function (f) {
                if (f) { renderList(); } else { openAlert('删除失败！'); };
            });
        };




        $scope.updateWorkFlow = function (statusId) {
            var vals = getChecked();
            if (vals == '') 
            {
                return openAlert('未选中！'); 
            };

            var p9 = g.pageFilterByCategoryType(categoryId, 9);
            var etor = {
                ids: vals,
                cateId: categoryId,
                listPageId: pageId,
                pageId: p9[0].ID,
                statusId: statusId
            };
            $.when(rest.updateWorkFlow(etor)).done(function (f) {
                if (f) { renderList(); } else { openAlert('权限未开或更新失败！'); };
            });
            
        };


        $scope.selectAll = function () {
            if ($("#selectAll").prop("checked") != true) {
                $(".ctltable tr td").find('input[type=checkbox]').prop("checked", false);
            } else {
                $(".ctltable tr td").find('input[type=checkbox]').prop("checked", true);
            }
        };


        $scope.createPop = function (pid) {

            var vals = getChecked();
            if (vals == '') {
                return openAlert('未选中！');
            };
            var itemId = vals.split(',')[0];

            $scope.createPageId = pid;
            $scope.itemId = itemId;
            $scope.categoryId = categoryId;


            var url = 'tmpl/create';
            var ctlor = 'subCreateController';

            if (fs.existsSync('custom/' + cooConfig.configObj.companyId + '/create_' + pid + '.html')) {
                url = 'custom/' + cooConfig.configObj.companyId + '/create_' + pid + '';
                ctlor = 'subCreate_' + pid + '_Controller';
            }


            ngDialog.open({
                template: url.toString()+'.html',
                controller: ctlor,
                scope: $scope
            });

        };


        $scope.createPop2 = function (indexId) {

            if ($scope.createpages.length > 0) {
                
                    var pid = $scope.createpages[0].ID;

                    $scope.createPageId = $scope.createpages[0].ID;
                    $scope.itemId = indexId;
                    $scope.categoryId = categoryId;


                    var url = 'tmpl/create';
                    var ctlor = 'subCreateController';

                    if (fs.existsSync('custom/' + cooConfig.configObj.companyId + '/create_' + pid + '.html')) {
                        url = 'custom/' + cooConfig.configObj.companyId + '/create_' + pid + '';
                        ctlor = 'subCreate_' + pid + '_Controller';
                    }


                    ngDialog.open({
                        template: url.toString()+'.html',
                        controller: ctlor,
                        scope: $scope
                    });
                }
        };










        $scope.joinPop = function (pid) {

            var vals = getChecked();
            if (vals == '') {
                return openAlert('未选中！');
            };
            var itemId = vals.split(',')[0];

            $scope.joinPageId = pid;
            $scope.itemId = itemId;
            $scope.categoryId = categoryId;


            var url = 'tmpl/create';
            var ctlor = 'joinCreateController';


            var fe = fs.existsSync('custom/' + cooConfig.configObj.companyId + '/create_' + pid + '.html');
            if (fe) {
                url = 'custom/' + cooConfig.configObj.companyId + '/create_' + pid + '';
                ctlor = 'joinCreate_' + pid + '_Controller';
            }


            ngDialog.open({
                template: url + '.html', 
                controller: ctlor,
                scope: $scope
            });

        };

        $scope.joinPop2 = function (indexId) {
    
            if ($scope.joinpages.length > 0) {

                var pid = $scope.joinpages[0].ID;
                $scope.joinPageId = pid;
                $scope.itemId = indexId;
                $scope.categoryId = categoryId;

                var url = 'tmpl/create';
                var ctlor = 'joinCreateController';


                var fe = fs.existsSync('custom/' + cooConfig.configObj.companyId + '/create_' + pid + '.html');
                if (fe) {
                    url = 'custom/' + cooConfig.configObj.companyId + '/create_' + pid + '';
                    ctlor = 'joinCreate_' + pid + '_Controller';
                }

                ngDialog.open({
                    template: url + '.html',
                    controller: ctlor,
                    scope: $scope
                });
            }

        };




        $scope.editPop2 = function (indexId) {

            if ($scope.editpages.length > 0) {
                $scope.editPageId = $scope.editpages[0].ID;
                $scope.itemId = indexId;
                $scope.categoryId = categoryId;
                
                var url = 'tmpl/edit';
                var ctlor = 'editController';

                if (fs.existsSync('custom/' + cooConfig.configObj.companyId + '/edit_' + $scope.editPageId + '.html')) {
                    url = 'custom/' + cooConfig.configObj.companyId + '/edit_' + $scope.editPageId + '';
                    ctlor = 'edit_' + $scope.editPageId + '_Controller';
                }

                ngDialog.open({
                    template: url.toString()+'.html',
                    controller: ctlor,
                    scope: $scope
                });
            }
        };



        //todo
        $scope.editPop = function (pid) {
            var vals = getChecked();
            if (vals == '') {
                return openAlert('未选中！');        
            };
            var itemId = vals.split(',')[0];
           
            $scope.editPageId = pid;
            $scope.itemId = itemId;
            $scope.categoryId = categoryId;


            var url = 'tmpl/edit';
            var ctlor = 'editController';

            if (fs.existsSync('custom/' + cooConfig.configObj.companyId + '/edit_' + pid + '.html')) {
                url = 'custom/' + cooConfig.configObj.companyId + '/edit_' + pid + '';
                ctlor = 'edit_' + pid + '_Controller';
            }


            ngDialog.open({
                template: url.toString()+'.html',
                controller: ctlor,
                scope:$scope
            });  
 
        };


        $scope.complexEdit = function (pid) {
            var vals = getChecked();
            if (vals == '') return openAlert('未选中！');
            var itemId = vals.split(',')[0];

            $scope.editPageId = pid;
            $scope.itemId = itemId;
            $scope.categoryId = categoryId;


            ngDialog.open({
                template: 'tmpl/complexedit.html',
                controller: 'complexeditController',
                scope: $scope
            });



        };




        $scope.closeDialog = function () {

            ngDialog.closeAll();
        };



        $scope.pviewPop2 = function (indexId) {
          
            if ($scope.viewdetailpages.length > 0) {

                var pid = $scope.viewdetailpages[0].ID;

                $scope.viewPageId = pid;
                $scope.itemId = indexId;
                $scope.categoryId = categoryId;


                var cpage = _.find(cooConfig.allpage, function (p) { return p.ID == $scope.viewdetailpages[0].ID });

                if (cpage != null && cpage.pageType == 8) {
                    ngDialog.open({
                        template: 'tmpl/view.html?pageId=' + pid,
                        controller: 'viewController',
                        scope: $scope
                    });
                }


                if (cpage != null && cpage.pageType == 101) {
                    ngDialog.open({
                        template: 'tmpl/complexview.html?pageId=' + pid,
                        controller: 'complexviewController',
                        scope: $scope
                    });
                }
            }
        };




        
        $scope.pviewPop = function (pid) {

            var cpage = _.find(cooConfig.allpage, function (p) { return  p.ID == pid });
                      

            var vals = getChecked();
            if (vals == '') return openAlert('未选中！');
            var itemId = vals.split(',')[0];

            $scope.viewPageId = pid;
            $scope.itemId = itemId;
            $scope.categoryId = categoryId;

            if (cpage != null && cpage.pageType == 8) {
                ngDialog.open({
                    template: 'tmpl/view.html?pageId=' + pid,
                    controller: 'viewController',
                    scope: $scope
                });
            }


            if (cpage != null && cpage.pageType == 101) {
                ngDialog.open({
                    template: 'tmpl/complexview.html?pageId=' + pid,
                    controller: 'complexviewController',
                    scope: $scope
                });
            }



        };

        $scope.datalogPop = function () {
            var vals = getChecked();
            if (vals == '') return openAlert('未选中！');
            var itemId = vals.split(',')[0];
            $scope.categoryId = categoryId;
            $scope.itemId = itemId;


            ngDialog.open({
                template: 'tmpl/datalog.html',
                controller: 'datalogController',
                scope: $scope
            });

        };


        $scope.export = function (pid) {

            $scope.listPageId = pageId;
            $scope.exportPageId = pid;   
            $scope.categoryId = categoryId;
            $scope.lsc = lsc;

            ngDialog.open({
                template: 'tmpl/export.html',
                controller: 'exportController',
                scope: $scope
            });
        };




        $scope.workflowlogPop = function () {
            var vals = getChecked();
            if (vals == '') return openAlert('未选中！');
            var itemId = vals.split(',')[0];
            $scope.categoryId = categoryId;
            $scope.itemId = itemId;

            ngDialog.open({
                template: 'tmpl/workflowlog.html',
                controller: 'workflowlogController',
                scope: $scope
            });
        };

        $scope.updateStatus = function (pid, sid) {

            var vals = getChecked();
            if (vals == '') return openAlert('未选中！');

            var ele = g.elementFilterByPage(pid);

            var etor = {
                ids: vals,
                cateId: categoryId,
                listPageId: pageId,
                pageId: pid,
                patternId: ele[0].patternId,
                statusId: sid
            };
      
            $.when(rest.updateStatus(etor)).done(function (f) {
                if (f) { renderList(); } else { openAlert('更新失败！'); };
            });       

        };


        $scope.bulkCreate = function (pid) {
  
            $scope.importPageId = pid;
            $scope.categoryId = categoryId;        

            ngDialog.open({
                template: 'tmpl/import.html',
                controller: 'importController',
                className: 'ngdialog-theme-plain',
                scope: $scope
            });
        };


        $scope.searchConfig = function () {
            if (!$("#searchConfig").is(":visible")) {
                $("#searchConfig").show();
            } else {
                $("#searchConfig").hide();

                $.when(userSetting.pageConfig($scope.sElements, 'os', p11[0].ID)).done(function (f) {
                    if (f) {

                        $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                            cooConfig.alluserelement = result;      
                            console.log('redirect');
                            $location.path('/list/' + categoryId + '/page/' + pageId + '/');
                            $scope.$apply();
                        });                  
                    }
                });
            }
        };

        $scope.viewConfig = function () {
            if (!$("#viewConfig").is(":visible")) {
                $("#viewConfig").show();
            } else {
                $("#viewConfig").hide();

                $.when(userSetting.pageConfig($scope.vElements, 'ov', p14[0].ID)).done(function (f) {
                    if (f) {

                        $.when(locdbServices.fetchAllUserElements()).done(function (result) {
                            cooConfig.alluserelement = result;
                            console.log('redirect');
                            $location.path('/list/' + categoryId + '/page/' + pageId + '/');
                            $scope.$apply();

                        });
                    }
                });
            }
        };

    });
   
});

















CooWorkApp.controller("movieStubController", function ($scope, $location, cooConfig) {



    if (cooConfig.isLogin) {
        $scope.headerSrc = "tmpl/header.html";
    }

    //$scope.movies = movieStubFactory.query(); 

    //$scope.currMovie = null;

    //$scope.getMovieById = function (id) {
    //    var movies = $scope.movies;
    //    for (var i = 0; i < movies.length; i++) {
    //        var movie = $scope.movies[i];
    //        if (movie.id == id) {
    //            $scope.currMovie = movie;
    //        }
    //    }
    //};

    //$scope.back = function () {
    //    window.history.back();
    //};

    //$scope.getCount = function (n) {
    //    return new Array(n);
    //}

    //$scope.isActive = function (route) {
    //    return route === $location.path();
    //}

    //$scope.isActivePath = function (route) {
    //    return ($location.path()).indexOf(route) >= 0;
    //}

});

CooWorkApp.controller("movieDetailsController", function ($scope, $routeParams) {
    $scope.getMovieById($routeParams.id);
});
CooWorkApp.controller("bookTicketsController", function ($scope, $http, $location, $routeParams) {
    $scope.getMovieById($routeParams.id);
    $scope.onlyNumbers = /^\d+$/;
    $scope.formData = {};
    $scope.formData.movie_id = $scope.currMovie.id;
    $scope.formData.movie_name = $scope.currMovie.name;
    $scope.formData.date = "Today"

    $scope.processForm = function () {
        console.log($scope.formData);
        $http({
            method: 'POST',
            url: 'http://moviestub.cloudno.de/book',
            data: $.param($scope.formData), // pass in data as strings
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            } // set the headers so angular passing info as form data (not request payload)
        })
            .success(function (data) {
                $location.path("/bookings");
            });
    };
});
CooWorkApp.controller("bookingDetailsController", function ($scope, movieStubBookingsFactory) {
    $scope.bookings = movieStubBookingsFactory.query();
});








CooWorkApp.controller('selectController', function ($scope, $location, $routeParams, $sce, locdbServices, userSetting, cooConfig, g, rest) {

    Date.firstDayOfWeek = 0;
    Date.format = 'yyyy-mm-dd';



    var categoryId = $scope.element.categoryId;

    var join = g.joinFilterByAB($scope.categoryId, $scope.element.categoryId);
    $scope.joinPatternId = join[0].joinPatternId;

    var pageId = g.pageFilterByCategoryType(categoryId, 10)[0].ID;

    var p11 = g.pageFilter(11, pageId);
    var p14 = g.pageFilter(14, pageId);

    var rec = [];
    $scope.sElements = [];
    $scope.vElements = [];
    var lsc = [];
    var stat = [];
    
    var indexPattern = g.patternFilterByIndexId(categoryId);
    
    $scope.s = '2';
    $scope.vdata = [];
    $scope.paging = {};
    $scope.startIndex = 1;
    $scope.pageSize = 15;


    $scope.pages = [{ ID: 6, Title: '6' }, { ID: 10, Title: '10' }, { ID: 15, Title: '15' }, { ID: 20, Title: '20' }, { ID: 30, Title: '30' }, { ID: 100, Title: '100' }];



    var renderList = function () {

        $.when(rest.search(categoryId, pageId, lsc, $scope.startIndex, $scope.pageSize)).done(function (result) {

            //todo server
            var r = /pageNumber\((\d+)\)/ig;
            var matches = [], found;
            while (found = r.exec(result.p)) {
                matches.push(parseInt(found[1]));
            }
            var total = 1;
            if (matches.length > 0) total = Math.max.apply(Math, matches);
            //todo

            $scope.paging = g.getPaging(total, $scope.startIndex);

            $scope.s = result.s.replace(/<[^>]+>/ig, '');           
   
            var pIndex = g.patternFilterByIndexId(categoryId);
            var vdata = [];
            $(result.data).each(function (j, val) {

                var row = [];
                for (var k = 0; k < rec.length; k++) {

                    var v = g.prepareVal(val, rec[k]);

                    var ctor = { ID: rec[k].ID, pTypeId: rec[k].pTypeId, val: v };

                    row.push(ctor);
                    row['index'] = val['__c' + pIndex[0].ID];
                    row['depth'] = val.depth;
                    if ($scope.joinPatternId>0)
                    {
                        row['joinName'] = val['__c' + $scope.joinPatternId ];
                    }
                };

                vdata.push(row);

            });
            $scope.vdata = vdata;

            var qlink = '<div class="qlink"></div>';  //todo
            //if (p2.length > 0) {
            //    qlink += '<div><a title="' + p2[0].UIname + '" onclick="editPopi(' + categoryId + ',' + p2[0].ID + ',' + val['__c' + pIndex[0].ID] + ')">' + p2[0].UIname.substring(0, 2) + '</a></div>';
            //}
            //if (p8.length > 0) {
            //    qlink += '<div><li><a title="' + p8[0].UIname + '" onclick="pviewPopi(' + categoryId + ',' + p8[0].ID + ',' + val['__c' + pIndex[0].ID] + ')">' + p8[0].UIname.substring(0, 2) + '</a></div>';
            //}
            //qlink += '</div>';

            $scope.$apply();


        });
    };


    var getChecked = function () {
        var checkboxes = document.getElementsByName("mainCheckBox");
        var vals = "";
        for (var i = 0, n = checkboxes.length; i < n; i++) {
            if (checkboxes[i].checked)
                vals += "," + checkboxes[i].id.replace("checkbox_", "");
        }
        vals = vals.length > 0 ? vals.substring(1) : "";
        return vals;
    }




    $.when(userSetting.getSettingElementByPage(p11[0].ID), userSetting.getSettingElementByPage(p14[0].ID)).done(function (a, b) {


        $(a).each(function (i,o) {
            if (o.pTypeId!=10 && o.pTypeId!=11)
            {
                $scope.sElements.push(o);
            }
        });
        

        //$scope.sElements = a;
        $scope.vElements = b;
        

        var iSearchConditions = 0;
        var stat = [];

    

        var r = 0;
        for (; r < $scope.vElements.length; r++) {
            if (r > 15) break;
            rec.push($scope.vElements[r]);
        }

        //   $scope.vElements = rec;       
        renderList();


        $scope.dosearch = function () {
            lsc = g.getSearchCondition('', $scope.sElements);
            $scope.startIndex = 0;
            renderList();
        };

        $scope.pageSizeChange = function (p) {
            $scope.startIndex = 0;
            renderList();
        };


        $scope.dosm = function () {
            $('#saomadiv').show();
        };

        $scope.saomacancel = function () {
            $('#saomadiv').hide();
        };

        $scope.saomasubmit = function () {
            var val = $("#idlist").val();
            var r = /[0-9]+/g;
            var matches = [], found;
            while (found = r.exec(val)) {
                matches.push(found[0]);
            }

            var tt = matches.toString();
            if (tt == "") tt = "0";


            $('#__c' + indexPattern[0].ID).val(tt);
            $('#__c' + indexPattern[0].ID + '_o').val(5);

            lsc = g.getSearchCondition('', $scope.sElements);
            $scope.startIndex = 0;
            renderList();

            $("#saomadiv").hide();
        };


    



        $scope.pageNumber = function (i) {
            $scope.startIndex = i;
            renderList();
        };
        


        $scope.selectAll = function () {
            if ($("#selectAll").prop("checked") != true) {
                $(".ctltable tr td").find('input[type=checkbox]').prop("checked", false);
            } else {
                $(".ctltable tr td").find('input[type=checkbox]').prop("checked", true);
            }
        };





    });

});




















