function urlencode(str){
    str = (str+'').toString();
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}


var no_msg = '暂无信息';
var huoche_post_action = '/tools/huoche';    //ajax地址
var checkUrlTimer;
var oldHash = "";
var searchTab;

//===================初始化方法（联想词||TAB)=====================
//初始化输入联想词
var initTextBoxDrop = function(inputId,showBoxId,url){
    var s_train = new TextBoxDrop(inputId,showBoxId);
    s_train.SetEnterHandler (function(value){
        //document.getElementById("goSearch").click();
    });
    s_train.TextFeild = "v";
    s_train.KeyFeild = "k";
    s_train.ShowKey = true;
    s_train.SetAjaxMethod($.get);
    s_train.Url(TOOL_URL + url);
    s_train.SetContentStyle(function(input,contentbox){
        var inputBox = $(input);
        if($.browser.ie){
            contentbox.style.left = inputBox.offset().left;
            contentbox.style.top = inputBox.offset().top + 27;
        }
        else{
            $(contentbox).css({
                              top : inputBox.offset().top + 27,
                              left: inputBox.offset().left
                            });
        }
    });
    s_train.DisplayContentHandler(function(input,contentbox){
        if($(contentbox).width() < $(input).outerWidth()){
            $(contentbox).width($(input).outerWidth());
        }
    });
    return s_train;
}



//===================车站精确选择@zen=====================
var trainSeletor=(function(){
    var that=$(this);
    var uniqueInstance;
    var sType=0,
        sStep=0,
        target=null,
        tempData={},
        activeId="";
    var pURL = huoche_post_action + "/json.aspx?oper=provinceSelect&province",
        cURL = huoche_post_action + "/json.aspx?oper=trainSelect&train";
    //初始化内容框
    var initBox=function(){
        if(!that.MsgBox){
            that.MsgBox=$("<div id='js_train_search_msg' class='box-alert'></div>");
            that.MsgHead=$("<div id='js_train_search_msg_hd'></div>").appendTo(that.MsgBox);
            that.MsgContent=$("<div id='js_train_search_msg_content' class='box-base'></div>").appendTo(that.MsgBox);
            that.MsgClose=$("<span id='js_train_search_msg_cls'></span>").appendTo(that.MsgHead);
            that.MsgTitle=$("<span id='js_train_search_msg_tit'></span>").appendTo(that.MsgHead);
            that.Selected=$("<span id='js_train_search_msg_selector'></span>").appendTo(that.MsgHead);
            that.ReSelect=$("<span id='js_train_search_msg_reselect'>重选</span>").appendTo(that.MsgHead);
            $("body").append(that.MsgBox);
            that.ReSelect.bind("click",function(){
                Didplay();
            });
            that.MsgClose.bind("click",function(){
                Public.ScreenManager.Hide();
            });
        }
        that.Selected.html("");
        that.ReSelect.hide();
        sStep=0;
    }
    var Didplay=function(){
        initBox();
        Public.ScreenManager.Show(that.MsgBox[0]);
        that.MsgBox.show();
        sStep==0?that.ReSelect.hide():that.ReSelect.show();
        that.MsgTitle.text(sType==0?"选择省份：":"选择车次类型：");
        GetData();
    }
    //获取数据并写入html
    var GetData=function(data){
        url=sType==0?pURL:cURL;
        if(sStep){
            url=url+"="+data;
        }else{
            data=sType==0?"pro":"cc";
        }
        if(typeof tempData[data]!=="undefined"){
            that.MsgContent.html(tempData[data]);
            LiveEvent();
        }else{
            $.ajax({
                url:url,
                success:function(text){
                    eval(text);
                    if(typeof stationJSON!="undefine"){
                        var html="";
                        for(var n in stationJSON){
                            if(sType==0){
                                html+='<li><span rel="'+stationJSON[n]+'">'+n+'</span></li>';
                            }else{
                                html+='<li title="'+stationJSON[n]+'"><span rel="'+n+'">'+stationJSON[n]+'</span></li>';
                            }
                        }
                        tempData[data]=html;
                        that.MsgContent.html(html);
                        LiveEvent();
                    }
                }
            });
        }
    }
    var LiveEvent=function(){
        that.MsgContent.find("span").click(function(){
            var text=sType==0?$(this).text().substring(2):$(this).text();
            if(sStep==0){
                that.Selected.html(text+" ");
                that.ReSelect.show();
                sStep=1;
                GetData($(this).attr("rel"));
            }else{
                target.val(text);
                sStep=0;
                initBox();
                Public.ScreenManager.Hide();
            }
        });
    }
    return {
        Bind:function(acElement,tarElement,type){
            acElement.bind("click",function(){
                sStep=0;
                sType=type;
                target=tarElement;
                activeId=this.id;
                Didplay();
            });
        }
    };
})();
//=======================车站精确选择@zen============

