if (! ("console" in window)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group"
                 , "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {};
}

var Searcher = {
    server: "http://search.kbmj.com",
    service: null,
    options: {},
    sliders: {},
    autoScroll: true,
    nextPageIndicatorOffset: -1,
    loadingPage: 0,
    loading: false,
    debug: false,
    showImportantMessageOnly: true,
    initialized: false,

    html: {
        query_label: ".query_label",

        // ロード中に表示するインジケータ
        indicator: ".search_indicator",
        
        // エラーなどを表示する部分
        message: "#search_message",
        
        // 検索オプション
        options: "#search_options",
        
        // 検索オプションのスライダー
        slider: ".search_slider",
        slider_label: ".search_slider_label",
        
        // 検索オプションのタグ。タグの数だけ複製される。
        tag: ".search_tag",
        // 検索オプションのタグのテキスト部分
        tag_text: null,
        // 検索オプションのタグの選択を解除するボタン
        tag_remove_button: null,
        
        // ソート順を選択する select タグ
        select_qf: "#search_select_qf",
        
        // ソート順を選択する select タグ
        select_sort: "#search_select_sort",
        
        // 表示件数を選択する select タグ
        select_limit: "#search_select_limit",
        
        // アイテム一覧を含む部分
        items: "#search_items",
        
        // アイテム一覧のページ。autoScroll を有効にする場合、ページごとにこの要素が複製される。
        page: ".search_page",
        
        // ページ内のヘッダ。表示件数を表示する部分。
        page_header: ".search_page_header",

        // ページについての情報。page_header の中に入れる。
        total: ".search_total",
        start_index: ".search_start",
        end_index: ".search_end",
        
        // 他のページへのリンクを含む部分。autoScroll が有効の場合は必要なし。
        page_links: ".search_page_links",
        
        // 前へ、次へ、各ページへのリンク。page_number は必要に応じて複製される。
        prev_page: ".search_prev_page",
        next_page: ".search_next_page",
        page_number: ".search_page_number",
        
        // アイテムを含む部分。この要素は表示するアイテムの数だけ複製される。
        item: ".search_item",
        
        // autoScroll が有効な場合に、次のページをロード中に表示する部分。
        scroll_next_page: "#search_scroll_next_page"
    },

    log: function() {
        if (this.debug) {
            console.debug(arguments);
        }
    },

    qf: function() {
        return $(this.html.select_qf).attr('value');
    },

    form: function(config) {
        var self = this;
        this.searchPage = config.page;
        this.queryElement = config.query;
        $(config.form).submit(function(event) {
            self.searchFromForm($(this).find(config.query).attr("value"));
            event.preventDefault();
        });
        $(config.query).suggest(this.server + '/' + this.service + '/suggest.json', {minchars: 2});
    },
    
    searchFromForm: function(query) {
        if (this.initialized) {
            this.log("historyLoad: " + this._encodeQuery(query));
            var qf = this.qf();
            var query = "q=" + this._encodeQuery(query);
            if (qf) {
                query += "/qf=" + qf;
            }
            $.historyLoad(query);
        } else {
            location.href = this.searchPage + "#q=" + this._encodeQuery(query);
        }
    },
    
    _encodeQuery: function(query) {
        if (query) {
            return encodeURIComponent(query.replace(/[\/~]/g, 
                                                    function(s) {
                                                        return "~" + s.charCodeAt(0).toString(16);
                                                    }));
        } else {
            return "";
        }
    },
    
    _decodeQuery: function(query) {
        if (query == null) return "";
        return decodeURIComponent(query).replace(/\~([0-9a-f][0-9a-f])/gi, function(str, p1, offset, s) {
            return String.fromCharCode(parseInt(p1, 16));
        });
    },

    searchFailed: function() {
        $(this.html.indicator).hide();
        Searcher.showMessage('検索に失敗しました。ページを再読み込みするか、別の条件で検索してください。', true)
    },

    resetLoading: function() {
        if (this.loading) {
            this.loading = false;
            this.searchFailed();
        }
    },

    logError: function(error) {
        if (window.console && window.console.error) {
            console.error(error);
        }
        $.getScript(this.server + "/" + this.service + "/search/error?" + $.param({error: error}));
    },

    search: function(query) {
        if (!this.loading) {
            $(this.html.indicator).show();
            this.loading = true;
            this.showMessage("検索中です...", false);
            var self = this;
            $.getScript(this.server + "/" + this.service + "/search.json?callback=Searcher.callback&" + query.encodeParams(),
                        function() {
                            self.resetLoadingTimer = setTimeout(function() {
                                self.resetLoading();
                            }, true);
                        });
        }
    },

    formatDate: function(d) {
        return d.getFullYear() + "/" + this.formatTwoDigits(d.getMonth() + 1) + "/" + this.formatTwoDigits(d.getDate());
    },

    formatTwoDigits: function(n) {
        return n < 10 ? "0" + n : n.toString(10);
    },

    // for backward compatibility
    _htmlEscape: function(str) {
        return this.htmlEscape(str);
    },
    
    htmlEscape: function(str) {
        if (str) {
            return String(str).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
        } else {
            return "";
        }
    },

    _renderPages: function(pageArea, response) {
        var self = this;
        var pages = [];
        var totalPages = 11;
        var start_page = response.query.page - (totalPages - 1) / 2;
        var end_page = response.query.page + (totalPages - 1) / 2;
        if (start_page <= 0) {
            end_page += 1 - start_page;
            start_page += 1 - start_page;
        }
        var max_page = Math.ceil(response.result.total / response.query.limit);
        if (end_page >= max_page) {
            start_page = max_page - totalPages + 1;
            if (start_page < 1) start_page = 1;
            end_page = max_page;
        }
        for (var i = start_page; i <= end_page; i++) {
            pages.push(i);
        }
        if (pages.length > 1) {
            var directive = {};
            directive[this.html.page_number] = {
                'page <- pages': {
                    '.': function(arg) {
                        if (arg.item == response.query.page) {
                            return ' <em>' + arg.item + '</em>';
                        } else {
                            return ' <a href="javascript:Searcher.selectPage(' + arg.item + ')">' + arg.item + '</a>';
                        }
                    }
                }
            };
            pageArea.find(this.html.page_links).each(function() {
                $(this).find(self.html.page_number + ':gt(0)').remove();
                $(this).render({pages: pages}, directive);
            });
            if (response.query.page > 1) {
                pageArea.find(this.html.prev_page).show().find('a').attr("href", 'javascript:Searcher.selectPage(' + (response.query.page - 1) + ')');
            } else {
                pageArea.find(this.html.prev_page).hide();
            }
            if (response.query.page < max_page) {
                pageArea.find(this.html.next_page).show().find('a').attr("href", 'javascript:Searcher.selectPage(' + (response.query.page + 1) + ')');
            } else {
                pageArea.find(this.html.next_page).hide();
            }
            pageArea.find(this.html.page_links).show();
            if (response.query.page < end_page) {
                setTimeout(function() {
                    self.nextPageIndicatorOffset = $(self.html.scroll_next_page).show().offset().top - 200;
                }, 10);
                //console.debug(this.nextPageIndicatorOffset);
            } else {
                this.nextPageIndicatorOffset = -1;
                $(this.html.scroll_next_page).hide();
            }
        } else {
            this.nextPageIndicatorOffset = -1;
            pageArea.find(this.html.page_links).hide();
            $(this.html.scroll_next_page).hide();
        }
    },

    sortTags: function(pairs) {
        var last = null;
        var result = [];
        for (var i = 0; i < pairs.length; i++) {
            if ("その他" == pairs[i][0]) {
                last = pairs[i];
            } else {
                result.push(pairs[i]);
            }
        }
        if (last) result.push(last);
        return result;
        
        //return pairs;
    },
    
    _renderTags: function(response, option, config) {
        var selector = config["selector"];
        //console.debug(Searcher.currentQuery);
        var tags = response.result.facet_fields[option];
        if (!tags) tags = [];
        var queryTags = this.currentQuery.options[option];
        if (queryTags) {
            // 0 件であっても、すでに選択されているタグがあれば表示する
            var tagNames = [];
            for (var i = 0; i < tags.length; i += 2) {
                tagNames.push(tags[i]);
            }
            $.each(queryTags, function() {
                var tag = String(this);
                var n = $.inArray(tag, tagNames);
                if (n < 0) {
                    tags.push(tag);
                    tags.push(0);
                }
            });
        }
        if (tags.length > 0) {
            var pairs = [];
            var last = null;
            if (config["all"]) {
                pairs.push([config["all"], null]);
            }
            for (var i = 0; i < tags.length; i += 2) {
                var pair = [tags[i], tags[i + 1]];
                pairs.push(pair);
            }
            pairs = this.sortTags(pairs);
            var self = this;
            $(selector).each(function() {
                $(this).find(self.html.tag + ":gt(0)").remove();
                var last = null;
                for (var i = 0; i < pairs.length; i++) {
                    var tag;
                    var tag_text;
                    var tag_remove_button = null;
                    if (!last) {
                        tag = last = $(this).find(self.html.tag);
                    } else {
                        tag = last.clone();
                        last.after(tag);
                        last = tag;
                    }
                    if (self.html.tag_text) {
                        tag_text = $(tag).find(self.html.tag_text);
                    } else {
                        tag_text = tag;
                    }
                    if (self.html.tag_remove_button) {
                        tag_remove_button = $(tag).find(self.html.tag_remove_button);
                    }
                    var item = pairs[i];
                    var name = item[0];
                    var count = item[1];
                    var className = "_search_tag_name";
                    var html = '<span class="' + className + '">' +
                        Searcher.htmlEscape(name) + 
                        '</span>';
                    if (count != null) {
                        if (!config["hideCount"]) {
                            html += " (" + count + ")";
                        }
                        tag.removeClass("_search_tag_all");
                    } else {
                        tag.addClass("_search_tag_all");
                    }
                    tag_text.html(html);
                    tag.addClass("_search_tag");
                    var removeButton = null;
                    var selectedValues = Searcher.currentQuery.options[option];
                    if ((selectedValues && 0 <= $.inArray(item[0], selectedValues)) ||
                        ((!selectedValues || selectedValues.length == 0) && count == null)) {
                        if (tag_remove_button) {
                            tag_remove_button.show();
                        }
                        tag.addClass("selected");
                    } else {
                        if (tag_remove_button) {
                            tag_remove_button.hide();
                        }
                        tag.removeClass("selected");
                    }
                }
            }).show();
        } else {
            $(selector).hide();
        }
    },

    suggestMessage: function(suggestions) {
        var suggestMessage = "";
        if (suggestions && suggestions.length > 0) {
            suggestMessage = 'もしかして';
            for (var i = 0; i < suggestions.length; i++) {
                suggestMessage += ' <a href="javascript:Searcher.selectSuggestion(' + i + ')">' + Searcher.htmlEscape(suggestions[i]) + '</a>';
            }
        }
        return suggestMessage;
    },

    renderSearchMessage: function(response) {
        var suggestMessage = this.suggestMessage(response.result.suggestions);
        if (response.result.items.length > 0) {
            if (suggestMessage) {
                $(this.html.message).html(suggestMessage).show();
            } else {
                this.showMessage("");
                //$(this.html.message).hide();
            }
        } else {
            if (this.currentQuery.keywordOnly()) {
                this.showMessage("<div><strong>" +
                                 this.htmlEscape(this.currentQuery.q) +
                                 "</strong> に一致する情報は見つかりませんでした。</div>" + 
                                 suggestMessage, true);
            }
        }
    },

    _doCallback: function(response) {
        clearTimeout(this.resetLoadingTimer);
        this.loading = false;
        $(this.html.indicator).hide();
        this.currentQuery = new this.Query();
        for (var key in response.query) {
            this.currentQuery.loadParam(key, response.query[key]);
        }
        var self = this;
        var pageArea;
        var itemsArea = $(this.html.items);
        if (this.loadingPage > 0) {
            this.cumulativeTotal += response.result.items.length;
            var clone = $("#_search_items_page_0").clone();
            clone.attr("id", "_search_items_page_" + this.loadingPage);
            clone.find(this.html.item + ':gt(0)').remove();
            clone.insertAfter("#_search_items_page_" + (this.loadingPage - 1));
            pageArea = clone;
        } else {
            this.cumulativeTotal = response.result.items.length;
            itemsArea.find(this.html.page + ':gt(0)').remove();
            itemsArea.find(this.html.item + ':gt(0)').remove();
            pageArea = itemsArea.find(this.html.page);
            pageArea.attr("id", "_search_items_page_0");
        }
        //$(this.html.query).text(response.query.q);
        itemsArea.show();
        self.suggestions = response.result.suggestions;
        if (response.result.items.length > 0) {
            //console.debug('matched ' + response.result.items.length + ' items');
            $(this.html.item).show();
            var header = pageArea.find(this.html.page_header);
            if (header.length) {
                header.find(this.html.total).text(response.result.total);
                var start = (response.query.page - 1) * response.query.limit;
                header.find(this.html.start_index).text(start + 1);
                header.find(this.html.end_index).text(start + response.result.items.length);
                header.show();
            } else {
                var header = $(this.html.page_header);
                if (header.length) {
                    header.find(this.html.total).text(response.result.total);
                    header.find(this.html.end_index).text(this.cumulativeTotal);
                    header.show();
                }
            }
            this._renderPages(pageArea, response);
            // pageArea.find('.search_counter').show();
            var directive = {};
            directive[this.html.item] = {
                'row <- rows': this.item_directive
            };
            pageArea.render({rows: response.result.items}, directive);
            for (var name in this.options) {
                var config = this.options[name];
                if ("tag" == config["type"]) {
                    this._renderTags(response, name, config);
                } else if ("slider" == config["type"]) {
                    if (response.result.ranges && response.result.ranges[name]) {
                        var slider = this.sliders[name];
                        slider.setFullRange(response.result.ranges[name]);
                        slider.loadQuery();
                    }
                }
            }
            $(this.html.options).show();
        } else {
            $(this.html.page_header).hide();
            $(this.html.items).hide();
            $(this.html.options).hide();
        }
        self.renderSearchMessage(response);
    },
    
    showMessage: function(msg, important) {
        $(this.html.message).html(msg);
        if (this.showImportantMessageOnly) {
            if (important) {
                $(this.html.message).show();
            } else {
                $(this.html.message).hide();
            }
        }
    },

    autoScroll: function() {
        //console.debug("autoScroll");
        this.loadingPage++;
        var query = this.currentQuery.copy();
        query.page = (query.page || 0) + 1;
        this.search(query);
    },

    selectAll: function() {
        var query = new this.Query({
            q: this.currentQuery.q
        });
        this.loadQuery(query);
    },
    
    changeSort: function(value) {
        if (!this.currentQuery) return;
        var query = this.currentQuery.copy();
        query.page = null;
        if (value && value.length > 0) {
            query.sort = value;
        } else {
            query.sort = null;
        }
        this.loadQuery(query);
    },

    changeLimit: function(value) {
        if (!this.currentQuery) return;
        var query = this.currentQuery.copy();
        query.page = null;
        query.limit = parseInt(value, 10);
        this.loadQuery(query);
    },

    selectSuggestion: function(i) {
        var query = new this.Query({
            q: this.suggestions[i]
        });
        this.loadQuery(query);
    },

    selectTag: function(key, tag) {
        var query = this.currentQuery.copy();
        query.page = null;
        var config = this.options[key];
        var tags = query.options[key];
        if (config.single) {
            if (tag) {
                tags = [tag];
            } else {
                tags = null;
            }
        } else {
            if (null == tags || $.inArray(tag, tags) < 0) {
                if (null == tags) tags = [tag];
                else tags.push(tag);
            } else {
                var n = $.inArray(tag, tags);
                tags.splice(n, 1);
            }
        }
        query.options[key] = tags;
        //console.debug("selectTag", query);
        this.loadQuery(query);
    },

    selectPage: function(page) {
        var query = this.currentQuery.copy();
        query.page = page;
        this.loadQuery(query);
    },

    loadQuery: function(query) {
        //console.debug("loadQuery");
        var hash = "q=" + this._encodeQuery(query.q);
        if (query.qf) {
            hash += "/qf=" + query.qf;
        }
        if (query.page) {
            hash += "/page=" + query.page;
        }
        if (query.limit) {
            hash += "/limit=" + query.limit;
        }
        if (query.sort) {
            hash += "/sort=" + query.sort;
        }
        for (var key in this.options) {
            if (query.options[key]) {
                var option = this.options[key];
                if ("tag" == option.type) {
                    $.each(query.options[key], function() {
                        hash += "/opt_" + key + "=" + Searcher._encodeQuery(this);
                    });
                } else {
                    hash += "/opt_" + key + "=" + this._encodeQuery(query.options[key]);
                }
            }
        }
        $.historyLoad(hash);
    },
    
    loadedQuery: function(query) {
    },

    loadPage: function(hash) {
        //console.debug("loadPage " + hash);
        if (hash.length > 0) {
            var data = hash.split(/\//);
            var query = new this.Query();
            var COOKIE_NAME = "search";
            
            for (var i = 0; i < data.length; i++) {
                var pair = data[i].split(/=/);
                var key = pair[0];
                //console.debug("pair[1]=" + pair[1]);
                var value = this._decodeQuery(pair[1]);
                query.loadParam(key, value);
            }
            /*
            if (query.q == null || query.q.length == 0) {
                return;
            }
            */
            $(this.queryElement).attr("value", query.q);
            $(this.html.query_label).text(query.q);
            if (query.qf) {
                $(this.html.select_qf).attr('value', String(query.qf));
            }
            if (query.limit) {
                $(this.html.select_limit).attr('value', String(query.limit));
            }
            if (query.sort) {
                $(this.html.select_sort).attr('value', String(query.sort));
            }
            this.loadedQuery(query);

            query.c = $.cookie(COOKIE_NAME);
            if (null == query.c) {
                var expire = new Date();
                expire.setTime(expire.getTime() + (1000 * 60 * 60 * 24 * 365 * 2));
                query.c = (parseInt(Math.random()*100000000000)).toString();
                $.cookie(COOKIE_NAME, 
                         query.c,
                         {expires: expire});
            }
            //console.debug("loadPage", query);
            this.loadingPage = 0;
            this.search(query);
        }
    },

    callback: function(response) {
        try {
            this._doCallback(response);
        } catch (e) {
            var msg = e.toString();
            if (e.stack) { // Firefox
                msg += "\n" + e.stack;
            }
            this.logError(msg);
            this.searchFailed();
        }
    },
    
    config: function(config) {
        $.extend(true, this, config);
    },

    init: function(config) {
        this.config(config);
        this.initialized = true;
        
        $.historyInit(function(data) {
            Searcher.loadPage(data);
        }, this.history_src);
        
        var self = this;
        for (var key in this.options) {
            (function(){
                var dupKey = key;
                var opt = self.options[key];
                if ("tag" == opt["type"]) {
                    $(opt["selector"]).bind("click", function(e) {
                        var tag = e.target;
                        while (tag != this) {
                            if ($(tag).hasClass("_search_tag")) {
                                if ($(tag).hasClass("_search_tag_all")) {
                                    Searcher.selectTag(dupKey, null);
                                } else {
                                    Searcher.selectTag(dupKey, $(tag).find("._search_tag_name").text());
                                }
                                e.preventDefault();
                                break;
                            }
                            tag = tag.parentNode;
                        }
                    });
                } else if ("slider" == opt["type"]) {
                    self.sliders[dupKey] = new Searcher.Slider(dupKey, opt);
                }
            })();
        }

        if (this.autoScroll) {
            $(window).scroll(function() {
                if (!self.loading) {
                    var bottom = $(window).scrollTop() + $(window).height();
                    self.log("bottom", bottom);
                    self.log("offset", self.nextPageIndicatorOffset);
                    if (self.nextPageIndicatorOffset >= 0 && bottom >= self.nextPageIndicatorOffset) {
                        self.log("loading next page");
                        self.autoScroll();
                    }
                }
            });
        }
        /*
		$('#date_slider').slider({
			range: true,
			values: [17, 67]
		});
        */
    },

    Slider: function(name, opt) {
        this.name = name;
        this.selector = opt["selector"];
        this.valueType = opt["value_type"];
        var sliderOpt = opt["slider_options"] || {};
        var self = this;
        this.sliderElement().slider($.extend({
            range: true, 
            values: [0, 100],
            slide: function(event, ui) {
                self.updateLabel();
            },
            change: function(event, ui) {
                self.search();
            }
        }, sliderOpt));
        
    },

    Query: function(params) {
        this.options = {};
        this.limit = 10;
        if (params) {
            for (var key in params) {
                if ("options" == key) {
                    for (var key2 in params.options) {
                        this.options[key2] = params.options[key2];
                    }
                } else {
                    this[key] = params[key];
                }
            }
        }
    }
}

Searcher.Query.VALID_KEYS = ["q", "page", "c", "limit", "sort", "qf"];

Searcher.Query.prototype = {
    keywordOnly: function() {
        var len = 0;
        for (var key in this.options) {
            len++;
        }
        return (!this.page || this.page == 1) && 0 == len;
    },
    
    encodeParams: function() {
        var self = this;
        var pq = {};
        $.each(Searcher.Query.VALID_KEYS, function() {
            var key = this;
            var value = self[key];
            if (value) {
                pq[key] = value;
            }
        });
        for (var key in self.options) {
            var value = self.options[key];
            if (jQuery.isArray(value)) {
                pq["opt_" + key + "[]"] = value;
            } else {
                pq["opt_" + key] = value;
            }
        }
        return $.param(pq);
    },
    
    loadParam: function(key, value) {
        //console.debug("loadParam(" + key + ", " + value + ")");
        var match = /^opt_(.*)/.exec(key);
        if (match && match[1]) {
            var optionName = match[1];
            var option = Searcher.options[optionName];
            if ("tag" == option.type && !$.isArray(value)) {
                if (!this.options[optionName]) this.options[optionName] = [value];
                else this.options[optionName].push(value);
            } else {
                this.options[optionName] = value;
            }
        } else {
            this[key] = value;
        }
    },

    copy: function() {
        return new Searcher.Query(this);
    }
}

Searcher.Slider.prototype = {
    updateLabel: function() {
        var range = this.range();
        if (!range) range = this.fullRange;
        if (range) {
            $(this.selector).find(Searcher.html.slider_label).text(
                this.formatLabel(range[0]) + " - " + this.formatLabel(range[1]));
        }
    },

    search: function() {
        if (this.updatingSlider) return;
        var query = Searcher.currentQuery.copy();
        query.page = null;
        var range = this.range();
        if (range) {
            query.options[this.name] = this.formatValue(range[0]) + "~" + this.formatValue(range[1]);
        } else {
            delete query.options[this.name];
        }
        Searcher.loadQuery(query);
    },
    
    sliderElement: function() {
        return $(this.selector).find(Searcher.html.slider);
    },
    
    parseDate: function(text) {
        if (text.match(/(\d{4})-(\d{2})-(\d{2})/)) {
            return Date.UTC(parseInt(RegExp.$1, 10), parseInt(RegExp.$2, 10) - 1, parseInt(RegExp.$3, 10));
        } else {
            return parseInt(text);
        }
    },

    parseValue: function(value) {
        if ("date" == this.valueType) {
            return this.parseDate(value);
        } else {
            return parseFloat(value);
        }
    },
    
    setFullRange: function(range) {
        //console.debug(this.name, range);
        this.fullRange = [this.parseValue(range[0]), this.parseValue(range[1])];
        this.updateLabel();
    },

    loadQuery: function() {
        this.updatingSlider = true;
        var opt = Searcher.currentQuery.options[this.name]
        var min = 0;
        var max = 100;
        if (opt && opt instanceof Array) {
            opt = opt[0];
        }
        if (opt) {
            var range = opt.split("~");
            var full = this.fullRange;
            if (full) {
                min = (this.parseValue(range[0]) - full[0]) / (full[1] - full[0]) * 100;
                max = (this.parseValue(range[1]) - full[0]) / (full[1] - full[0]) * 100;
            }
        }
        this.sliderElement().slider('values', 0, min);
        this.sliderElement().slider('values', 1, max);
        this.updateLabel();
        this.updatingSlider = false;
    },

    range: function() {
        var full = this.fullRange;
        if (full) {
            var min = this.sliderElement().slider('values', 0);
            var max = this.sliderElement().slider('values', 1);
            if ((min == 0 && max == 100) || full[0] == full[1]){
                return null;
            } else {
                var vmin = full[0] + min / 100 * (full[1] - full[0]);
                var vmax = full[0] + max / 100 * (full[1] - full[0]);
                return [vmin, vmax];
            }
        } else {
            return null;
        }
    },
    
    formatValue: function(value) {
        if ("date" == this.valueType) {
            var date = new Date();
            date.setTime(value);
            return date.getFullYear() + "-" + Searcher.formatTwoDigits(date.getMonth() + 1) + "-" + Searcher.formatTwoDigits(date.getDate());
            //return value;
        } else {
            return value;
        }
    },

    formatLabel: function(value) {
        return this.formatValue(value);
    }
}
