//
// Copyright (c) 2007-2010 Business Search Technologies Corporation
// $Id: popterm.base.js,v 1.6 2011/02/21 09:25:34 nakajo Exp $
//

//
// popTerm class
//
function popTerm(param){
    //
    // configurable property
    //
    this.request_url = "http://search.bsearchtech.com/popterm/popterm.pl"; // uri
    this.juid = "fc819f8c0bcaf08fbedd4677fabcc77e244c211e"; // juid
    this.pick_interval = 200; // 0.2 sec for next char, 0.4 sec for request
    this.pop_max_items = 10;  // items to be displayed

    //
    // unique property (do not change)
    //
    this.service = param.service;
    this.trid = param.trid;
    this.ppid = param.form; // uniq id for this object
    if (this.trid == null){
        this.trid = 0;
    }

    // display count flag and disable popterm flag
    this.show_count = param.show_count;
    if (this.show_count == null) {
        this.show_count = 0;
    }
    this.show_disable = param.show_disable;
    if (this.show_disable == null) {
        this.show_disable = 0;
    }
    this.fit_width = param.fit_searchbox_width;
    if (this.fit_width == null) {
        this.fit_width = 0;        
    }
    this.bgc = param.background_color;
    if (this.bgc == null) {
        // configurable popTerm css
        var bgc = $('body').css('background-color');
        if (bgc == 'transparent'){
            bgc = '#fff';
        }
        if (bgc == 'rgba(0, 0, 0, 0)') {
            bgc = '#fff';
        }
        this.bgc = bgc;
    }
    var popTermAreaCSS = {
        'position': 'relative'
    };
    var popTermSelectionCSS = {
        'position': 'absolute',
        'background-color': this.bgc,
        'z-index': '99',
        'font-size':'80%'
    };

    //
    // dereference
    //
    var aname  = 'popTermArea'; // area including input text
    var sname  = 'popTermSelection'; // listing table for popup
    var idform = "#" + param.form;
    var idsel  = "#" + param.form + sname; //idsbox
    var sarea  = "#" + param.form + ' .' + aname;
    var stext  = "#" + param.form + ' .' + aname + " input[type='text']";
    var self = this;
    this.idform = idform;
    this.idsel  = idsel;
    this.idtext = stext;
    this.aname = aname;
    this.sname = sname;

    //
    // properties
    //
    this.pop_items = -1;
    this.kid = null; // key input
    this.pid = null; // popup
    this.leadstr = null;
    this.selected = -1;
    this.in_sbox = 0;
    this.enabled = 1;

    //
    // browser check
    //
    var ua = navigator.userAgent;
    if (/msie/i.test(ua)){
        this.browser = 'IE';
    }else if (/firefox/i.test(ua)){
        this.browser = 'firefox';
    }else if (/chrome/i.test(ua)){
        this.browser = 'chrome';
    }else if (/safari/i.test(ua)){
        this.browser = 'safari';
    }else if (/opera/i.test(ua)){
        this.browser = 'opera';
    }

    //
    // initialize
    //
    this.popTermArea = $(sarea);
    this.popTermArea
        .css(popTermAreaCSS)
        .after('<table class="'+sname+'" id="'+this.ppid+sname+'"></table>'); // create selection box
    this.popTermText = $(stext);
    this.popTermSelection = $(idsel);

    this.popTermSelection
        .css(popTermSelectionCSS)
        .mouseover(
            function(){
                self.in_sbox=1;
            })
        .mouseout(
            function(){
                self.in_sbox=0;
            })
        .hide();
    this.popTermText
        .attr('autocomplete', 'off')
        .focus(
            function(){
                if (self.enabled == 1){
                    self.popTermSelection.fadeIn(50);
                    self.start();
                }
            })
        .blur(
            function(ev){
                if (self.in_sbox == 0){
                    self.popTermSelection.fadeOut(50);
                    self.stop();
                }
            });

    var keyin = function(e){
        if (e.keyCode == 27){ // escape
            self.popTermSelection.fadeOut(50);
            if (self.browser == 'IE'){
                return false;
            }
            return true;
        }else if (e.keyCode == 38){ // up
            if (self.selected > 0){
                var el = '#' + self.ppid + 'popTermD' + self.selected;
                $(el).css({'background-color': self.bgc,
                           'color': 'black'});
                self.selected--;
                el = '#' + self.ppid + 'popTermD' + self.selected;
                $(el).css({'background-color': '#666',
                           'color': 'white'});
            }
        }else if (e.keyCode == 40){ // down
            if (self.selected < self.pop_items-1){
                var el = '#' + self.ppid + 'popTermD' + self.selected;
                $(el).css({'background-color': self.bgc,
                           'color': 'black'});
                self.selected++;
                el = '#' + self.ppid + 'popTermD' + self.selected;
                $(el).css({'background-color': '#666',
                           'color': 'white'});
            }
        }else if (e.keyCode == 39 || e.keyCode == 13){ // right or enter
            if (self.selected == -1){
                return true;
            }
            var el = '#' + self.ppid + 'popTermD' + self.selected;
            self.popTermText.val($(el).text());
            self.selected = -1;
        }
        return true;
    };

    if (this.browser == 'IE' || this.browser == 'chrome' || this.browser == 'safari'){
        this.popTermText.keydown(keyin);
    }else{
        this.popTermText.keypress(keyin);
    }
};