//初始化事件
var initEvents = function(){
    // 清除当前获得焦点的文本框 ID
    $('#js_box_focus').val('');
    
    // 点击输入框下的“例如”链接时
    $('#tab_box span.js_input_eg').click(function() {
        var text = $(this).text();
        if ($('#search_ss').css('display') != 'none') {
            if ($('#js_box_focus').val() == 'js_box_end_station') {
               $('#js_box_end_station').val(text);
               document.getElementById("js_box_end_station").focus();
            }
            else {
                $('#js_box_start_station').val(text);
                document.getElementById("js_box_start_station").focus();
            }
        }
        if ($('#search_s').css('display') != 'none') {
            $('#js_box_station').val(text);
            document.getElementById("js_box_station").focus();
        }    
    });

    // 起始站 focus
    $('#js_box_start_station').focus(function() {
        $('#js_box_focus').val('js_box_start_station');
    });

    // 终点站 focus
    $('#js_box_end_station').focus(function() {
        $('#js_box_focus').val('js_box_end_station');
    });
    
    //动态绑定打印时刻表
    $("#main>.col-main").find("span.print").bind("click",function(){
        printTable(this);
    });
    
    // 站站查询
    /*
    $("#search_ss").submit(function() {
        //var search_back = $('#js_search_back_no').attr('checked') ? '0' : '1';
        var start = urlencode($.trim($('#js_box_start_station').val()));
        var end = urlencode($.trim($('#js_box_end_station').val()));
        var data = {"st": "s:ss","search_back":'0',"s":start,"e":end};
        SsSearchMethod(data);
        return false;
    });
    // 车次查询
    $("#search_t").submit(function(){
        var train = $.trim($('#js_box_train').val());
        var data = {"t": train, "st": "s:t"};
        SsSearchMethod(data,2);
        set_location_hash('st-s:t/t-' + train);
        return false;
    });
    // 站点查询
    $("#search_s").submit(function() {
        var station = $.trim($('#js_box_station').val());
        var data = {"s": station, "st": "s:s"};
        SsSearchMethod(data,1);
        set_location_hash('st-s:s/s-' + station);
        return false;
    });
    */
    // 站站查询中的列车查询
    $('#result_table .js_train_detail').bind('click', function() {
        
        var obj_tr = $(this).parents('tr');
        var train = $(this).attr('train');
        if (obj_tr.next('.detail').length > 0) {
            var obj_detail = obj_tr.next('.detail');
            var obj_js_price = obj_tr.next().next('.js_price');
        } else {
            var obj_detail = obj_tr.next().next('.detail');
            var obj_js_price = obj_tr.next('.js_price');
        }
        if (obj_detail.length > 0) {
            if (obj_detail.css('display') != 'none') {
                obj_detail.hide();
            } else {
                obj_detail.show();
                obj_js_price.hide();
            }
        } else { // AJAX 获取新内容
            var data = {"t": train, "st": "s:t", "detail": "1"};
            $.post(huoche_post_action, data, function(result) {
                if (result != '') {
                    result = '<tr class="detail"><td colspan="7">' + result + '</td></tr>';
                } else {
                    result = '<tr class="detail"><td colspan="7">无法获取信息</td></tr>'
                };
                obj_js_price.hide();
                obj_tr.after(result);

                // 高亮显示始发站至到达站
                var station2 = obj_tr.children('td[rel="s"]').text().split('-');
                var station_start = station2[0].replace(' ', '');
                var station_end = station2[1]?station2[1].replace(' ', ''):"";

                obj_tr.next('.detail').find('.detail-table td a').each(function(i, n) {
                    if ($(this).text() == station_start || $(this).text() == station_end) {
                        $(this).parents('tr').addClass('even');
                    }
                });
            });
        }

        return false;
    });

    // 选择列车类型显示
    var lineTr=$('#result_table .js_train_line'),
         detail=$('#result_table .detail');
    $('#result_table .js_select_train_type').bind('change', function() {
        var type = $(this).val();
        if(type == '') {
            lineTr.show();
        } else {
            detail.hide();
            lineTr.each(function(){
                var tr=$(this);
                if(tr.attr("type")==type){
                    tr.show();
                }else{
                    tr.hide();
                }
            });
        }
    });
}

