/*
 * @(#)jQuery.CEA.SelectCity.js
 *       
 * 系统名称：东航电子商务国内B2C系统
 * 版本号：1.0
 * 
 * Copyright (c)  TravelSky
 * All Rights Reserved.
 * 
 * 作者：bjiang
 * 创建日期：Nov 4, 2009
 * 
 * 功能描述：城市先择器
 *      需要DWR支持.
 *      需要Cookies支持.
 * 公用方法描述：
 *      $('#fromcity').jSelectCity({tips:''});
 *    
 * 修改人：
 * 修改日期：
 * 修改原因：
 * 
 * 
 */
 
 //请求支持库
if(typeof CityList === 'undefined')
{
 $.ajax({
    type:"GET",
    url:'/mu/dwr/interface/CityList.js',
    async: false,
    dataType:'script'
    });
}

(function($)
{
   var allcity_CN = null;
   var allcity_OT = null;
   var allcity = null;
   var HotCity_CN = null;
   var HotCity_OT = null;
   $.fn.jSelectCity = function(options)
   {
        var defaultop = {
            Adjacent: 'E',
            defaultHotCity: '',
            tips: '',
            $from: null,
            $international: null,
            noAirport:false
        };
        
        //成员变量
        var config = $.extend(defaultop, options);
        var $this = $(this);
        var windowid = 'selectcity';
        var CityData = null;
        var HotCity = null;
        var fromCity = '';
        //var refreshcachetimer = null;
        var International = 0;
        var getInternational = function()
        {
            if(config.$international!=null && config.$international.attr('checked') == true)
            {
                return  1;
            }
            return 0;
        };
        //显示位置
        var getXY = function(obj)
        {
            var hight = 156;
            var width = 260;
            switch (config.Adjacent)
            {
            case 'T':
                return {
                    top: $(obj).offset().top - hight,
                    left: $(obj).offset().left
                };
            case 'E':
                return {
                    top: $(obj).offset().top + $(obj).height()+4,
                    left: $(obj).offset().left
                };
            case 'R':
                return {
                    top: $(obj).offset().top,
                    left: $(obj).offset().left + $(obj).width()
                };
            case 'L':
                return {
                    top: $(obj).offset().top,
                    left: $(obj).offset().left - width
                };
            case 'TL':
                return {
                    top: $(obj).offset().top - hight,
                    left: $(obj).offset().left - width
                };
            case 'EL':
                return {
                    top: $(obj).offset().top + $(obj).height(),
                    left: $(obj).offset().left - width
                };
            case 'TR':
                return {
                    top: $(obj).offset().top - hight,
                    left: $(obj).offset().left + $(obj).width()
                };
            case 'ER':
                return {
                    top: $(obj).offset().top + $(obj).height(),
                    left: $(obj).offset().left + $(obj).width()
                };
            default:
                return {
                    top: $(obj).offset().top + $(obj).height(),
                    left: $(obj).offset().left
                };
            }
        };
        //设置城市信息
        var setCityinfo = function($dom,_3CODE,text)
        {
            $dom.attr('_3CODE',_3CODE);
            $dom.val(text);
            $dom.change();
        };
        /*
         * 取城市列表
         * async:
         *      true    异步请求
         *      false   同步请求
         */
        var getCityData = function()
        {
            DWREngine.setAsync(false);
            //计算需要什么城市列表
            if(config.noAirport)
            {
                if(fromCity == "")
                {
                    CityList.getCityView(function(data)
                    {
                        CityData = data;
                    });
                }
                else
                {
                    CityList.getCityViewto(fromCity,function(data)
                    {
                        CityData = data;
                    });                    
                }
                DWREngine.setAsync(true);
                return;
            }
            
            
            //检测国际标记
            var getInter = 0;
            if(config.$international!=null&&config.$international.attr('checked')==true)
            {
                getInter = 1;
            }
            //检测是否始发城市
            if(config.$from == null)
            {
                getInter = 0;
            }
            
            if (fromCity == '')
            {
                switch(getInter)
                {
                    case 0:
                    {
                        CityData = allcity_CN;
                        break;
                    }
                    case 1:
                    {
                        CityData = allcity_OT;
                        break;
                    }
                }
                if(CityData == null)
                {
                    CityList.getCitylist(getInter,
                    function(data)
                    {
                        CityData = data;
                        switch(getInter)
                        {
                            case 0:
                            {
                                allcity_CN = CityData;
                                break;
                            }
                            case 1:
                            {
                                allcity_OT =  CityData;
                                break;
                            }
                        }
                    });
                }

            }
            else
            {
                CityList.getCityto(International, fromCity,
                function(data)
                {
                    if(data == null)
                    {
                        data = '';
                    }
                    CityData = data;
                });
            }
            DWREngine.setAsync(true);
        };
        /*
         * 取热点城市
         * async:
         *      true    异步请求
         *      false   同步请求
         */
        var getHotCity = function()
        {
            var URL = '/mu/images/hotcity_CN.data';
            switch(International)
            {
                case 0:
                {
                    HotCity = HotCity_CN;
                    URL = '/mu/images/hotcity_CN.data';
                    break;
                }
                case 1:
                {
                    HotCity = HotCity_OT;
                    URL = '/mu/images/hotcity_OT.data';
                    break;
                }
            }
            if(HotCity==null)
            {
                $.ajax({
                    //取缓存数据
                    cache: true,
                    async: false,
                    url: URL,
                    success: function(date)
                    {
                        HotCity = date.match(/[^,]*,/ig);
                        for (var i = 0; i < HotCity.length; i++)
                        {
                            HotCity[i] = HotCity[i].split('|');
                        }
                        switch(International)
                        {
                            case 0:
                            {
                                HotCity_CN = HotCity;
                                break;
                            }
                            case 1:
                            {
                                HotCity_OT =  HotCity;
                                break;
                            }
                        }
                    }
                });
            }
        };
        
        /*
         * 构造title
         */
        var createTitle = function(current)
        {
            //生成对像
            var $title;
            if (config.$from == null)
            {
                $title = $('<a id="hotcity" href="#" title="热门城市">热门城市</a><a id="allcity" href="#" title="所有城市">所有城市</a>');
        
                //添加事件
                $title.eq(0).click(function()
                {
                    $.msgbox.closemsgbox(windowid);
                    show($this, createTitle('hotcity'), hotCityData());
                    return false;
                });
                $title.eq(1).click(function()
                {
                    $.msgbox.closemsgbox(windowid);
                    //show($this, createTitle('allcity'), allCityData($this.val() == config.tips ? '': $this.val()));
                    show($this, createTitle('allcity'), allCityData(''));
                    return false;
                });
               
                if(current === 'allcity')
                {
                    $title.eq(1).addClass('current');
                }
                else
                {
                    $title.eq(0).addClass('current');
                }
            }
            else
            {
                $title = $('<a id="hotcity" class="current" href="#" title="所有城市">所有城市</a>');
                $title.click(function()
                {
                    $.msgbox.closemsgbox(windowid);
                    //show($this, createTitle('allcity'), allCityData($this.val() == config.tips ? '': $this.val()));
                    show($this, createTitle('allcity'), allCityData(''));
                    return false;
                });
            }
            return $title;
        };
        var GetCityAnd3Code = function(ar)
        {
            var _3CODE = ar[4];
            var city='';
            if(config.noAirport===true)
            {
                _3CODE = ar[0].replace(/,/,'');
                city = ar[1];
                if(ar[4]==='PVG')
                {
                    return;
                }
            }
            else
            {
                var jc = ar[5].replace(ar[1],'').trim().replace(',','');
                city = ar[1] + (jc.length>0?'('+(jc==='机场'?ar[5]:jc).replace(',','')+')':'');
            }
            if(ar.length>6)
            {
                city = ar[6].trim().replace(',','') + ',' + city;
            }
            return {
                _3CODE:_3CODE,
                city:city
            };
        };
        /*
         * 构造热点城市列表
         */
        var hotCityData = function()
        {
            //构造对像
            var $hotcity = $('<ul id="hotcitys"></ul>');
            for (var i = 0; i < HotCity.length && i < 12; i++)
            {
                var city = GetCityAnd3Code(HotCity[i]);
                if(city === undefined)
                {
                    continue;
                }
                $hotcity.append('<li _3CODE="' + city._3CODE + '">' + city.city + '</li>');
            }
            
            //添加事件
            $hotcity.find('li').click(function()
            {
                var _3CODE = $(this).attr('_3CODE');
                setCityinfo($this,_3CODE,$(this).text());
                $this.attr('_show','');
                $.msgbox.closemsgbox(windowid);
            });
            
            return $hotcity;
        };
        
        /*
         * 构造城市列表
         */
        var allCityData = function(select)
        {
            if(CityData==null)
            {
                getCityData();
            }
            var $allcity = null;
            var sel = '';
            if (!(select == null || select == ''))
            {
                sel = '<div id="searchmessage">' + select + ', 按拼音排序</div>';
            }
            sel += '<div id="resultcitys">';
            var ar = SelectCity(select, CityData);
            for(i in ar)
            {
                try
                {
                    var pinYin = ar[i][2];
                    var city = GetCityAnd3Code(ar[i]);
                    sel += '<a href="#" _3CODE="' + city._3CODE + '"><span>' + pinYin + '</span>' + city.city + '</a>';
                }
                catch(e)
                {
                    
                }
            }
            sel += '</div>';
            $allcity = $(sel);
            $allcity.find('a:first').css({'background':'#e7f1fd 0px 0px'});
            $allcity.find('a:first').attr('sel','sel');
            if(ar==null)
            {
                $allcity=$('<div id="searchmessage">对不起，找不到：'+select+'</div>');
            }
            
            //添加事件
            $allcity.find('a[_3CODE]').click(function()
            {
                var _3CODE = $(this).attr('_3CODE');
                setCityinfo($this,_3CODE,this.lastChild.nodeValue);
                $this.attr('_show','');
                $.msgbox.closemsgbox(windowid);
                return false;
            });
            
            return $allcity;
        };
        
        //正则查找
        var SelectCity = function(select, data)
        {
            select = select.replace(/\(.*/,'');
            select = select.replace(/[^,].*,/,'');
            select = select.replace('主站','');
            var slrg = new RegExp('(?:,|^)(?:|[^,]*\\|)' + select + '[^,]*?(?=,)', 'ig');
            var out = data.match(slrg);
    
            if (out != null)
            {
                out = out.slice(0, out.length);
            }
            for (i in out)
            {
                out[i] = out[i].split('|');
            }
            
            //排序
            if (out != null)
            {
                out.sort(function(a, b)
                {
                    if (a[2] > b[2])
                    {
                        return 1;
                    }
                    else if (a[2] < b[2])
                    {
                        return - 1;
                    }
                    else
                    {
                        return 1;
                    }
                });
                //后保留前10条数据
                //out = out.slice(0, out.length > 10 ? 10 : out.length);
            }
    
            return out;
        };
        //显示列表
        var show = function(obj, $title, $content)
        {
            var position = getXY(obj);
            var $popwin = $.msgbox.msgbox(windowid, 250, 100, $title, $content).css({
                'top': position.top + 'px',
                'left': position.left + 'px'
            }).addClass('popwin_' + windowid);
            return $popwin;
        };
        //事件绑定
        $this.click(function()
        {
            //标记已显示列表
            $this.attr('_show','show');
            //
            if($this.val() == config.tips)
            {
                $this.val('');
            }
            //检测是否需要更新数据
            var reloadcity = false;
            if(config.$from != null)
            {
                if(config.$from.attr('_3CODE')!=fromCity)
                {
                    fromCity = config.$from.attr('_3CODE');
                    reloadcity = true;
                }
            }
            
            if(International != getInternational())
            {
                International = getInternational();
                reloadcity = true;
            }
            
            if(reloadcity == true)
            {
                $this.val('');
                getHotCity();
                getCityData();
            }
            
            //显示列表
            if ($(this).val() != '' &&  $(this).val() != config.tips || config.$from!=null)
            {
                show($this, createTitle('allcity'), allCityData($this.val()==config.tips?'':$this.val()));
            }
            else
            {
                show($this, createTitle('hotcity'), hotCityData());
            }
            return false;
        });
        $this.bind('keyup',function(Key)
        {
            switch(Key.keyCode)
            {
                case 40:
                {
                    var $sel = $('#resultcitys > a[sel="sel"]');
                    if($sel.length==0)
                    {
                        $('#resultcitys > a:first').css({background:'#e7f1fd 0px 0px'});
                        $('#resultcitys > a:first').attr('sel','sel');
                    }
                    else
                    {
                        if($sel.next().length != 0)
                        {
                            $sel.css({background:''});
                            $sel.next().css({background:'#e7f1fd'});
                            $sel.attr('sel','');
                            $sel.next().attr('sel','sel');
                        }
                    }
                    break;
                }
                case 38:
                {
                    var $sel = $('#resultcitys > a[sel="sel"]');
                    if($sel.length==0)
                    {
                        $('#resultcitys > a:first').css({background:'#e7f1fd 0px 0px'});
                        $('#resultcitys > a:first').attr('sel','sel');
                    }
                    else
                    {
                        if($sel.prev().length != 0)
                        {
                            $sel.css({background:''});
                            $sel.prev().css({background:'#e7f1fd'});
                            $sel.attr('sel','');
                            $sel.prev().attr('sel','sel');
                        }
                    }
                    break;                    
                }
                case 13:
                {
                    break;
                }
                default:
                {
                    $.msgbox.closemsgbox(windowid);
                    show($this, createTitle('allcity'), allCityData($this.val()==config.tips?'':$this.val()));
                    break;
                }
            }
            return false;
        });
        $this.bind('keydown',function(key)
        {
            switch(key.keyCode)
            {
                case 13:
                {
                    $('#resultcitys > a[sel="sel"]').click();
                    break;
                }
                case 9:
                {
                    $('#resultcitys > a[sel="sel"]').click();
                    break;  
                }
            }
        });
        $this.focus(function()
        {
        	$this.select();
            return $this.click();
        });
        $this.blur(function()
        {
            if($this.val() == '')
            {
                setCityinfo($this,'',config.tips);
                //$this.val(config.tips);
                //$this.attr('_3CODE','');
            }
        });
        //初始化
        var init = function()
        {
            //取数据
            getCityData();
            if(config.$from == null)
            {
               getHotCity();    
            }
            $this.attr('title', config.tips);
            if($this.attr('_3CODE')=='' || typeof $this.attr('_3CODE') === 'undefined')
            {
//                $this.val(config.tips);
                setCityinfo($this,'',config.tips);    
            }
            $(document).mousedown(function(event)
            {
                $target=$(event.target);
                if (($this.attr('_show') == 'show') && $('#' + windowid).length !=0 && $target.parents("#" + windowid).length == 0 && !($target.attr('_show')=='show'))
                {
//                    $this.attr('_3CODE','');
//                    $this.val('');
                    setCityinfo($this,'',config.tips);
                    $('#resultcitys > a[sel="sel"]').click();
                    $this.attr('_show','');
                    $.msgbox.closemsgbox(windowid);
                }
            });
            return $this;
        };
        return init();
    }     
 })(jQuery);
 