/*------------------------------------------------------ */
//-- 价格指数页面 JS 脚本
/*------------------------------------------------------ */


var gdata = {};

function doRequestData(id, flag) {
    //if (arr.length == 0) return;
    var pick = '';
    if (flag == 1) pick  = 'day';
    else if (flag == 2) pick = 'week';
    else if (flag == 3) pick = 'month';


    if (id in gdata) {
        //console.log(gdata[id]);
        var plot = $("#chart-" + pick + "-" + id + "").data();
        if (plot instanceof Object && 'shutdown' in plot) plot.shutdown();
        draw_chart(gdata[id], id, flag);
        return;
    }

    $.ajax({
        type: 'POST',
        url: 'ajaxindex',
        data: { 'id': id, 'pick': pick},
        dataType: "json",
        cache: true,
        success: function(ret) {
            var result=ret.data;
            if (result instanceof Object) {
                gdata[id] = result;
            } else {
                return;
            }
            draw_chart(result, id, flag);
        },
        complete: function() {

        }
    });

}

function draw_chart(ret, id, flag) {
    var res, pick;
    if (flag == 1) {res  = ret.day_line; pick  = 'day'}
    else if (flag == 2) {res = ret.week_line; pick  = 'week'}
    else if (flag == 3) {res = ret.month_line; pick  = 'month'}

    if (res instanceof Object) {
        if (res.list instanceof Object) {
            var data = [];
            for (var key in res.list) {
                var arr1 = key.split("-");
                var date1 = new Date(arr1[0],parseInt(arr1[1])-1,arr1[2],8,0,0);
                data.push([date1, res.list[key]]);
            }
            var start_date = (res.date_rang[0]);
            var end_date = (res.date_rang[res.date_rang.length-1]);

            var tick = (flag==3) ? 'month' : 'day';
            var $chart = $("#chart-" + pick + "-" + id + "");
            var plot = gen_price_chart($chart, data, pick);
            $chart.data(plot);
        }
    }

}

var coustom_method = {

    showTooltip: function (x, y, contents) {
        $('<div class="charts_tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y + 5,
            left: x + 5,
            padding: 3,
            border: "1px solid #d6d6d6",
            background: "#fff",
            borderRadius: 2,
            zIndex: 99999
        }).appendTo("body").fadeIn('fast');
    },

};

function gen_price_chart($chart, data, tick) {

    var t = 1, tm = "%m月%d日", c = "#91FA8B";
    if (data.length > 1) {
        if (parseInt(data[data.length-1][1])>parseInt(data[data.length-2][1])) c = "#ff265c";
        else if (parseInt(data[data.length-1][1])==parseInt(data[data.length-2][1])) c = "#8a8a7b";

    }
    if (tick == 'month') {
        tm = null;
        c = "#9440ed";
    }
    if (tick == 'week') {
        t = 7;
        c = "#F7810C";
    }
    if (tick == 'day') {
        if (data.length > 6) t = 2;
        if (data.length > 12) t = 3;
        if (data.length > 18) t = 4;
    }
    if (tick == 'week' && data.length > 8) {t = 9;}
    if (tick == 'month') {
        if (data.length > 12) {t = 2; tm = "%y年%m月";}
        if (data.length > 18) {t = 3;}
    }
    if (tick == 'week') tick = 'day';

    var plot1 = $.plot($chart, [ { label: "", data: data } ],
        {
            colors: [c,"#00AADD"],
            animate: true,
            animateReplot: true,
            series: {
                lines: {
                    show: true,
                    lineWidth: 2,
                    fill: false,
                    fillColor: "rgba(188,176,150,0.3)"
                },
                points: {show: true},
                shadowSize: 2
            },

            grid: {
                hoverable: true,
                show: true,
                borderWidth: 0,
                tickColor: "#d2d2d2",
                labelMargin: 12
            },

            legend: {
                show: true,
                margin: [0,-24],
                noColumns: 0,
                labelBoxBorderColor: null
            },

            yaxis: {
                min: null,
                max: null,
                minTickSize: 1.0,
                tickDecimals: 0
            },
            xaxis: {
                mode: "time",
                timezone: "browser",
                timeformat: tm,
                minTickSize: [t, tick],
                monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                /*tickFormatter: function (val, axis) {
                 var d = new Date(val);
                 return d.toLocaleDateString();

                 }*/
            }
        });

    plot1.resize();
    $chart.bind('resize', function(event, ui) {
        //plot1.replot( { resetAxes: true } );
    });
    // Tooltip Show
    var previousPoint = null;
    $chart.bind("plothover", function (event, pos, item) {
        if (item) {
            if (previousPoint != item.dataIndex) {
                previousPoint = item.dataIndex;
                $(".charts_tooltip").fadeOut("fast", function(){
                    $(this).remove();
                });


                var x = item.datapoint[0],
                    y = item.datapoint[1].toFixed(2);
                x = (new Date(x));
                x = x.getFullYear() + "-" + (x.getMonth()+1) + "-" + (x.getDate());

                coustom_method.showTooltip(item.pageX-40, item.pageY+8, "<font color='grey'>日期：" + x + "</font><br><font color='grey'>报价：</font><b>" + y + " </b>");
            }
        } else {
            /*$(".charts_tooltip").fadeOut("fast", function(){
             $(this).remove();
             });*/
            $(".charts_tooltip").remove();
            previousPoint = null;
        }
    });

    return plot1;
}