//
// method
//
popTerm.prototype = {
    popup_withoutxhr: function(str){
        // Without XMLHttpRequest; with JSONP
        var self = this;
        var cb = 'popterm_noxhr_callback';
        var rurl = this.request_url +
            '?callback=' + cb +
            '&trid=' + self.trid + '&k=' + encodeURIComponent(str) + '&c=' + self.pop_max_items;

        window[cb] = function(res){
            self.popup_callback(self, res);
        };
        // $('head').append('<script type="text/javascript" src="' + rurl + '" />');
        var sc = document.createElement("script");
        sc.setAttribute("type", "text/javascript");
        sc.setAttribute("charset", "utf-8");
        sc.setAttribute("src", rurl);
        var hh = document.getElementsByTagName("head")[0];
        hh.appendChild(sc);
    },
    popup_withxhr: function(str){
        // with XMLHttpRequest
        var self = this;
        var trid = this.trid;
        var rurl = this.request_url;
        $.ajax({
            dataType: "jsonp",
            data:{trid: trid, k: str, c: self.pop_max_items},
            cache: true,
            url: rurl,
            success: function(res){
                self.popup_callback(self, res);
            }
        });
    },
    start: function(first){
        var self = this;

        // initialize position
        var pttop = this.popTermText.offset().top + this.popTermText.outerHeight({margin: true});
        var ptleft = this.popTermText.offset().left + 2;
        var ptwidth = this.popTermText.innerWidth();
        if (this.fit_width == 1) {
            this.popTermSelection.css({'top': pttop + 'px', 'left': ptleft + 'px', 'width': ptwidth + 'px'});
        } else {
            this.popTermSelection.css({'top': pttop + 'px', 'left': ptleft + 'px'});
        }

        var str = this.popTermText.val();

        if (str == null || str == ''){
            this.popTermSelection.fadeOut(50);
        }else if (str == this.leadstr){
        }else{
            if (this.pid != null){
                clearTimeout(this.pid);
            }
            // choose either popup_withxhr or popup_withoutxhr
            this.pid = setTimeout(function(){self.popup_withoutxhr(str);}, this.pick_interval * 2);
            // this.pid = setTimeout(function(){self.popup_withxhr(str);}, this.pick_interval * 2);
        }
        this.leadstr = str;
        this.kid = setTimeout(function(){self.start();}, this.pick_interval);
    },
    stop: function(){
        if (this.kid != null){
            clearTimeout(this.kid);
            this.tid = null;
        }
        if (this.pid != null){
            clearTimeout(this.pid);
            this.pid = null;
        }
    },
    disable: function(){
        this.stop();
        this.enabled = 0;
    },
    popup_callback: function(self, res){
        var idform = self.idform;
        var popTermSelection = self.popTermSelection;
        var popTermText = self.popTermText;
        if (res.list == null){
            return;
        }
        popTermSelection.empty();
        var r;
        var n=0;
        for (var x in res.list){
            r = r || res.list[x][1];
            var rate = (res.list[x][1]/r) * 100;
            if (this.show_count == 1) {
                popTermSelection.append('<tr class="popTermItem">'+
                                        '<td id="' + self.ppid + 'popTermD' + n + '"' +
                                        ' style="text-align:left">' + res.list[x][0] + '</td>' +
                                        '<td style="text-align:right">' + res.list[x][1] + '</td></tr>');
            } else {
                popTermSelection.append('<tr class="popTermItem">'+
                                        '<td id="' + self.ppid + 'popTermD' + n + '"' +
                                        ' style="text-align:left">' + res.list[x][0] + '</td></tr>');
            }
            $('#'+self.ppid+'popTermD'+n)
                .dblclick(
                    function(){
                        popTermText.val($(this).text());
                        $(idform).submit();
                    })
                .click(
                    function(ev){
                        if (ev.detail && ev.detail != 1) return;
                        popTermText.val($(this).text());
                    })
                .hover(
                    function(){
                        var el = '#' + self.ppid + 'popTermD' + self.selected;
                        $(el).css('background-color', self.bgc)
                            .css('color', 'black');
                        self.selected = n;
                        $(this)
                            .css('background-color', 'black')
                            .css('color', 'white');},
                    function(){
                        $(this)
                            .css('background-color', self.bgc)
                            .css('color', 'black');});
            n++;
        }
        if (this.show_disable == 1) {
            popTermSelection.append('<tr><td colspan="2" id="'+self.ppid+
                                    'popTermDisable">disable popTerm</td></tr>');
        }
        $('#'+self.ppid+'popTermDisable').click(
            function(){
                self.disable();
                popTermSelection.fadeOut(50);
            });
        self.pop_items = n;
        popTermSelection.fadeIn(100);
    }
};

