/* Author: yangzeming
 * Date: 2013-12-10
 * Desc: 旅游地图
    
 */
define("component/lvyoumap",["component/fulloverlay","component/mapoverlay"],function (require, exports, module) {
	var fulloverlay = require("./fulloverlay");
	var mapoverlay = require("./mapoverlay");
    var lymap = _.Class({
        initial: function (option) {
            this._eventStack = {};
            var defaultOp = {
                isCenter:true,
				label:"name",
				popWidth:232,
				showLabel:true,
				showPop:true,
				showNavigation:false,
				enableScrollWheelZoom : true,
				withoutLine:false

            };
            var op = this.options = $.extend(true, {}, defaultOp, option);
            this.bt = baidu.template;
			this._map = new BMap.Map(op.con, {
                enableMapClick: false
            });
           
            //g.extend(this, n);
            this.labelType = op.label || "name";
            op.enableScrollWheelZoom && this._map.enableScrollWheelZoom();
            var contr = {
                width: 130,
                type: BMAP_NAVIGATION_CONTROL_LARGE,
                anchor: BMAP_ANCHOR_TOP_LEFT,
                offset: new BMap.Size(10, 10)
            };
            op.showNavigation && this._map.addControl(new BMap.NavigationControl(contr));
            this.polyLine = [];
            this.labelList = [];
            this.currentLabel = null;
			this.bounds = new Array();
			this.linesPoints = new Array();;
            this.currentPop = null;
			this.currentPlanData = [
      /*  {
            "plan_trips_id": "58c45ba6000f1ebb9f2b07d5",
            "plan_days_id": "f978a1777e914f32a9e2f4b3",
            "pl_id": "08db7222b6075754f03b756a",
            "position": "0",
            "remark": "",
            "traffic": "2",
            "traffic_time": null,
            "traffic_dist": null,
            "plan_collect_detail_id": "1db7d7ca6e38ddfed8b75a16",
            "xid": "c543a40f9b9df6dff74030b6",
            "type": "1",
            "parent_sid": "c543a40f9b9df6dff74030b6",
            "detail_cotent": ""
        }*/
    ];
			//this._map.centerAndZoom("桂林",15); 
            
        },
		getMap: function() {
            return this._map
        },
        getCenter: function() {
            return this._map.getCenter()
        },
        getZoom: function() {
            return this._map.getZoom()
        },
        updateMapView: function(p) {
            var sceneList = this.sceneList;
            var plan = [];//p.currentPlanData;
            var isCenter = true;//p.isCenter;
            var q = 0;//p.showCount;
            var t = [];//p.tempCenterAndZoom;
            if (sceneList) {
                this.createPoint(sceneList, {
                    isClear: true,
                    isCenter: isCenter,
                    type: "scene",
                    showCount: q,
                    tempCenterAndZoom: t
                })
            }
            
           /* if (plan) {
                this.createPoint(plan, {
                    isClear: false,
                    type: "plan"
                })
            }*/
           this.createLine()
        },
     
		formatPlanData:function(){
		   var data = [],
			   tmp = this.currentPlanData,
			   self = this;
		   $(tmp).each(function(index,item){
				var xid = item["xid"];
				item.map_x = self.allPoint[xid]["map_x"];
				item.map_y = self.allPoint[xid]["map_y"];
				data.push(item);
		   });
		   this.currentPlanData = data;
		   return data;
		},
		run : function(){
			var self = this;
			var myIcon = new BMap.Icon("../images/car.png", new BMap.Size(30,30), {imageOffset: new BMap.Size(0, 0),imageSize:new BMap.Size(30,"auto")});
			 for(var m = 0;m < self.linesPoints.length; m++){
				var pts = self.linesPoints[m];
				var len = pts.length;
				var carMk = new BMap.Marker(pts[0],{icon:myIcon});
				
				self._map.addOverlay(carMk);
				var $img = $(carMk.Sc);//.find("img");
				resetMkPoint(1,len,pts,carMk,$img)
			}
			function getPointPL(s,e){
						var pl = Math.pow((Math.pow((s.x-e.x),2)+Math.pow((s.y-e.y),2)),0.5);
						return pl*10;
					
					}
			function resetMkPoint(i,len,pts,carMk,$img){
				carMk.setPosition(pts[i]);
				var angle = 0;

				var l = self._map.pointToPixel(pts[i]);//pointToOverlayPixel(pts[i]);
				var l2 = $.extend(true,{},l);
				if(pts[i+1]){
					 l2 = self._map.pointToPixel(pts[i+1]);//pointToOverlayPixel(pts[i]);
					angle = Raphael.angle(l.x,l.y,l2.x,l2.y);
					$img.css({
								"transform" : "rotate("+angle+"deg)"
							});
				}
				//var g = $(self._map.getPanes().markerPane).find("img");
				if(i < len){
					setTimeout(function(){
						i++;
						resetMkPoint(i,len,pts,carMk,$img);
					},getPointPL(l,l2));
				}
			}
		
		},
        createLine: function() {
			var self = this;
			this.formatPlanData();
            var cp = this.currentPlanData;
            this.clearLine();
            for (var o = 0, len = cp.length; o < len; o++) {
                if (o > 0) {
                    //var n = g("#J_day-" + a.currentDayIndex).find(".sortable-node").get(o - 1);
                    var p = {
                        show: true,
                      //  $distanceDom: g(n).find(".J_traffic-dest"),
                        //$timeDom: g(n).find(".J_traffic-time"),
                       // $detailDom: g(n).find(".J_detail-more"),
                      //  $detailPanel: g(n).find(".J_traffic-panel"),
                        index: o - 1
                    };
                    this.getTraffic(cp[o - 1], cp[o], p);
                }
            }
			/*setTimeout(function(){
			//self._map.setViewport(self.bounds);
			self._map.setCenter(new BMap.Point(cp[0].map_x, cp[0].map_y));
			self._map.setZoom(15);
			//self.run();
			},4000);*/
        },
        
        createPoint: function(scenceList, op) {
            op.isCenter = op.isCenter || false;
            $.extend(true,this, op);
            this.showCount = op.showCount || 0;
            this.type = op.type || "scene";
            this.markIconUrl = op.markIconUrl || "/static/plan/img/map-icon.png";
            this.defaultLabelStyle = "map-default-label";
            this.activeLabelStyle = "map-current-label";
            if (this.isClear) {
                this.clearOverlays();
                this.points = [];
                this.polyLine = [];
                this.labelList = [];
                this.currentMarker = null;
                this.currentLabel = null;
                this.currentPop = null
            }
            this.paths = scenceList;
            this.points = this.points || [];
            this.scenePoints = [];
            var self = this,
                n, o, r;
            if (this.type == "scene") {
                $(scenceList).each(function(index, item) {
                    //j.updateAllPointData(w);
                    if (item.map_x && item.map_x != "0") {
                        r = n = new BMap.Point(item.map_x, item.map_y);
                        r.xid = n.xid = item.xid || "0";
                        self.allPoint[r.xid]["xidpoint"] = n;
                       // var t = self.isInList(n.xid, self.currentPlanData);
                       // if (!t) {
                        var te = self.checkShowList(item);
                            if (te) {
                                var v = {
                                    divClass: "mark"
                                };
                              /*  if (parseInt(item.type, 10) == 2) {
                                    v.divClass = "food-fullMarker"
                                }
                                if (parseInt(item.type, 10) == 3) {
                                    v.divClass = "hotel-fullMarker"
                                }*/
                                self.createMarker(n, v, true);
                            } else {
                                self.createMarker(n, {
                                    markIconUrl: "../images/map-icon.png",
                                    iconWidth: 14,
                                    iconHeight: 18
                                }, false);
                            }
                       // }
                        if (te) {
                            self.scenePoints.push(r);
                        }
                        self.points.push(n)
                    }
                })
            } else {
               
                    if (this.type == "plan") {
                        g(s).each(function(t, u) {
                            j.updateAllPointData(u);
                            if (u.map_x && u.map_x != "0") {
                                n = new BMap.Point(u.map_x, u.map_y);
                                n.xid = u.xid || "0";
                                q.createMarker(n, {}, true);
                                q.points.push(n)
                            }
                        })
                    }
            }
			if (this.isCenter && this.scenePoints.length > 0) {
                this.setCenterAndZoom(this.scenePoints)
            }
            if (self.tempCenterAndZoom) {
               // this.setCenterAndZoom(this.points, p.tempCenterAndZoom)
            }
        },
        setShowList : function(list){
        	//this.showList = list;
        	var temp = {};
        	for(var i=0,len = list.length;i<len;i++){
        		
        		var item = list[i],
        			xid = item.xid;
        		temp[xid] = item;
        		
        	}
        	this.showList = temp;
        	
        	
        },
        checkShowList : function(sdata){
        	var showlist = this.showList;
        	if(showlist[sdata.xid]){
        		
        		return true;
        	}else{
        		
        		return false;
        	}
        	
        },
		getSceneList : function(data){
			var list = data.list||data;
			this.sceneList = list;
			var allPoint = {};
			for(var i=0,len=list.length;i<len;i++){
				allPoint[list[i].xid]=list[i];
			
			}
			this.allPoint = allPoint;
			return allPoint;
		
		},
		getViewPoints : function(sceneList){
			var points = [];
			$(sceneList).each(function(index,item){
				points.push(new BMap.Point(item.map_x, item.map_y));
			
			});
			return points;
		
		},
        setCenterAndZoom: function(p, r) {
            var o = this._map.getViewport(p);
            var n = r && r.center || o.center;
            var q = r && r.zoom || o.zoom;
            this._map.centerAndZoom(n, q);
            //a.mapZoom = q
        },
        resetCenter: function(o) {
            var n = [];
            g(o).each(function(p, q) {
                if (q.map_x && q.map_x != "0") {
                    n.push(new BMap.Point(q.map_x, q.map_y))
                }
            });
            this.setCenterAndZoom(n)
        },
        clearOverlays: function() {
            this._map.clearOverlays()
        },
		inListIndex: function(g, h) {
            var i = false;
            $(h).each(function(j, k) {
                if (k.xid == g) {
                    i = j;
                    return
                }
            });
            return i
        },
        createMarker: function(point, op, z) {
            var self = this,
                opt = op || {}, 
				markIcon = opt.markIconUrl || this.markIconUrl,
                iW = opt.iconWidth || 14,
                iH = opt.iconHeight || 18,
                xid = point.xid,
                scence = self.allPoint[xid],
				y = this.inListIndex(xid, this.currentPlanData);
            var t = new BMap.Icon(markIcon, new BMap.Size(iW, iH));
            if (!scence) {
                return
            }
            if (z||y) {
                if (y !== false) {
                    point.marker = new fulloverlay(point, scence[self.labelType], self._map, {
                        divText: (y + 1),
                        zIndex: 3,
                        "class": "plan-text",
                        divClass: "plan-fullMarker"
                    }, self);
                    this._map.addOverlay(point.marker);
                } else {
                    point.marker = new fulloverlay(point, scence[self.labelType], self._map, {
                        "class": "scenelist-text",
                        divClass: op.divClass
                    }, self);
                    this._map.addOverlay(point.marker)
                }
            } else {
                point.marker = new BMap.Marker(point, {
                    icon: t,
                    title: scence[self.labelType]
                });
                this._map.addOverlay(point.marker);
                var o;
                point.marker.addEventListener("mouseover", function() {
                    o = setTimeout(function() {
                        self.activeMarker(point, {
                            isCenter: false
                        })
                    }, 200)
                });
                point.marker.addEventListener("mouseout", function() {
                    if (o) {
                        clearTimeout(o)
                    }
                    if (this.status) {
                        
                           // if (x.marker.getIcon().imageUrl == "/static/plan/img/hover-map-icon.png") {
                                var B = new BMap.Icon("../images/map-icon.png", new BMap.Size(14, 18));
                                point.marker.setIcon(B)
                           // }
                        
                        point.marker.setTop(false);
                    }
                });
                $(point.marker).bind("mouseout", function() {
                   
                    if (this.status) {
                        
                           // if (x.marker.getIcon().imageUrl == "/static/plan/img/hover-map-icon.png") {
                                var B = new BMap.Icon("../images/map-icon.png", new BMap.Size(14, 18));
                                point.marker.setIcon(B)
                           // }
                        
                        point.marker.setTop(false);
                    }
                });
                point.marker.addEventListener("click", function() {
                    this.status = false;
                    self.oldMarker = self.currentMarker;
                    self.currentMarker = this;
                    if (self.oldMarker) {
                        self.oldMarker.status = true;
                        $(self.oldMarker).trigger("mouseout", {})
                    }
                    self.createPop(point, {
                        popWidth: self.popWidth
                    });
                    
                })
               /* if (x.marker) {
                    x.marker.addEventListener("mouseover", function() {
                        o = setTimeout(function() {
                            v.activeMarker(x, {
                                isCenter: false
                            })
                        }, 200)
                    });
                    g(x.marker).bind("mouseout", function() {
                        if (this.status) {
                            if (x.marker.getIcon().imageUrl == "/static/plan/img/hover-collect-icon.png") {
                                if (x.type == 1) {
                                    var A = new BMap.Icon("/static/plan/img/scene-collect-icon.png", new BMap.Size(15, 20))
                                } else {
                                    if (x.type == 2) {
                                        var A = new BMap.Icon("/static/plan/img/food-collect-icon.png", new BMap.Size(15, 20))
                                    } else {
                                        var A = new BMap.Icon("/static/plan/img/hotel-collect-icon.png", new BMap.Size(15, 20))
                                    }
                                }
                                x.marker.setIcon(A)
                            } else {
                                if (x.marker.getIcon().imageUrl == "/static/plan/img/hover-map-icon.png") {
                                    var B = new BMap.Icon("/static/plan/img/map-icon.png", new BMap.Size(14, 18));
                                    x.marker.setIcon(B)
                                }
                            }
                            x.marker.setTop(false)
                        }
                    });
                    x.marker.addEventListener("mouseout", function() {
                        if (o) {
                            clearTimeout(o)
                        }
                        if (this.status) {
                            if (x.marker.getIcon().imageUrl == "/static/plan/img/hover-collect-icon.png") {
                                if (x.type == 1) {
                                    var A = new BMap.Icon("/static/plan/img/scene-collect-icon.png", new BMap.Size(15, 20))
                                } else {
                                    if (x.type == 2) {
                                        var A = new BMap.Icon("/static/plan/img/food-collect-icon.png", new BMap.Size(15, 20))
                                    } else {
                                        var A = new BMap.Icon("/static/plan/img/hotel-collect-icon.png", new BMap.Size(15, 20))
                                    }
                                }
                                x.marker.setIcon(A)
                            } else {
                                if (x.marker.getIcon().imageUrl == "/static/plan/img/hover-map-icon.png") {
                                    var B = new BMap.Icon("/static/plan/img/map-icon.png", new BMap.Size(14, 18));
                                    x.marker.setIcon(B)
                                }
                            }
                            x.marker.setTop(false)
                        }
                    });
                    x.marker.addEventListener("click", function() {
                        this.status = false;
                        v.oldMarker = v.currentMarker;
                        v.currentMarker = this;
                        if (v.oldMarker) {
                            v.oldMarker.status = true;
                            g(v.oldMarker).trigger("mouseout", {})
                        }
                        v.createPop(x, {
                            popWidth: v.popWidth
                        });
                        c.nslog(location.href, 1702, {
                            cmd: "click",
                            pos: "edit-map-scene-click"
                        })
                    })
                }*/
            }
        },
        createPop: function(data, q) {
            var cp = this.currentPop;
            var xid = data.xid;
            var s = this.allPoint[xid];
            var t = q.popWidth;
            var r = {
                left: q.left,
                top: q.top,
                move: true
            };
            var self = this;
            if (!this.options.showPop) {
                return
            }
            var bindEvent = {
            		'closebtn':function(target,item){
		           		 $(item).unbind('click.closebtn').bind("click.closebtn",function(){
		        			 target.hide();
		        			 
		        		 });
            			},
            		"addToPlan" :function(target,item){
            			 $(item).unbind('click.addToPlan').bind("click.addToPlan",function(){
            				 self.options.planCon.addPlan(s);
            				 target.hide();
		        			 
		        		 });
            			
            		}
            };
            if (!cp) {
            	cp = new mapoverlay(data, '<div class="map-pop-wrap">'+this.renderTemplate(s)+'</div>',{},self._map,self,bindEvent);
        		
        		
        	
            	cp.render(this._map);
            } else {
            	cp.setData(this.renderTemplate(s),bindEvent);
            	cp.reposition(data, r);
            }
            this.currentPop = cp;
        },
        renderTemplate : function(data){
        	var type = this.type,
        		td = {
        		   list : data	
        	    },
        		_html = '';
        	switch(type){
        		case "scene" : 
        			_html += this.bt(this.options.mapPopTemp, td);
        			break;
        	
        	}
        	return _html;
        	
        },
        activeMarker: function(point, opt) {
            var v = opt.isCenter || false;
            var s = opt.showPop;
            var q = point.xid || opt.xid;
            var r = this._map.getBounds().containsPoint(point);
            if (!r) {
                v = true;
            }
            
            var u = this.allPoint[q];
           
           
            var w = new BMap.Icon("../images/hover-map-icon.png", new BMap.Size(15, 20));
            point.marker.setIcon(w)
           
            point.marker.setTitle(u[this.labelType]);
            point.marker.setTop(true);
            point.marker.status = true;
            var t = point.marker;
            if (!point) {
                return
            }
            if (v) {
                this._map.panTo(point)
            }
        },
        getTraffic: function(sp, ep, r) {
            var self = this;
            if (sp.map_y != ep.map_y && sp.map_x != ep.map_x && sp.map_x && ep.map_x) {
                var p;
                var t = parseInt(sp.traffic || r.traffic || 3);
                var q = new BMap.Point(sp.map_x, sp.map_y);
                var o = new BMap.Point(ep.map_x, ep.map_y);
                if (t == 1) {
                    p = new BMap.WalkingRoute(q)
                } else {
                    if (t == 2) {
                        p = new BMap.DrivingRoute(q)
                    } else {
                        p = new BMap.TransitRoute(q, {
                            pageCapacity: 1
                        })
                    }
                }
                p.setSearchCompleteCallback(function(z) {
					var b =new Array();
					var addPoints = function(points){
						for(var i = 0; i < points.length; i++){
							self.bounds.push(points[i]);
							b.push(points[i]);
						}
					};
                    if (p.getStatus() == BMAP_STATUS_SUCCESS) {
                        sp.polyLine = [];
                        var B = z.getPlan(0);
                        if (!B) {
                            if (r.$distanceDom && r.$timeDom) {
                                r.$distanceDom.text("暂无");
                                r.$timeDom.text("")
                            }
                            return
                        }
                        if (r.show) {
                            if (t == 1) {
                                for (var A = 0, x = B.getNumRoutes(); A < x; A++) {
                                    var E = B.getRoute(A);
                                    var C = new BMap.Polyline(E.getPath(), {
                                        strokeColor: "#fe847d",
                                        strokeWeight: 6,
                                        strokeOpacity: 1
                                    });
                                    s.polyLine.push(C);
                                    u.polyLine.push(C);
                                    s._map.addOverlay(C)
                                }
                            } else {
                                if (t == 2) {
                                    for (var A = 0, x = B.getNumRoutes(); A < x; A++) {
                                        var E = B.getRoute(A);
										 addPoints(E.getPath());
                                        var C = new BMap.Polyline(E.getPath(), {
                                            strokeColor: "#fe847d",
                                            strokeWeight: 6,
                                            strokeOpacity: 1
                                        });
                                        self.polyLine.push(C);
                                        sp.polyLine.push(C);
                                       self._map.addOverlay(C)
									  // map.setViewport(bounds);
    
    
									  
                                    }
									 
									 self.linesPoints[self.linesPoints.length] = b;
                                } else {
                                    for (var A = 0, x = B.getNumRoutes(); A < x; A++) {
                                        var D = B.getRoute(A);
                                        if (D.getDistance(false) > 0) {
                                            var C = new BMap.Polyline(D.getPath(), {
                                                strokeColor: "#fe847d",
                                                strokeWeight: 6,
                                                strokeOpacity: 1
                                            });
                                            s.polyLine.push(C);
                                            u.polyLine.push(C);
                                            s._map.addOverlay(C)
                                        }
                                    }
                                    for (A = 0, x = B.getNumLines(); A < x; A++) {
                                        E = B.getLine(A);
                                        C = new BMap.Polyline(E.getPath(), {
                                            strokeColor: "#fe847d",
                                            strokeWeight: 6,
                                            strokeOpacity: 1
                                        });
                                        s.polyLine.push(C);
                                        u.polyLine.push(C);
                                        s._map.addOverlay(C)
                                    }
                                }
                            }
                        }
                        if (r.$distanceDom && r.$timeDom) {
                            var w = B.getDistance(true);
                            var y = B.getDuration(true);
                            var v = t == 1 ? "步行 " : t == 2 ? "自驾 " : "公交 ";
                            r.$distanceDom.text(v + w);
                            s.renderTrafficPanel({
                                traffic: t,
                                firstPlan: B,
                                dom: r.$detailPanel,
                                start: u,
                                end: n
                            });
                            r.$timeDom.text(y);
                            u.traffic_dist = w;
                            u.traffic_time = y
                        }
                        self.changeTrafficType(t, r, sp)
                    } else {
                        if (r.isCircle === false) {
                            s.changeTrafficType(t, r, u);
                            r.$distanceDom.text("暂无");
                            r.$timeDom.text("");
                            r.$detailPanel.html(b("J_traffic-panel-tpl", {
                                list: [],
                                from: u.name,
                                to: n.name,
                                traffic: t
                            }));
                            return
                        }
                        if (t == 1) {
                            s.changeTrafficType(1, r, u);
                            if (r.$distanceDom && r.$timeDom) {
                                r.$distanceDom.text("暂无");
                                r.$timeDom.text("");
                                r.$detailPanel.html(b("J_traffic-panel-tpl", {
                                    list: [],
                                    from: u.name,
                                    to: n.name,
                                    traffic: t
                                }))
                            }
                        } else {
                            if (t == 2) {
                                u.traffic = 1;
                                s.getTraffic(u, n, r)
                            } else {
                                u.traffic = 2;
                                s.getTraffic(u, n, r)
                            }
                        }
                    }
                });
                p.search(q, o)
            } else {
                if (r.$distanceDom && r.$timeDom) {
                    r.$distanceDom.text("暂无");
                    r.$timeDom.text("")
                }
            }
        },
        renderTrafficPanel: function(p) {
            var o = [];
            if (p.traffic == 1 || p.traffic == 2) {
                var n = p.firstPlan.getRoute(0);
                var s = n.getNumSteps();
                for (var q = 0; q < s; q++) {
                    o.push(n.getStep(q).getDescription(false))
                }
            } else {
                var r = p.firstPlan.getDescription(false);
                o = r.match(/(乘坐|步行)[^乘坐|步行]+/ig)
            }
            p.dom.html(b("J_traffic-panel-tpl", {
                list: o,
                from: p.start.name,
                to: p.end.name,
                traffic: p.traffic
            }))
        },
        changeTrafficType: function(p, o, n) {
            /*if (a.inEditPage) {
                if (a.currentPlanData && a.currentPlanData[n.position]) {
                    if (!a.orginPlanData[n.position].traffic || a.orginPlanData[n.position].traffic != n.traffic) {
                        g.post("/plan/ajax/plantrips/update", {
                            plan_trips_id: n.plan_trips_id,
                            plan_days_id: n.plan_days_id,
                            traffic: n.traffic || 3,
                            traffic_dist: n.traffic_dist || "",
                            traffic_time: n.traffic_time || "",
                            bdstoken: F.context("user").bdstoken || 0
                        }, function() {}, "json")
                    }
                } else {
                    g.post("/plan/ajax/plantrips/update", {
                        plan_trips_id: n.plan_trips_id,
                        plan_days_id: n.plan_days_id,
                        traffic: n.traffic || 3,
                        traffic_dist: n.traffic_dist || "",
                        traffic_time: n.traffic_time || "",
                        bdstoken: F.context("user").bdstoken || 0
                    }, function() {}, "json")
                }
            }*/
        },
        clearLine: function() {
            var n = this;
            $(this.polyLine).each(function(o, p) {
                n._map.removeOverlay(p)
            });
            this.polyLine = []
        }

    });
    module.exports = lymap;
});