// 公共初始化JS
$(function(){

    (function(){

        var mydate=new Date();
        var weekday=new Array("周日","周一","周二","周三","周四","周五","周六");
        var month= new Array("01","02","03","04","05","06","07","08","09","10","11","12");
        var theweek=weekday[mydate.getDay()];
        var thedaytime=mydate.getFullYear()+"/"+month[mydate.getMonth()]+"/"+(mydate.getDate());
        $("div .t-gray").each(function() {

            //$(this).find('span').eq(0).html("时间："+thedaytime+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+theweek);
        });


        //行情　月，周 日
        $(".t-tab").each(function(index) {
            $(".t-tab").eq(index).find("a").click(function(){
                var i = $(this).index();
                var id = $(this).parent().attr("data-id");
                $(this).addClass("current");
                $(this).parent("div.t-tab").parent("div.trend-con").find("div.t-img").eq(i).show();
                for(var g=0;g<3;g++) {
                    if(g!=i) {
                        $(".t-tab").eq(index).find("a").eq(g).removeClass("current");
                        $(this).parent("div.t-tab").parent("div.trend-con").find("div.t-img").eq(g).hide();
                    }
                }
                var flag = $(this).parent().find("a.current").attr("data-target");
                doRequestData(id, flag);
            });
        });

        $(".table-w").find("tbody").each(function() {
            $(this).find("tr").each(function(index){

                var id = $(this).find(".t-tab").attr('data-id');
                if (! id instanceof Number) id = $(this).find("input:hidden").val();
                var fun = function(e){
                    if (! $(this).parent().hasClass('dis-yes')) {
                        $(this).parent().addClass('dis-yes');
                        e.stopPropagation();
                    }
                    //指数图表数据导入
                    var flag = $("#bspi-" + id).find("div.t-tab a.current").attr("data-target");

                    $(this).parent().find('div.trend.bspi-call').removeClass('bspi-call');
                    $(this).find('div.trend').eq(0).addClass('bspi-call');

                    doRequestData(id, flag);
                };
                if ($(this).find('td.dy-point').length == 1) {
                    $(this).find('td.dy-point').eq(0).mouseenter(fun);
                } else {
                    $(this).mouseenter(fun);
                }

                var nlist=index+1;

            });


        });

        //这个方法只是在priceindices页面使用到
        var detail_id=$("#hlpricedetail").val();
        if (detail_id != undefined && detail_id > 0){
            doRequestData(detail_id, 1);
        }

    })();

});


