/**
 * 
 */

var helper={};

	
	helper.formatTime=function(time){
		var t=new Date(time);
		var y=t.getFullYear();
		var m=t.getMonth()+1;
			m=(m<10)?"0"+m:m;
		var d=t.getDate();
			d=(d<10)?"0"+d:d;
		var h=t.getHours();
			h=(h<10)?"0"+h:h;
			return y+"-"+m+"-"+d+" "+h+":"+"00:00";
	};
	
	

	helper.nextTime=function(str){
		tmp=[];
		console.log(str)
		var ts=str.split("-");
			ts.forEach(function(s){
				tmp.push(parseInt(s));
			});
		var time=new Date(tmp[0],tmp[1]-1,tmp[2],(tmp[3]-1),0,0);
			
			return this.formatTime(time.getTime());
	};
	
	
	helper.getTime=function(str){
		tmp=[];
		var ts=str.split("-");
			ts.forEach(function(s){
				tmp.push(parseInt(s));
			});
		var time=new Date(tmp[0],tmp[1]-1,tmp[2],tmp[3],0,0);
			
			return this.formatTime(time.getTime());
	};
	
	
	helper.getTimeStamp=function(str){
		tmp=[];
		str=str.replace(" ","-");
		var ts=str.split("-");
			ts.forEach(function(s){
				tmp.push(parseInt(s));
			});
		var time=new Date(tmp[0],tmp[1]-1,tmp[2],tmp[3],0,0);
		
		return time.getTime();
	}
	
	
	helper.getFulltimePoint=function(str){
		var tmp=[];
			str=str.replace(" ","-");
			str=str.replace(/:/g,"-");
			ts=str.split("-");
			ts.forEach(function(s){
				tmp.push(parseInt(s));
			});
			
			var time=new Date(tmp[0],tmp[1]-1,tmp[2],tmp[3],tmp[4],tmp[5]);
				console.log(tmp,time)
			var h=time.getHours();
			if(h==0){		
				var time=new Date(time.getTime()-60*60*1000);
				var y=time.getFullYear();
				var m=time.getMonth()+1;
					m=(m<10)?"0"+m:m;
				var d=time.getDate();
					d=(d<10)?"0"+d:d;
				var h=time.getHours();
					return y+"-"+m+"-"+d+" "+h+"点至24点";
				
			}else if(h==8){
				var time=new Date(time.getTime()-12*60*60*1000);
				var y=time.getFullYear();
				var m=time.getMonth()+1;
					m=(m<10)?"0"+m:m;
				var d=time.getDate();
					d=(d<10)?"0"+d:d;
				var h=time.getHours();
					return y+"-"+m+"-"+d+" "+h+"点至" +y+"-"+m+"-"+(d+1)+' 8点'
			}else{		
				var y=time.getFullYear();
				var m=time.getMonth()+1;
					m=(m<10)?"0"+m:m;
				var d=time.getDate();
					d=(d<10)?"0"+d:d;
				var h=time.getHours();
					//h=(h<10)?"0"+h:h;
					return y+"-"+m+"-"+d+" "+(h-4)+"点至"+h+"点";	

			}
		
	};
	

	helper.getPoint=function(str){
		tmp=[];
		str=str.replace(" ","-");
		var ts=str.split("-");
			ts.forEach(function(s){
				tmp.push(parseInt(s));
			});
		var time=new Date(tmp[0],tmp[1]-1,tmp[2],tmp[3],0,0);
		
		
			var h=time.getHours();
			if(h==0){
				
				var time=new Date(time.getTime()-60*60*1000);
				
				var y=time.getFullYear();
				var m=time.getMonth()+1;
					m=(m<10)?"0"+m:m;
				var d=time.getDate();
					d=(d<10)?"0"+d:d;
				var h=time.getHours();
					return y+"-"+m+"-"+d+" "+h+"点至24点";
				
			}else{
					
				var y=time.getFullYear();
				var m=time.getMonth()+1;
					m=(m<10)?"0"+m:m;
				var d=time.getDate();
					d=(d<10)?"0"+d:d;
				var h=time.getHours();
					//h=(h<10)?"0"+h:h;
					return y+"-"+m+"-"+d+" "+(h-1)+"点至"+h+"点";	
			}
			
	};
	


	



	
/* js/models/realtime.js */

var RealTimeModel=Backbone.Model.extend({
	defaults:{
		name:"realtime",
		theme:"全部",
		page:1
	}
});
/* js/models/theme.js */

