﻿//Ready
$(document).ready(function() {
    new $(".SearchPro").pViewSearch({ id: 'SearchPro', index: 1, size: 15 });
});

jQuery.fn.pViewSearch = function(config) {

    //参数
    config = jQuery.extend({

        id: null,     //ID
        index: 1,     //Current page
        size: 15,     //page Size
        pSize: 12,     //pager Size show
        sort: '',
        dir: 'asc',
        param: '',
        type: 'Ab',
        pager: new Array(),
        defVal: 'Search products by antigen name,catalog no. etc.',
        errorVal: "Please Input your keyword",
        callback: function() { return false; } //回调函数

    }, config || {});

    return this.each(function() {

        var isloaded = new Array();
        var me = $(this);
        var keyword = (getRequest('key')) ? unescape(getRequest('key').Trim()).Filter() : ''; //serach word

        adjustSearchCorners = function() {

            if ($(".SearchPro").length <= 0) return;
            var cB = { id: '',
                tl: { radius: 5 },
                tr: { radius: 5 },
                bl: { radius: 5 },
                br: { radius: 5 },
                antiAlias: true,
                autoPad: true, validTags: ["div"]

            };
            $('.SearchPro div:first').corner(cB);
        };

        searchgo = function() {
            var svl = $("#search").val().Trim().Filter();
            if (svl != "" && svl != config.defVal && svl != config.errorVal) {
                window.location = "PViewSearch.aspx?key=" + svl + "&params=" + getParams();
            }
            else {
                $("#search").val(config.errorVal).removeClass("foucs").addClass('null');
                $("#searchGo").removeClass("foucs").addClass('null');
            }
        };

        onKeydowm = function(e) {
            var currentKey = e ? e.keyCode : e.which;
            if (currentKey == 13) { searchgo(); return false; }
        };
        onFocus = function() {
            var obj = $("#search");
            if (obj.val() == config.defVal || obj.val() == config.errorVal)
                obj.val("");
            obj.removeClass("null").addClass("foucs");
            $("#searchGo").removeClass("null").addClass("foucs");
        };

        onBlur = function() {
            var obj = $("#search");
            if (obj.val().Trim() == "")
                obj.val(config.defVal);
            $("#search").removeClass("foucs").removeClass("null");
            $("#searchGo").removeClass("foucs").removeClass("null");
        };

        /* Sub tab content*/
        setPager = function(row) {
            config.pager[config.type] = jQuery.extend(config.pager[config.type], { total: eval('row.TotalRow') });

            $("#dvProPager" + config.type).SimplePager({
                showNum: config.pSize,
                pageSize: config.size,
                nowPage: ((config.pager[config.type].nowPage) ? config.pager[config.type].nowPage : 1),
                totalRec: config.pager[config.type].total,
                callback: reload
            });
        };
        setList = function(rows) {
            $("#dataList" + config.type).TableSetter({ id: 'dataList' + config.type, innerHtml: makelist(rows) });
        };
        setLeft = function(r1, r2, r3) {
            var str = new Array();
            str.push("<div><strong class='plus'>By Symbol</strong><ul style='list-style-type: none;'>");
            $.each(r1, function(i, o) {
                str.push("<li><a t='s' n='" + this.Symbol + "' href='javascript:void(0)' class='extlink' title='" + this.FullName + this.Synonyms + "'>" + this.Symbol + "</a></li>");
            });
            str.push("</ul></div>");
            str.push("<div class='mainlevel'></div>");
            str.push("<div><strong class='plus'>By WB Lysate</strong><ul style='list-style-type: none;'>");
            $.each(r2, function(i, o) {
                str.push("<li><a t='l' n='" + this.LysateName + "' href='javascript:void(0)' class='extlink'>" + this.LysateName + "</a></li>");
            });
            str.push("</ul></div>");
            str.push("<div class='mainlevel'></div>");
            str.push("<div><strong class='plus'>By IHC Tissue</strong><ul style='list-style-type: none;'>");
            $.each(r3, function(i, o) {
                str.push("<li><a t='t' n='" + this.Tissue + "'  href='javascript:void(0)' class='extlink'>" + this.Tissue + "</a></li>");
            });
            str.push("</ul></div>");
            str.push("<div class='mainlevel'></div>");

            $('#dvPviewLeft').empty().append(str.join(''));

            $('#dvPviewLeft li a').click(function() { addFilter(this); });

            $('#dvPviewLeft .plus').click(function() { $(this).next().toggle(); });

        };

        addFilter = function(o) {
            var t = $(o).attr('t');
            var n = $(o).attr('n');
            var of = $('#filter');
            var oli = $('#filter li[t="' + t + '"]');
            //exist
            if (oli.length > 0) {

                oli.children().eq(0).text(getName(t) + ': ' + n);
                oli.children().eq(1).val(n);
            }
            //no
            else {
                addOneFilter(of, t, n);
            }

            reload(1);
        };

        initFilter = function() {
            var p = getRequest('params');
            if (p == null) return;
            p = p.split('|');
            var of = $('#filter');
            for (var i = 0; i < p.length; i++) {

                var kv = p[i].split('=');
                if (kv.length == 2 && kv[0].length == 1 && kv[1] != '') {
                    addOneFilter(of, kv[0], kv[1]);
                }
            }
        };

        addOneFilter = function(of, t, n) {
        var str = '<li t="' + t + '"><div class="text">' + getName(t) + ': ' + n + '</div><div class="close"><input type="hidden" id="hid' + t + '" value="' + n + '" /></div></li>';
            of.append(str);

            of.parent().show();

            $('#filter li[t="' + t + '"] .close').click(function() { $(this).parent().remove(); if ($('#filter li').length <= 1) $('#filter').parent().hide(); reload(1); });
        };

        getName = function(t) {
            if (t == 's') return 'Symbol';
            else if (t == 't') return 'IHC Tissue';
            else if (t == 'l') return 'Western blot lysate';
        };

        /* Sub tab content end */

        load = function(again) {
            setLoading(true);
            if (!getRequest('key')) { setLoading(false); return; }

            if (!config.pager[config.type] || again) {
                config.pager[config.type] = jQuery.extend(config.pager[config.type], { start: 1, end: config.size, nowPage: 1 });
            }
            $.getJSON("../Handler/ProductHandler.ashx?r=" + Math.random(),
            { func: 'GetPViewSearch', param: getParams() },
            function(res) {

                setPager(res.table[4].rows[0]);
                setList(res.table[3].rows); $('#dvTemp').hide();
                setLeft(res.table[0].rows, res.table[1].rows, res.table[2].rows);
                highlight(config.type);
                adjustMain();
                setLoading(false);
            });
        };

        reload = function(p, pSize) {
            setLoading(true);
            if (pSize && config.pager[config.type].size != pSize) {
                p = 1;
            }
            config.pager[config.type] = jQuery.extend(config.pager[config.type], {
                start: (p - 1) * config.size + 1,
                end: p * config.size,
                nowPage: p
            });
            load();
        };

        makelist = function(rows) {
            if (!rows) return "";
            var str = new Array();

            $.each(rows, function(i, o) {
                switch (config.type.toLowerCase()) {
                    case "ab":
                        str.push('<tr>');
                        str.push('<td width="70" rowspan="2"><a href="PViewDetail.aspx?catNo=' + this.CatalogNo + '" target="_blank">' + this.CatalogNo + '</a></td>');
                        str.push('<td width="200">' + this.ProductName + '</td>');
                        str.push('<td width="190">' + this.TestedIHCTissue + '</td>');
                        str.push('<td width="190">' + this.TestedWBLysate + '</td>');
                        str.push('</tr>');
                        str.push('<tr>');
                        str.push('<td colspan="4" style="text-align:left;padding-left:3px;">Synonyms : ' + rpl(this.FullName) + '' + rpl(this.Synonyms) + '</td>');
                        str.push('</tr>')
                        break;
                    default:
                        break;
                }
            });

            return str.join('');
        };

        highlight = function(t) {
            switch (config.type.toLowerCase()) {
                case "ab":
                    $('#dataList' + t + ' td').highlight(keyword);
                    break;
                default:
                    break;
            }
        };
        formatType = function(tbl) {
            if (tbl.toLowerCase() == 'cdna')
                return (tbl.substr(0, 1).toLowerCase()) + (tbl.substr(1).toUpperCase());
            else
                return (tbl.substr(0, 1).toUpperCase()) + (tbl.substr(1).toLowerCase());
        };

        //Tips : params : key , s:Symbol, t:IHC Tissue, l: lysate, start end
        getParams = function() {

            var p = 'key=' + keyword;
            p = p + '|s=' + ($('input[id="hids"]').length > 0 ? $('#hids').val() : "");
            p = p + '|l=' + ($('input[id="hidl"]').length > 0 ? $('#hidl').val() : "");
            p = p + '|t=' + ($('input[id="hidt"]').length > 0 ? $('#hidt').val() : "");
            p = p + '|start=' + ((!config.pager[config.type]) ? 1 : config.pager[config.type].start);
            p = p + '|end=' + ((!config.pager[config.type]) ? config.size : config.pager[config.type].end);
            return p;
        }

        //repalce ; with ;+sp
        rpl = function(str) {
            return str.replace(/;/g, "\; ");
        }

        init = function() {
            setLoading(true);
            adjustSearchCorners();
            $("#search").val((getRequest('key')) ? keyword : config.defVal).focus(onFocus).keydown(onKeydowm).blur(onBlur);
            $("#searchGo").click(searchgo).blur(onBlur);
            initFilter();
            load();
        };

        start = function() {
            init();
        };

        start();
    });
};