/**
 * @author 老阴
 */
$(function(){



    /*********全局变量***********/
    var url;
    
    (function(){
        var url;
        InitUrl = function(i){
            if (i) {
                url = i;
            }
            return {
                Get: get,
                Set: set
            };
        }
        function get(){
            return url;
        };
        function set(i){
            if (i) {
                url = i;
            }
        };
            })();
    
    var json;
    (function(){
        var json;
        InitJson = function(i){
            if (i) {
                json = eval('(' + i + ')');
                
            }
            return {
                Get: get,
                Set: set
            };
        }
        function get(){
            return json;
        };
        function set(i){
            if (i) {
                json = eval('(' + i + ')');
            }
        };
            })();
    
    var pageInfo;
    
    (function(){
        var pageInfo;
        InitPageInfo = function(i){
            if (i) {
                pageInfo = eval('(' + i + ')');
                
            }
            return {
                Get: get,
                Set: set
            };
        }
        function get(){
            return pageInfo;
        };
        function set(i){
            if (i) {
                pageInfo = eval('(' + i + ')');
            }
        };
            })();
    
    var totalCount;
    (function(){
        var totalCount;
        InitTotalCount = function(i){
            if (i) {
                totalCount = i;
                
            }
            return {
                Get: get,
                Set: set
            };
        }
        function get(){
            return totalCount;
        };
        function set(i){
            if (i) {
                totalCount = i;
            }
        };
            })();
    
    
    var tag;
    (function(){
        var t;
        InitTag = function(i){
            if (i != undefined) {
                t = i;
                
            }
            return {
                Get: get,
                Set: set
            };
        }
        function get(){
            return t;
        };
        function set(i){
            if (i) {
                t = i;
            }
            
        };
            })();
    
    
    
    /**********序列号***************/
    
    var indexnum;
    (function(){
        var t;
        InitIndex = function(i){
            if (i != undefined) {
                t = i;
                
            }
            return {
                Get: get,
                Set: set
            };
        }
        function get(){
            return t;
        };
        function set(i){
            if (i) {
                t = i;
            }
            return this;
        };
            })();
    
    /******** 初始化全局变量******/
    
    (function(){
        url = InitUrl($("#hfSiteUrl").val());
        
        
        try {
            json = InitJson($("#hfJson").val());
        } 
        catch (e) {
            alert(e);
        }
        try {
            pageInfo = InitPageInfo($("#hfPageInfo").val());
        } 
        catch (e) {
            alert(e);
        }
        
        totalCount = InitTotalCount($("#hfTotalCount").val());
        
        tag = InitTag($("#tag").val());
        
        
        indexnum = InitIndex(1);
        
    })();
    
    
    
    var loading = false;
    /*******************************/
    
    (function(){
        getInstrumentPaged(1);
    })();
    
    var paging = cy.csts.paging({
        id: 'instrumet-paging-bottom',
        totalRecords: totalCount.Get(),
        pageSize: pageInfo.Get().PageSize,
        curPage: pageInfo.Get().CurrentPage,
        pageChanging: accountPagingChanging,
        pageChanged: function(newPageNum){
            //indexnum.Set(newPageNum*pageInfo.Get().PageSize);
            getInstrumentPaged(newPageNum, tag.Get());
        }
    });
    
    function accountPagingChanging(curPage, newPage){
    
        if (loading) {
            return false;
        }
        loading = true;
        return true;
    }
    
    /*************根据页数取值***************/
    function getInstrumentPaged(newPageNum){
    
        var html = '<p class="ul" style="margin-top: 12px; margin-bottom: 12px;"></p>' +
        ' <table width="100%">' +
        '<tbody>' +
        '<tr>' +
        '<td valign="top" width="110"><div class="img-box">' +
        '<a class="nbg" name="item"  id="_id_" title="_name_">' +
        '<img class="divshadow" src="_src_" width="87" height="87" alt="_name_"></a>' +
        '</div></td>' +
        '<td valign="top">' +
        '<div class="pl2">' +
        '<a name="item" style="cursor:pointer;" id="_id_">_name_ / <span style="font-size: 12px;">' +
        '_name_ /_alias_  _isshare_  (_gather_) </span></a></div>' +
        '<p class="pl"> <span class="unitinlist"><a class="unitinlist" style="color:black" href="_unitlink_" target="_blank">_unit_</a></span> / 仪器类别:_cate_/ 入网日期:_date_  _syscode_  _equipcode_ _specify_ / _service_ / _mission_ / _share_ / _value_(万) / _gather_</p>' +
        '<p class="pl">_func_</p>' +
        '<div class="star clearfix"><span class="pl">相关标签：_tag_</span><span class="rating_nums"></span></div>' +
        ' </td></tr></tbody> </table>';
        
        
        
        var info = pageInfo.Get();
        
        info.CurrentPage = newPageNum;
        try {
            $.ajax({
                type: 'POST',
                url: url.Get() + '/Ajax/Instrument/GetInstrumentList.ashx',
                data: 'pageinfo=' + $.toJSON(info) + '&json=' + $.toJSON(json.Get()) + '&tag=' + tag.Get(),
                dataType: 'json',
                success: function(data, textStatus){
                    if (data && data.success) {
                        $("div#item-list").empty();
                        for (var i = 0; data.list[i]; i++) {
                            (function(item){
                                var s = html.replace(/_id_/g, unescape(item.id));
                                s = s.replace(/_name_/g, unescape(item.name) ? unescape(item.name) : '');
                                s = s.replace(/_alias_/g, unescape(item.alias) ? unescape(item.alias) : '');
                                s = s.replace(/_date_/g, unescape(item.date) ? unescape(item.date) : '');
                                s = s.replace(/_cate_/g, unescape(item.type) ? unescape(item.type) : '');
                                s = s.replace(/_unit_/g, unescape(item.unit) ? unescape(item.unit) : '');
                                 s = s.replace(/_unitlink_/g, unescape(item.unitlink) ? unescape(item.unitlink) : '');
                                s = s.replace(/_value_/g, unescape(item.value) ? unescape(item.value) : '');
                                s = s.replace(/_pdate_/g, '');//unescape(item.purchedate) ? unescape(item.purchedate) : 
                                s = s.replace(/_specify_/g, unescape(item.isspecify) ? '特色仪器' : '非特色仪器');
                                s = s.replace(/_share_/g, unescape(item.isshare) ? '协作共用' : '非协作共用');
                                s = s.replace(/_service_/g, unescape(item.isservice) ? '对外提供服务' : '不对外提供服务');
                                s = s.replace(/_mission_/g, unescape(item.ismission) ? '接受外来任务' : '不接受外来任务');
                                
                                s = s.replace(/_func_/g, unescape(item.func) ? unescape(item.func).substring(0, 50) : '');
                                s = s.replace(/_tag_/g, item.tags ? unescape(item.tags) : '');            
															
								s = s.replace(/_src_/g, unescape(item.img) ? '../../../Ajax/InstrumentManagement/InstrumentInfoManagement/ImageRender.ashx?Id='+unescape(item.img)+'&type=_middle': '');
								
                                //s = s.replace(/_src_/g, unescape(item.url) ? unescape(item.url) : '');
                                
                                s = s.replace(/_isshare_/g, unescape(item.isshare) === 'true' ? '(协作)' : '(非协作)');
                                
                                
                                s=s.replace(/_syscode_/g,unescape(item.syscode)? '/ 系统编号:'+unescape(item.syscode) :'');
                                
                                s=s.replace(/_equipcode_/g,unescape(item.instrcode)?'/ 单位自建编号:'+unescape(item.instrcode):"");
                                
                                //s=s.replace(/_auditdate_/g,unescape(item.auditdate)?unescape(item.auditdate):"");
                                
                                if (parseInt(item.gatherid) === 0) {
                                    s = s.replace(/_gather_/g, '未安装采集盒');
                                }
                                else {
                                    s = s.replace(/_gather_/g, '采集盒:' + unescape(item.gather));
                                }
                                
                                $(s).find("a[name='item']").click(function(){
                                    window.open("instrumentdetail.aspx?id="+$(this).attr("id"));
                                }).end().find("a.tag").click(function(){
                                    var t = $(this).html();
                                    if (t) {
                                        json.Get().tags = [];
                                        json.Get().tags.push(t);
                                        getInstrumentPaged(1);
                                        GetPageTotalCount();
                                    }
                                }).end().appendTo("div#item-list");
                            })(data.list[i]);
                        }
                        
                        fillRelativeTypes(data.types);
                        fillRelativeTags(data.tags);
                        fillRelativeInstument(data.insts);
                        fillRelativeUnit(data.unit);
                        
                    }
                    loading = false;
                    
                }
            });
        } 
        catch (e) {
            alert(e);
        }
    }
    
    var IsTypeFirst = true;
    function fillRelativeTypes(list){
    
        var html = '<span style="marging-right:5px;"><a id="_id_" class="tag" >_name_(_num_)</a></span>';
        if (list) {
            $("div#relative-type-con div.tags-list").empty();
            for (var i = 0; i < list.length; i++) {
                var s = html.replace(/_id_/g, list[i].id);
                s = s.replace(/_name_/g, unescape(list[i].name));
                s = s.replace(/_num_/, list[i].count ? list[i].count : 0);
                $(s).find("a").click(function(){
                    var type = $(this).attr("id");
                    if (type && json.Get().hasOwnProperty("Cate")) {
                        json.Get().Cate = type;
                        getInstrumentPaged(1);
                        GetPageTotalCount();
                    }
                }).appendTo("div#relative-type-con div.tags-list");
                
            }
        }
        
    }
    
    var isTagFirst = true;
    function fillRelativeTags(list){
        if (isTagFirst) {
            var html = '<span><a class="tag" id="_id_" style="marging-right:3px;" >_name_</a></span>';
            if (list) {
                $("div.floatr div#relative-tag-con div.tags-list").empty();
                for (var i = 0; i < list.length; i++) {
                    var s = html.replace(/_id_/g, list[i]);
                    s = s.replace(/_name_/g, list[i]);
                    $(s).find("a").click(function(){
                        var t = $(this).html();
                        if (t && json.Get().hasOwnProperty("tags")) {
                            json.Get().tags = [];
                            json.Get().tags.push(t);
                            //  getInstrumentPaged(1);
                            GetPageTotalCount();
                        }
                        
                    }).appendTo("div.floatr div#relative-tag-con div.tags-list");
                }
            }
        }
    }
    
    var isInstrumentFirst = true;
    function fillRelativeInstument(list){
        var html = '<li style="display:inline;"><a style="display:inline;" href="InstrumentDetail.aspx?id=_id_">_name_</a> <span style="font-size:12px;line-height:13px;color:#666699;">_ename_</span></li>';
        if (list && list.length > 0) {
            $("div.floatr div#relative-instrument-con ul.bs").empty();
            for (var i = 0; i < list.length; i++) {
                var s = html.replace(/_id_/g, unescape(list[i].id));
                s = s.replace(/_name_/g, unescape(list[i].name) ? unescape(list[i].name) : '');
                s = s.replace(/_ename_/g, unescape(list[i].ename) ? "(" + unescape(list[i].ename) + ")" : '');
                $(s).find("a").click(function(){
                }).end().appendTo("div.floatr div#relative-instrument-con ul.bs");
            }
        }
        
        
    }
    
    var isUnitFirst = true;
    function fillRelativeUnit(list){
        if (isUnitFirst) {
            var html = '<li style="display:inline-block;margin-right:5px"><a id="_id_">_name_</a></li>';
            if (list && list.length > 0) {
                $("div.floatr div#relative-unit-con ul").empty();
                for (var i = 0; i < list.length; i++) {
                    var s = html.replace(/_id_/g, unescape(list[i].id));
                    s = s.replace(/_name_/g, unescape(list[i].name));
                    $(s).find("a").click(function(){
                        var unit = $(this).attr("id");
                        if (unit && json.Get().hasOwnProperty("Unit")) {
                            json.Get().Unit = unit;
                            getInstrumentPaged(1);
                            GetPageTotalCount();
                        }
                    }).end().appendTo("div.floatr div#relative-unit-con ul");
                }
            }
        }
    }
    
    /**************排序****************/
    
    
    (function(){
        $("span#sort-con a").click(function(){
            var s = $(this).attr("value");
            json.Get().sort.length = 0;
            json.Get().sort.push(s);
            /*********对当前的页号和页面的数字***********/
            
            getInstrumentPaged();
        });
    })();
    
    
    
    /**************搜索*****************/
    
    /*****搜索类别******/
    
    (function(){
        $("input[name='search_text']").focus(function(){
            //this.value = this.value.toLowerCase() == "Search".toLowerCase() ? "" : this.value;
            this.value = '';
        });
        $("input#btn-type-search").click(function(e){
            var t = $(this).prev("input").val();
            if (t && json.Get() && json.Get().hasOwnProperty("Cates") && json.Get().hasOwnProperty("Cate")) {
                (function(){
                    $.ajax({
                        type: 'GET',
                        url: url.Get() + '/Ajax/Instrument/SelectTypes.ashx',
                        data: 'typename=' + t,
                        dataType: 'json',
                        success: function(data, textStatus){
                            if (data && data.success) {
                                json.Get().Cates = [];
                                json.Get().Cate = data.list[0];
                                for (var i = 0; i < data.list.length; i++) {
                                    json.Get().Cates.push(data.list[i]);
                                }
                                GetPageTotalCount();
                            }
                        }
                    });
                })();
                
                
            }
        });
        
        $("input#btn-tag-search").click(function(e){
            var t = $(this).prev("input").val();
            if (t && json.Get() && json.Get().hasOwnProperty("tags") && json.Get().hasOwnProperty("tags")) {
                json.Get().tags = [];
                json.Get().tags.push(t);
                
                GetPageTotalCount();
            }
        });
    })();
    
    /******点击相关类型*******/
    
    (function(){
        $("div.aside div#relative-type-con div.tags-list a").click(function(){
            var type = $(this).attr("id");
            if (type && json.Get().hasOwnProperty("Cate")) {
                json.Get().Cate = type;
                getInstrumentPaged(1);
                GetPageTotalCount();
            }
            
        })
    })();
    
    
    
    /***********标记***************/
    
    (function(){
        $("span#sort-con a").click(function(){
            $(this).addClass("current-link").siblings().removeClass();
        });
    })();
    
    /*********设置页面值************/
    
    
    function GetPageTotalCount(){
        $.ajax({
            type: 'Get',
            url: url.Get() + '/Ajax/Instrument/GetInstrumentTotalCount.ashx',
            data: 'json=' + $.toJSON(json.Get()) + '&tag=' + tag.Get(),
            dataType: 'json',
            success: function(data, textStatus){
                if (data && data.success) {
                    $("#totalcount").html(data.num);
                    $("#ul-pageinfo #record-num").html(data.num);
                    $("#ul-pageinfo #page-count").html((Math.ceil((data.num / parseInt(pageInfo.Get().PageSize))>0?(data.num / parseInt(pageInfo.Get().PageSize))-1:0 ) + (data.num % parseInt(pageInfo.Get().PageSize) > 0 ? 1 : 0)));
                    paging.setPageSize(pageInfo.Get().PageSize);
					paging.setTotalRecords(data.num);					
				//	paging.redirectTo(1);                   
                }
                else {
                    alert("error");
                }
            }
        });
    }
    
    $("#ajax-loading").ajaxStart(function(){
        $(this).show();
    }).ajaxStop(function(){
        $(this).hide();
    });
    
    
    
    /***********************************/
    
    (function(){
        $('#instrument-list-category').find(".hideul").hide().end().find('img').click(function(){
            var currentimg = $(this);
            var answer = $(this).next().next();
            if (answer.is(':visible')) {
                answer.slideUp();
                currentimg.attr("src", "img/tree-node-close-hover.gif");
                currentimg.attr("Title", "点击展开分类导航");
            }
            else {
                answer.slideDown();
                currentimg.attr("src", "img/tree-node-open.gif");
                currentimg.attr("Title", "点击合拢分类导航");
            }
        });
        
        $('#unit-list-category').find(".hideul").hide().end().find('img').click(function(){
            var currentimg = $(this);
            var answer = $(this).next().next();
            if (answer.is(':visible')) {
                answer.slideUp();
                currentimg.attr("src", "img/tree-node-close-hover.gif");
                currentimg.attr("Title", "点击展开分类导航");
            }
            else {
                answer.slideDown();
                currentimg.attr("src", "img/tree-node-open.gif");
                currentimg.attr("Title", "点击合拢分类导航");
            }
        });
        
        
        /*************导航***************/
        
        $("div#instrument-list-category a").click(function(){
            reInitialJson();
            var cateid = $(this).attr("id");
            if (cateid && json.Get() && json.Get().hasOwnProperty("Cate")) {
                json.Get().Cate = cateid;
            }
            GetPageTotalCount();
        });
        
        $("div#unit-list-category a.root").click(function(){
            reInitialJson();
            if (json.Get().hasOwnProperty("unitflag")) {
                json.Get().unitflag = $(this).attr("value");
            }
            GetPageTotalCount();
        });
        
        $("div#unit-list-category a.branch").click(function(){
            reInitialJson();
            if (json.Get().hasOwnProperty("unitflag") && json.Get().hasOwnProperty("unittype")) {
                json.Get().unitflag = $(this).parent().parent().parent().find("a.root:first").attr("value");
                json.Get().unittype = $(this).attr("value");
            }
            GetPageTotalCount();
        });
        
        $("div#unit-list-category a.leaf").click(function(){
            reInitialJson();
            var u = $(this).attr("id");
            if (json.Get().hasOwnProperty("Units")) {
                json.Get().Units = [];
                json.Get().Units.push(u);
            }
            GetPageTotalCount();
        });
        
        
    })();
    
    
    
    
    
    function reInitialJson(){
        if (json && json.Get()) {
            json.Set($("#templatejson").val());
        }
        
    }
    
    
    /***************仪器搜索*******************/
    
    
    (function(){
        $("#instrument-search-text").focus(function(){
            $(this).val("");
        });
        $("#instrument-search-button").click(function(){
            var name = $.trim($("#instrument-search-text").val());
            if (name && name !== '请输入仪器名称') {
                reInitialJson();
                if (json.Get().hasOwnProperty("Name")) {
                    json.Get().Name = name;
                    GetPageTotalCount();
                }
            }
            
        })
    })();
    
    
    /******************************************/
    (function(){
        $("#ul-pageinfo select").change(function(){
            //reInitialJson();
            pageInfo.Get().PageSize = $(this).val();
            GetPageTotalCount();
            
        });
    })();
    
    
    
    
    
});
