//@charset "utf-8";
/**
 * 股票代码键盘精灵实现类
 * author 梁威<liangwei@myhexin.com>
 * create 2009-11-26
 */
var JpjlModel = Class.extend({
    /**
     * 构造函数
     * @param {String}  inputSelector   股票代码输入框选择符
     * @param {String}  addBtnSelector  股票代码添加按钮选择符
     * @param {Integer} showListNum     用于提示的代码数量
     */
     init : function(inputSelector, addBtnSelector, showListNum, markets, stockclass) {
        this._inputSelector     = inputSelector;
        this._addBtnSelector    = addBtnSelector;
        this._showListNum       = showListNum || 10;
        this._markets			= markets;
        this._stockclass		= stockclass;
        try {
        	this._thsUtil       = external.createObject('Util');
        } catch(e) {
        	return;
        }
        this._windowResize      = null;
        this._windowScroll      = null;
    }

    ,destroy : function() {
        this._inputSelector     = null;
        this._addBtnSelector    = null;
        this._showListNum       = null;
        this._markets			= null;
        this._stockclass		= null;
        this._thsUtil           = null;
        this._windowResize      = null;
        this._windowScroll      = null;
    }
    
    /**
     * 用于渲染股票代码的键盘精灵
     */
    ,render : function() {
        var $autocomplete = $('<ul class="autocomplete br"></ul>').hide()
				.appendTo('body');
        
        var self = this;
        //改变窗口大小动作
        $(window).resize(function() {
            if (self._windowResize) {
                return;
            }
            self._windowResize = setTimeout(function() {
                var $inputEl      = $(self._inputSelector);
                var inputElPosObj = $inputEl.offset();
                var totalHeight	  = $(window).height();
                var autoCompleteH = self._showListNum * 20;
                var scrollTop = document.documentElement.scrollTop;
                //加上滚动条位置
                if (totalHeight - inputElPosObj.top - $inputEl.height() + scrollTop < autoCompleteH) {
					self.position = 'up';
                	var top = inputElPosObj.top - autoCompleteH - 21 + 'px';
                } else {
					self.position = 'down';
                	var top = inputElPosObj.top + $inputEl.height() + 2 + 'px';
                }
                $autocomplete.css({
                    left : inputElPosObj.left - 1 + 'px',
                    top  : top
                });
                self._windowResize = null;
            }, 200);
        }).trigger('resize');
        //页面滚动动作
        $(window).scroll(function() {
            if (self._windowScroll) {
                return;
            }
            self._windowScroll = setTimeout(function() {
                var $inputEl      = $(self._inputSelector);
                var inputElPosObj = $inputEl.offset();
                var totalHeight	  = $(window).height();
                var autoCompleteH = self._showListNum * 20;
                var scrollTop = document.documentElement.scrollTop;
                if (totalHeight - inputElPosObj.top - $inputEl.height() + scrollTop < autoCompleteH) {
					self.position = 'up';
                	var top = inputElPosObj.top - autoCompleteH - 21 + 'px';
                } else {
					self.position = 'down';
                	var top = inputElPosObj.top + $inputEl.height() + 2 + 'px';
                }
                $autocomplete.css({
                    left : inputElPosObj.left - 1 + 'px',
                    top  : top
                });
                self._windowScroll = null;
            }, 200);
        }).trigger('scroll');

        var selectedItem = null;
        var setSelectedItem = function(item) {
            selectedItem = item;
            if (selectedItem === null) {
                $autocomplete.hide();
                return;
            }
            if (selectedItem < 0) {
                selectedItem = 0;
            }
            var maxLength = $autocomplete.find('li').length - 1;
            if (selectedItem > maxLength) {
                selectedItem = maxLength;
            }
            $autocomplete.find('li').removeClass('selected')
                    .eq(selectedItem).addClass('selected');
			if (self.position && self.position == 'up') {
				var $inputEl	= $(self._inputSelector);
				var inputTop	= $inputEl.offset().top;
				var num			= $autocomplete.find('li').length;
				var top			= inputTop - num * 20 - 21;
				$autocomplete.css({top: top});
			}
            $autocomplete.show();
        };

        var populateSearchField = function() {
            var str = $autocomplete.find('li').eq(selectedItem).find('strong').text();
            $(self._inputSelector).val(str);
            setSelectedItem(null);
           
            //changed by fb for twice to once
            $(self._addBtnSelector).trigger('click');
            //changed end
        };

        $(this._inputSelector).keyup(function(event) {
            // Keys with codes 40 and below are special (enter, arrow keys, escape, etc.).
            // Key code 8 is backspace.
            if ((event.keyCode > 40 || event.keyCode == 8 || event.keyCode == 32)) {
                var val = $(this).val();
                if(val.length > 0 && val.length < 7){
                    var data = self._thsUtil.filterStock({filter : val, count : self._showListNum, markets : self._markets, stockclass : self._stockclass});
                    data = data.replace(/(\w)'(\w)/g, "$1\\'$2");
                    data = eval('(' + data + ')');
//                    alert(data);return;
                    if (data && data.length) {
                        $autocomplete.empty();
                        $.each(data, function(index) {
                            var elCnt = '<strong>' + this.stock + '</strong><span>' + this.name + '</span>' + this.py;
                            $('<li></li>').html(elCnt).appendTo($autocomplete).mouseover(function() {
                                setSelectedItem(index);
                            }).click(populateSearchField);
//                            var maxLiWidth = 200;
//                            $autocomplete.find('li').css('width', 'auto').each(function() {
//                                var liWidth = $(this).width();
//                                if (liWidth > maxLiWidth) {
//                                    maxLiWidth = liWidth;
//                                }
//                            });
//                            $autocomplete.find('li').css('width', maxLiWidth + 'px');
                        });
                        setSelectedItem(0);
                    } else {
                        setSelectedItem(null);
                    }
                } else {
                    setSelectedItem(null);
                }
            } else if (event.keyCode == 38 && selectedItem !== null) {// User pressed up arrow.
                setSelectedItem(selectedItem - 1);
                event.preventDefault();
            } else if (event.keyCode == 40 && selectedItem !== null) {// User pressed down arrow.
                setSelectedItem(selectedItem + 1);
                event.preventDefault();
            } else if (event.keyCode == 27 && selectedItem !== null) {// User pressed escape key.
                setSelectedItem(null);
            }
        }).keydown(function(event) {
            if (event.keyCode == 13) {// User pressed enter key.
                if (selectedItem !== null) {
                    populateSearchField();
                    event.preventDefault();
                } else {
                    if (self._addBtnSelector) {
                        $(self._addBtnSelector).trigger('click');
                    }
                    var rel = $(self._inputSelector).get(0);
                    var rng = rel.createTextRange();
                    rng.moveStart('character', 0);
                    rng.select();
                    delete rng; rng = null;
                    delete rel; rel = null;
                }
            }
        }).blur(function(event) {
            setTimeout(function() {
                setSelectedItem(null);
            }, 250);
        });
    }

    /**
     * 用于获得股票代码输入框内所属如代码的详细信息对象
     * @return {Object}
     */
    ,getInputCodeData : function() {
        var  val = $(this._inputSelector).val();
        if (!val.length) {
            return null;
        }
        var data = this._thsUtil.filterStock({filter : val, count : 1, markets : this._markets, stockclass : this._stockclass});
        data = eval('(' + data + ')');
        if (data && data.length == 1) {
            return {stock : data[0].stock, name : data[0].name};
        }
        return null;
    }
});