$(function(){
    (function(){

        $.jqtab = function(tabtit,tab_conbox,shijian) {
            $(tabtit).find("li").bind(shijian,function(){
                $(this).addClass("current").siblings("li").removeClass("current");
                var activeindex = $(tabtit).find("li").index(this);
                $(tab_conbox).eq(activeindex).show().siblings().hide();
                var id = $(tab_conbox).eq(activeindex).find(".bspi-call").eq(0).find(".t-tab").eq(0).attr('data-id');
                var flag = $("#bspi-" + id).find("div.t-tab a.current").attr("data-target");

                doRequestData(id, flag);

                return false;
            });

        };

        $.jqtab("#bspi-tabs",".mt-bspi","click");
        var id = $('.bspi-table > tbody').find('tr:first').attr('data-id');
        if (id){
            doRequestData(id, 1);
        }

    })();
});


/**
 * 搜索产品规格
 * priceindices 页面使用到些方法
 */
function  select_pr_spec() {
    var s_spec = $("#select_spec").val();
    var this_url = window.location.href;
    if(s_spec.length>1){
        if ((s_spec.indexOf('-') != -1 || s_spec.toLowerCase().indexOf('.html') != -1)) {
            alert('无效字符，请重试。');
            return;
        }
        s_spec = encodeURI(s_spec);
        if (this_url.indexOf("keywords") > 0){
            window.location.href = replaceParamVal('keywords',s_spec);
        }else if (this_url.indexOf("?") > 0){
            window.location.href = this_url+'&keywords='+s_spec;
        }else {
            window.location.href = this_url+'?keywords='+s_spec;
        }
    }else {
        window.location.href = "priceindices";
    }
}
/**
 * 正则替换url参数值
 */
function replaceParamVal(paramName,replaceWith,obj_url,is_auto) {
    if (obj_url) {
        var oUrl = obj_url;
    } else {
        var oUrl = this.location.href.toString();
    }
    nUrl = oUrl + '? ' + paramName + '=' + replaceWith;
    var re = eval('/(' + paramName + '=)([^&]*)/gi');
    var nUrl = oUrl.replace(re, paramName + '=' + replaceWith);
    if (is_auto == 1) {
        window.location.href = nUrl;
    }
    return nUrl;
}

$(function(){
    (function(){
        //显示更多
        $('.show_more').click(function() {
            var hide_more = $(this).parent().parent().parent().find('.hide_more').eq(0);
            if (hide_more) {
                if ($(this).attr('show') == "show") {
                    $(this).html("收起");
                    hide_more.show();
                    $(this).attr('show','hide');
                } else{
                    $(this).html("更多 》");
                    hide_more.hide();
                    $(this).attr('show','show');
                }
            }

        });

        /**
         * 排序价格
         */
        $(".col55").eq(1).click(function(){
            var order= $(this).attr("data-order");
            click_this("pre_price",order);
        });
        $(".col66").eq(1).click(function(){
            var order= $(this).attr("data-order");
            click_this("chg_val_f",order);
        });

    })();
});

/**
 * 点击排序
 * @param sort
 * @param order
 */
function click_this(sort,order) {
    var this_url=$("#link_order").val();

    if(order=='asc'){
        this_url = this_url+'&order='+order;
    }
    this_url = this_url+'&sort='+sort;
    window.location.href = this_url;
}


/*$chart.highcharts({
 title: {
 text: '产品价格指数',
 align:'left',
 text:null
 },
 subtitle: {
 text:null
 },
 chart: {
 backgroundColor: '#ffffff',
 type: 'line'
 },
 credits: {
 enabled: false
 },
 exporting: {
 enabled:false
 },
 plotOptions: {
 series: {
 marker: {
 enabled: false
 }
 },
 },
 xAxis: {
 categories: month_list,
 tickInterval:12,
 gridLineColor: '#E8E8E8',
 gridLineWidth: 1
 },
 yAxis: {
 title: {
 text: null
 },
 plotLines: [{
 value: 0,
 width: 1,
 color: '#808080'
 }],
 gridLineColor: '#E8E8E8',
 gridLineWidth: 1,
 //max:month_max_price,
 //min:month_min_price,
 tickInterval:month_y_kdu,
 allowDecimals: false

 },
 tooltip: {
 valueSuffix: null
 },
 legend: {
 layout: '数据线',
 align: 'left',
 verticalAlign: 'left',
 borderWidth: 0,
 x:50,
 enabled:false
 },
 series: [{
 name:'价格',
 data: eval(def_month_price_list),
 color:'#91FA8B'
 }]
 });*/