var ThemeModel=Backbone.Model.extend({
	defaults:{
		name:"theme",
		active:"全部",
	},
	url:"servlet/Theme.do"
//	url:"http://wr52b5.natappfree.cc/bjfzxWebapp/servlet/Theme"
		
});
/* js/models/top.js */
var TopModel=Backbone.Model.extend({
	defaults:{
		name:"top10",
		tpl:"indexTpl",
		now:function(){

			var time=new Date();	
			var h=time.getHours();
			if(h==0){
				var time=new Date(time.getTime()-4*60*60*1000);
				var y=time.getFullYear();
				var m=time.getMonth()+1;
					m=(m<10)?"0"+m:m;
				var d=time.getDate();
					d=(d<10)?"0"+d:d;
				var h=time.getHours();
					return y+"-"+m+"-"+d+" "+h+"点至24点";
				
			}else if(h==8){
				var time=new Date(time.getTime()-12*60*60*1000);
				var y=time.getFullYear();
				var m=time.getMonth()+1;
					m=(m<10)?"0"+m:m;
				var d=time.getDate();
					d=(d<10)?"0"+d:d;
				var h=time.getHours();
					return y+"-"+m+"-"+d+" "+h+"点至" +y+"-"+m+"-"+(d+1)+' 8点'
			}else{
					
				var y=time.getFullYear();
				var m=time.getMonth()+1;
					m=(m<10)?"0"+m:m;
				var d=time.getDate();
					d=(d<10)?"0"+d:d;
				var h=time.getHours();
					//h=(h<10)?"0"+h:h;
					return y+"-"+m+"-"+d+" "+(h-4)+"点至"+h+"点";	
			}
			
		}(),
		time:function(){
			var time="";
			var t=new Date();
			var y=t.getFullYear();
			var m=t.getMonth()+1;
				m=(m<10)?"0"+m:m;
			var d=t.getDate();
				d=(d<10)?"0"+d:d;
			var h=t.getHours();
				h=(h<10)?"0"+h:h;
				time=y+"-"+m+"-"+d+" "+h+":00:00";				
			return time;
		}()
		
	},
	initialize:function(){
		var selt=this;
		this.on("change:time",function(a,b){
			var t=helper.getFulltimePoint(b);
			this.set("now",t);
		});
	},
	url:"servlet/Index.do"
//	url:"http://wr52b5.natappfree.cc/bjfzxWebapp/servlet/Index"
});
var RealTimeCollection=Backbone.Collection.extend({
	model:RealTimeModel,
	url:"servlet/Realtime.do"
//	url:"http://wr52b5.natappfree.cc/bjfzxWebapp/servlet/Realtime"		
});
var app=app ||{};

	app.tpls={};
	  app.navigate = function(route, options) {
		     options || (options = {});
		     Backbone.history.navigate(route, options);
		 	};
    $("script.template").each(function(){
       app.tpls[$(this).attr("id")]=_.template($(this).html());
       $(this).remove();
    });


/* 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});     
              });

        });
	}

});
var app=app || {};
var Route=Backbone.Router.extend({
 routes: {
	"":"index",// #index
	"index(/t:time)(/:group)":"index",    // #index
	"realtime/:theme(/p:page)(/t:time)":"realtime",    //#theme/全部
	"theme(/t:time)":"theme",
	"*other":"index"
		},

  index: function(t,group) {
  	console.log("index");
  	console.log('t:'+t,'group:'+group)
  	app.topModel=new TopModel({
  	  	
	  	});
  	//是否传了默认时间
  	if(t){
  		app.topModel.set("time",t);  		
  	}
  	
  	if(group) {
  		app.topModel.set("group",group);
  		$.cookie("group",group);
  	}else{
  		app.topModel.set("group",undefined)
  		$.cookie("group",undefined);
  	}

  	

  	var datas={
  			time:app.topModel.get("time"),
  			groupName:app.topModel.get("group")
  	};
  	
  	app.topModel.fetch({
  		data:datas,
  		success:function(model,res,opt){
	  			app.topView=new TopView({
	  		  		model:model
	  		  	});
			},
			error:function(err){
				console.error(err);
			}
  	});
  	
  },
  realtime: function(theme,p,t) {
	$(".wrap").html(app.tpls["loadTpl"]());
	var nowPage=p || 1;
	

  	//默认当前时间点
	var time=helper.formatTime(new Date().getTime());
	//如果带时间参数
	if(t){
		t=helper.getTimeStamp(t);
		console.log(t);
		time=helper.formatTime(t);
	}
	

  	var datas={
  		"theme":theme,
  		"time":time,
  		"loadPage":"1",
  		"page":nowPage,
  		"groupName":$.cookie("group")
  	};
  	

  	if(t){
  		app.realTimeModel=new RealTimeModel({
  	 		theme:theme,
  	 		realtime:time
  	 	});
  		app.themeModel=new ThemeModel({
  	  		active:theme,
  	  		realtime:time
  	  	});
  	}else{
  		app.realTimeModel=new RealTimeModel({
  	 		theme:theme
  	 	});
  	  	app.themeModel=new ThemeModel({
  	  		active:theme
  	  	});
  	}
  	
 
 	

 	app.realTimeCollection=new RealTimeCollection();
 	app.realTimeCollection.reset();
 	app.realTimeCollection.fetch({
 		data:datas,
 		success:function(collections,res,opt){
				app.realTimeView=new RealTimeView({
			 		collection:collections,
			 		model:app.realTimeModel
			 	});
 		}
 	});
 

  },
  theme:function(t){
  	console.log("theme");
  	if(!app.themeModel){
  			if(t){
  				t=helper.getTimeStamp(t);
  				var time=helper.formatTime(t);
  				app.themeModel=new ThemeModel({
  					realtime:time
  		  	  	});
  			}else{
  				app.themeModel=new ThemeModel({
  					
  		  	  	});
  			}
  		
  	}
  	
  		var datas = {
  				groupName:$.cookie("group")
  		}
  	
  		app.themeModel.fetch({
  			data:datas,
  			success:function(model,res,opt){
  				app.themeView=new ThemeView({
  			 		model:model
  			 	});
  			},
  			error:function(err){
  				console.error(err);
  			}
  		});
  	
 	
  }

});
$(function(){
//300ms延遲
 FastClick.attach(document.body);
var app=app||{};
app.route=new Route();
Backbone.history.start();
});