//初始化TAB
var initTab = function(){
    searchTab = new tab_content(
            [{TabId:"js_tap_search_ss",ContentId:"search_ss",Type:0},
            {TabId:"js_tap_search_t",ContentId:"search_t",Type:2},
            {TabId:"js_tap_search_s",ContentId:"search_s",Type:1}],"active"
        );
}

var showDefaultContent = function(type,isHiden){
    
}

var toggle_loading = function(action) {
    if (action == 'show') {
        $('#js_loading').show();
    } else {
        $('#js_loading').hide();
    }
}
var activeType = 0;

//客运铁路图拖放
var Map=function(){
    var outer=$("#railway_outer");
    var inner=$("#railway_inner");
    var innerHeight=inner.height(),innerWidth=inner.width(),outerHeight=outer.height(),outerWidth=outer.width();
    var load=0;
    var sX,sY,sL,sT;
    var dragMapMouseDown=function(e){
        sX=e.clientX;
        sY=e.clientY;
        sL=inner.position().left;
        sT=inner.position().top;
        if(!load){
            var img=new Image();
            img.onload=function(){
                load=1;
                inner.css({
                    backgroundImage:"url("+img.src+")",
                    backgroundPosition:"0 0"
                })
            }
            img.src="/static/tools/huoche/railway_cn.gif";
        }
        $(document).bind('mousemove',dragMapMouseMove);
        $(document).bind('mouseup',dragMapMouseUp);
        return false;
    }
    var dragMapMouseMove=function(e){
        var eX=e.clientX,eY=e.clientY;
        var nL=sL+eX-sX,nT=sT+eY-sY;
        if(nL>0){
            nL=0;
        }else if(nL<outerWidth-innerWidth){
            nL=outerWidth-innerWidth;
        }
        if(nT>0){
            nT=0;
        }else if(nT<outerHeight-innerHeight){
            nT=outerHeight-innerHeight;
        }
        inner.css({
            left:nL+"px",
            top:nT+"px"
        });
        return false;
    }
    var dragMapMouseUp=function(e){
        $(document).unbind('mousemove',dragMapMouseMove);
        $(document).unbind('mouseup',dragMapMouseUp);
        return false;
    }
    inner.bind("mousedown",dragMapMouseDown);
}
//打印时刻表
var printTable=function(obj){
   window.print();
}
$(document).ready(function(){
    initTextBoxDrop("js_box_start_station","js_start_train_search_msg", huoche_post_action + '/json.aspx?oper=stationInput&k=');
    initTextBoxDrop("js_box_end_station","js_end_train_search_msg",huoche_post_action + '/json.aspx?oper=stationInput&k=');
    initTextBoxDrop("js_box_station","js_box_station_search_msg",huoche_post_action + '/json.aspx?oper=stationInput&k=');
    initTextBoxDrop("js_box_train","js_box_train_search_msg",huoche_post_action + '/json.aspx?oper=trainInput&k=');
    
    initEvents();
    initTab();                     
    Map();
    searchTab.SetChangeHandler(function(){   //设置转换Tab事件
        $("#js_start_train_search_msg,#js_end_train_search_msg,#js_box_train_search_msg,#js_box_station_search_msg").hide();
    });
    
    trainSeletor.Bind($("#js_box_start_station_btn"),$("#js_box_start_station"),0);
    trainSeletor.Bind($("#js_box_end_station_btn"),$("#js_box_end_station"),0);
    trainSeletor.Bind($("#js_box_train_btn"),$("#js_box_train"),1);
    trainSeletor.Bind($("#js_box_station_btn"),$("#js_box_station"),0);
   
});