/* js/views/realtime.js */
RealTimeView = Backbone.View.extend({
    el: ".wrap",
    template: app.tpls["realtimeTpl"],
    initialize: function() {
        this.render();
       	var self=this;
       	
    },
    templateLi: app.tpls["realtimeLiTpl"],
    templateWrap: app.tpls["realtimeWrapTpl"],
    render: function() {
    	
    	var theme=this.model.get("theme")?this.model.get("theme"):"全部"
    	if(app.themeModel){
    		var theme=app.themeModel.get("active");
    	}
    
        this.$el.html(this.template({
            data: this.collection.models,
            theme:theme,
            realtime:app.realTimeModel.get("realtime")
        }));
        
        console.log(this.collection);
        this.swiper();
        this.iscorller();
    },
    iscorller:function(){
        this.scorllers = {};
        var self = this;
        var h = $(".swiper-slide").height();
        var loading = '<div class="loading"></div>';
        var nomore = '<div class="nomore">没有更多数据</div>';
        var theme = this.model.get("theme");
        
        var ptClick = ''
        
        if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        	ptClick = false
        } else if (/(Android)/i.test(navigator.userAgent)) {
            //alert(navigator.userAgent); 
        	ptClick = true
        } else {
            window.location.href ="pc.html";
            ptClick = true
        };
   
    	 console.log(this)
    	 _.each(this.collection.models, function(m) {
             e = m.toJSON();
             if(!ptClick) {
            	 self.scorllers[m.cid] = new IScroll('.wrapper' + e.time.replace(" ","-"));
             }else{
            	 self.scorllers[m.cid] = new IScroll('.wrapper' + e.time.replace(" ","-"),{
                	 mouseWheel: true,
                	 click: ptClick,
                	 preventDefaultException: { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|A)$/ }
                 });
             }
             
             self.scorllers[m.cid].on('scrollEnd', function() {
                 if (this.y <= this.maxScrollY) {
                     if (!$(this.wrapper).find(".loading").length) {
                         $(this.wrapper).find(".events").append(loading);
                         var time = $(this.wrapper).attr("data-time"),
                             model = m.get(m.cid),
                             page = m.get("page") + 1;
                         	m.set("page", page);
                         if (page > 10) {
                             $(this.wrapper).find(".loading").remove();
                             if (!$(this.wrapper).find(".nomore").length) {
                                 $(this.wrapper).find(".events").append(nomore);
                             }
                             return false;
                         }
                         time=helper.getTime(time);
                         self.loadMore(theme, time, page, this.wrapper, self.scorllers[m.cid]);
                     }
                 }
             });
         }); 
    	 
        $(".wrapper").height(h - 37);
    },
    swiper: function() {
        var cache = [];
        var self = this;
        var theme = this.model.get("theme");
        console.log(theme)
        console.log(this.model)
        this.mySwiper = new Swiper('.swiper-container', {
            // Optional parameters
            initialSlide: 0,
            prevButton: '.swiper-button-prev',
            nextButton: '.swiper-button-next',
            onSlideChangeEnd: function(swiper) {
                console.log(swiper)
                console.log(swiper.activeIndex)
                console.log(swiper.slides.length)
                var time = $(".swiper-slide-next").find(".wrapper").attr("data-time");
                var id= $(".swiper-slide-next").find(".wrapper").attr("data-id");
                	if(!time){
                		return;
                	}
                
                if ((swiper.activeIndex == (swiper.slides.length - 2))) {

                    var model = self.collection.get(id);
                    	console.log(model)
//                    var  theme = model.get("theme");
                    var datas = {
                        "theme": theme,
                        "time": helper.nextTime(time),
                        "loadPage":"1",
                        "page":1,
                        "groupName":$.cookie("group")
                    };
                                   
            	if((id in cache)){
            		return false;
            	}

                   cache.push(id);
                   self.loadPage(datas);
                }
            }
        });
    },
    loadPage: function(datas) {
        var self = this;
      //  alert(datas.time);
        $.ajax({
          url: "servlet/Realtime.do",
//        	url: "http://wr52b5.natappfree.cc/bjfzxWebapp/servlet/Realtime",
            type: "GET",
            data:datas,
            dataType: "json",
            success: function(data) {
                self.collection.add(data);
                console.log(self.collection)
                var html = [];
                for(var i=self.collection.models.length,j=i-data.length;j<i;j++){
                	 var tmp = self.templateWrap({
                         data: self.collection.models[j]
                     });
                     html.push(tmp);
                }
                self.mySwiper.appendSlide(html);
                self.iscorller();
            },
            error: function(e) {
                console.log(e)
            }
        });
    },
    loadMore: function(theme, time, page, target, iscroller) {
    	
        var datas = {
            "theme": theme,
            "time": time,
            "page": page,
            "loadPage":"0",
            "groupName":$.cookie("group")
        };
        var nomore = '<div class="nomore">没有更多数据</div>';
        $(target).find(".events .nomore").remove();
        var model = this.collection.get(time);
        var self = this;
        $.ajax({
            url: "servlet/Realtime.do",
//            url: "http://wr52b5.natappfree.cc/bjfzxWebapp/servlet/Realtime",
            data: datas,
            type: "GET",
            dataType: "json",
            success: function(data) {
            	if(data.length){
            	     var html = self.templateLi({"data":data});
                     $(target).find(".events").append(html);
                     $(target).find(".loading").remove();
                     iscroller.refresh();
            	}else{
            		  $(target).find(".events").append(nomore);
                	  $(target).find(".loading").remove();
            	}
            	 iscroller.refresh();
            	
            },
            error: function(e) {
                console.log(e);
            }
        });
    }
});
/* js/views/theme.js */
var ThemeView=Backbone.View.extend({
	el:".wrap",
	template:app.tpls["themeTpl"],
	initialize:function(){
		this.render();

	},
	render:function(){
		if(this.model.get("realtime")){
			this.$el.html(this.template({"themes":this.model.get("themes"),"active":this.model.get("active"),"realtime":this.model.get("realtime")}));
		}else{
			this.$el.html(this.template({"themes":this.model.get("themes"),"active":this.model.get("active")}));
		}
	
	},
	events:{
		"click a":"select"
	},
	select:function(e){
		var e=$(e.target).text();
		this.model.set("active",e);
	}
});
/* js/views/top.js */
var app=app ||{};
var TopView=Backbone.View.extend({
	el:".wrap",
	template:app.tpls["indexTpl"],
	initialize:function(){
		this.render();
	},
	render:function(){
		console.log(this.model);
		var time=this.model.get("time");
		var now=this.model.get("now");
		console.log(time,now)
		this.$el.html(this.template({"time":time,"now":now}));
		var h = $(".index").height();
			$(".barChartWrap").height(h-160);
		var top10=this.model.get("top10");
		this.showBar(top10,time);
		
		



	},
	showBar:function(data,time) {
    // 路径配置
    require.config({
        paths: {
            echarts: 'js/lib/echart/dist'
        }
    });
    // 使用
    require(
        ['echarts', 'echarts/chart/bar' // 使用柱状图就加载bar模块，按需加载
        ], function(ec) {
            // 基于准备好的dom，初始化echarts图表
            var myChart = ec.init(document.getElementById('barChart'));
            
         
            var dataOrder=_.sortBy(data,"value");
            var names=_.pluck(dataOrder,"name");
            	
            var nameOrigin = _.clone(names);	
            var names=_.map(names,function(name){            	
            	return lineFeed(name);
            });
            
            function lineFeed(str) {
            	var len = Math.floor(str.length / 6)
            	if(!len) {
            		return str
            	}else{
            		var temp = []
                	for(var i = 0; i< len; i++) {
                		var part =str.substr(i* 6,6)
                		temp.push(part)
                	}
                	return temp.join('\n')           		
            	}
             	
            	
            }
            
       
            console.log(names)
            
            var values=_.pluck(dataOrder,"value"); 
            var option = {
                color: ["#00b1f1"],
                grid: {
                    x: 100,
                    y: 20,
                    x2: 50,
                    y2: 0,
                    borderWidth: 0,
                },
                xAxis: [{
                    type: 'value',
                    position: 'top',
                    axisLine: {
                        lineStyle: {
                            color: "#00b1f1",
                            width: 2,
                            type: 'solid'
                        }
                    },
                    axisTick: {
                        show: true,
                        inside: true,
                        lineStyle: {
                            color: "#00b1f1",
                            width: 2,
                            type: 'solid'
                        }
                    },
                    axisLabel: {
                        show: true,
                    },
                    splitLine: {
                        show: false
                    }
                }],
                yAxis: [{
                    type: 'category',
                    data: names,
                    barCategoryGap: "40",
                    axisLine: {
                        lineStyle: {
                            color: "#00b1f1",
                            width: 2,
                            type: 'solid'
                        }
                    },
                    axisLabel:{
                    	show:true,
                    	clickable: true
                    },
                    axisTick: {
                        show: true,
                        inside: true,
                        lineStyle: {
                            color: "#00b1f1",
                            width: 2,
                            type: 'solid'
                        }
                    },
                    splitLine: {
                        show: false
                    }
                }],
                series: [{
                    name: '2011年',
                    type: 'bar',
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                position: 'right',
                                textStyle: {
                                    color: "#000"
                                }
                            }
                        }
                    },
                    barWidth: 15,
                    data: values
                }]
            };
            
            // 为echarts对象加载数据 
            myChart.setOption(option);
            myChart.on("click", function(e){
                

                if(e.name){
                    
                var v=e.name.replace("...","");

                }
                var word;
                _.each(nameOrigin,function(name,index){

                   if(name.indexOf(v)>-1){
                     word=nameOrigin[index];
                   }
                })
                 app.navigate("realtime/"+word+"/t"+time,{trigger:true});     
              });

        });
	}

});