// JavaScript Document
var slide;
var routes = null;

var ROUTES = {
	_data : {},
	_ui : {},
	_curData : null,
	curUI : null,
	
	/**
	 * Add the route to the data repository and set it as the current data
	 */
	addData : function(obj) {
		if (!obj || !obj.city) return;
		this._data[obj.city] = obj;
		this._curData = obj;
	},
	
	addUI : function(key, obj) {
		if (!obj) return;
		this._ui[key] = obj;
		//this.curUI = obj;
	},

	getBaseDir : function() {
		return this._curData.imgDir;
	},
	
	getImageDir : function() {
		return this._curData.imgDir + this._curData.name + "/";
	},
	
	getValueCategory : function(name) {
		return this._curData.category[name];
	},
	
	getUI : function(name) {
		return this._ui[name];
	},
	
	setCurrentUI : function(ui) {
		if (this.curUI == ui) return;
		if (this.curUI) {
			this.curUI.display(false);
		}
		this.curUI = ui;
		this.curUI.display(true);
	}
};

var costWheel = {
	types : [],
	scrollDuration : 400,
	itemWidth : 170,
	currentIndex : 0,
	container: null,
	virtualContainer : null,
	
	initContent : function (obj) {
		var cat = obj.category;
		var arr = [];
		for (var i in cat) {
			arr.push(i);
		}
		this.types = arr;
		
		var wrapper = removeWhiteNode($('valueCategoryWrapper'));
		for (var i=0; i< arr.length; i++) {
			var elem = new Element('div', {'class': 'vc_item', href: "javascript:void(0);"});
			elem.set('html', arr[i] + " yuan");
			elem.idx = arr[i];
			elem.inject(wrapper);
			var imgUrl = ROUTES.getBaseDir() + arr[i] + '-yuan.gif';
			elem.style['background'] = 'url(' + imgUrl + ') no-repeat';
			elem.addEvent('click', this._clickType);
		}
	
		this.initVirtual($('valueCategory'));
		this.initSlide();
		
		for (var i in cat) {
			cat[i].type = i;
		}
		var cost = new TypeCategory(cat[0]);
		ROUTES.addUI(arr[0], cost);
		ROUTES.setCurrentUI(cost);
	},
	
	initVirtual : function(elem) {
		this.container = elem;
		var v = elem.clone(true);
		v.inject(elem.getParent());
		v.style.display = 'none';
		v.style.zIndex = 80;
		var w = v.getFirst();
		var c = w.getFirst();
		this._copyVirtual(c, this.types.length);
		this._copyVirtual(c, this.types.length);
		this.virtualContainer = v;
	},
	
	initSlide : function() {
		var id = 'valueCategory';
		slide = new Fx.Scroll(costWheel.virtualContainer, {
			wait : false,
			duration : costWheel.scrollDuration,
			offset : { x: 0, y: 0},
			transition: Fx.Transitions.Quad.easeInOut
		});
		slide.start(0, 0);
	},
	
	showContainer : function(bln) {
		this.container.style.display = bln ? 'block' : 'none';
	},
	
	showVirtual : function(bln) {
		this.virtualContainer.style.display = bln ? 'block' : 'none';
	},
	
	_copyVirtual : function(elem, count) {
		var parent = elem.getParent();
		for (var i=0; i< count; i++) {
			var copy = elem.clone(true);
			elem.idx = i + 1;
			copy.inject(parent);
			copy.idx = parent.getChildren().length;
			elem = elem.getNext();
		}
	},
	
	_clickType : function (event) {
		event = new Event(event).stop();
		var elem = event.target;
		focusOn(elem);
		//console.log(elem.idx);
		var routes = null;
		if (!(routes = ROUTES.getUI(elem.idx))) {
			routes = new TypeCategory(ROUTES.getValueCategory(elem.idx));
			ROUTES.addUI(elem.idx, routes);
		}
		ROUTES.setCurrentUI(routes);
	}
	
};

function getFirst(obj) {
	for ( var i in obj) {
		return obj[i];
	}
}

var rc = [];

var TypeCategory = new Class({
	name : null,
	initialize : function(data) {
		this.name = data.type;
		var arr = [];
		for (var i in data) {
			if (!(data[i] instanceof Array)) continue;
			for (var j=0; j<data[i].length; j++) {
				if (!arr[j]) {
					arr[j] = [];
				}
				arr[j].push(data[i][j]);
			}
		}
		_O = arr;

		//var p = removeWhiteNode($('magicBox'));
		var slide = new Element('div', {'class': 'magicBox'});
		slide.inject(document.body);
		//var e = p.getFirst();
		var elem = new Element('div', {'class': 'typeCatContent'});
		elem.inject(document.body);
		for(var i=0; i<arr.length; i++) {
			//var n = e.getNext();
			var item = new TypeItem(arr[i][0], elem);
			var route = new RouteCategory(arr[i], slide, item);
			item.setSlide(route);
			rc.push(route);
			route.hide();
			//e = n;
		}
		this._ui = elem;
		this._slideUI = slide;
	},
	
	display : function(bln) {
		this._ui.style['display'] = bln ? "block" : "none";
		this._slideUI.style['display'] = bln ? "block" : "none";
	}
});

var _O;

var TypeItem = new Class({
	_data : null,
	_image : null,
	initialize: function(data, elem) {
		this._data = data;
		var holder = new Element('div', {'class': 'typeItem'});
		var img = new Element('img', {
			src: ROUTES.getImageDir() + data.img,
			width: 140,
			height: 130
		});
		this._image = img;
		var _this = this;
		img.addEvents({
			'click': function() {
				$('details').fade(1);
				_this.onClick();
			},
			'mouseover': function() {
				_this._slide.endTransaction();
				_this._slide.inside = true;
				_this.showSlide();},
			'mouseout': function() {
				_this._slide.inside = false;
				setTimeout(function() {_this.hideSlide();},20);
			}
					  });
		img.inject(holder);
		this._ui = holder;
		holder.inject(elem);
	},
	
	onClick : function() {
		this._slide.beginTransaction();
		this._slide.inside = false;
		this.hideSlide();
		displayPoint(this._data);
		center(this._data);
	},
	
	setPoint : function(point) {
		this._point = point;
		this.refresh(this._point._data);
	},
	
	refresh : function(data) {
		this._data = data;
		this._image.set('src', ROUTES.getImageDir() + data.img);
	},
	
	showSlide: function() {
		this._slide.show();
		this._slide.focused = true;
	},
	
	hideSlide: function() {
		this._slide.hide();
	},
	
	toggle: function() {
		this._slide.toggle();
	},
	
	setSlide: function(slide) {
		this._slide = slide
	}
});

var tipId = 0;
var Point = new Class({
	_parent : null,
	_data : null,
	_ui : null,
	
	display : function() {
		//this._parent.refreshTrigger(this._data);
		displayPoint(this._data);
	},
	
	initialize : function(parent, data) {
		this._parent = parent;
		this._data = data;
		var id = tipId++;
		var it = new Element('div', {'class': 'nav_item nav_list_item'});
		var img = new Element('img', {
			'class': 'tipper',
			'src': ROUTES.getImageDir() + data.img,
			'width': 130,
			'height': 130,
			'rel': "{content: 'tip" + id + "'}"
		});
		var tips = new Element('div', {
			'id': "{content: 'tip" + id + "'}",
			'class': 'tipContainer'
		});
		tips.set('html', data.desc);
		img.inject(it);
		tips.inject(it);
		
		this._ui = it;
		var _this = this;
		it.addEvent('click', function(e) {_this.onClick(e);});
	},
	
	onClick : function(e) {
		this._parent.beginTransaction();
		this._parent.focusOn(this);
		this.display();
		this._parent.inside = false;
		this._parent.hide();
		center(this._data);
	}
});

var RouteCategory = new Class({
	_data : null,
	_childs : null,
	_trigger : null,
	_ui : null,
	txn : false,
	initialize : function(data, parent, trigger) {
		this._data = data;
		this._trigger = trigger;
		elem = new Element('div', {'class': 'nav_list'});
		this._ui = elem;
		//alert(data.length);
		for (var i=0; i< data.length; i++) {
			this.add(new Point(this, data[i]));
		}
		elem.inject(parent);
		//elem = $(elem);
		var s = new Fx.Slide(elem, {
								   mode: 'horizontal', 
								   //link: 'cancel',
								   duration: 400});
		var r = this;
		elem.addEvents({
			'mouseover' : function() {
				r.inside = true;
				r.show();},
			'mouseout' : function() {
				r.inside = false;
				setTimeout(function() {r.hide();}, 20);
				}
		});
		
		this._slide = s;
	},
	
	beginTransaction : function() {
		this._slide.options.link = '';
	},
	
	endTransaction : function() {
		this._slide.options.link = 'cancel';
	},
	
	focusOn : function(point) {
		this._trigger.setPoint(point);
	},
	
	add : function(child) {
		if (!this._childs) this._childs = [];
		this._childs.push(child);
		child._ui.inject(this._ui);
	},
	
	toggle: function() {
		this._slide.toggle();
	},
	
	hide : function() {
		if (!this.inside) {
			if (detailsCover) detailsCover.fade(0);
			this._slide.slideOut();
		}
	},
	
	show : function() {
		if (detailsCover) detailsCover.fade(0.7);
		this._slide.slideIn();
	}
});

var details = null;
var detailsCover = null;

window.addEvent('load', function() {	
	// invoke resize here because there is a little timing problem in firefox
	resetNavSize();
	loadMap();
	
	new MooTooltips({
		hovered: '.tipper',
		container: $('magicBox'),
		ToolTipClass:'ToolTips',	// tooltip display class
		toolTipPosition: 1, // -1 top; 1: bottom - set this as a default position value if none is set on the element
		sticky:false,		// remove tooltip if closed
		fromTop: 0,		// distance from mouse or object
		fromLeft: -10,	// distance from left
		duration: 300,		// fade effect transition duration
		fadeDistance: 20    // the distance the tooltip starts the morph
	});
	
	loadRoutes();
});

function resetNavSize() {
	var footer = $("footer");
	if (!footer) return;
	var height = footer.offsetTop;
	$("typeCat").style["height"] = height + "px";
	$("typeCatShadow").style["height"] = height + "px";
	// do resize details cover
	details = $('details');
	detailsCover = $('detailsCover');
	detailsCover.style['width'] = details.offsetWidth + 'px';
	detailsCover.style['height'] = $('content').offsetHeight + 'px';
}

function focusOn(elem) {
	costWheel.showVirtual(true);
	costWheel.showContainer(false);
	var n = 0;
	var wrapper = elem.getParent();
	var previous = elem.getPrevious();
	while(elem.getPrevious()) {
		n++;
		wrapper.getFirst().inject(wrapper);
	}
	var x = costWheel.currentIndex + n;
	if (n > 0) {
		slide.options.duration = costWheel.scrollDuration*n;
		slide.start(costWheel.itemWidth*x, 0);
	}
	var typesLen = costWheel.types.length;
	costWheel.currentIndex = x < typesLen ? x : x - typesLen;

	setTimeout(function() {
		if (x >= typesLen) {
			var a = costWheel.virtualContainer.scrollLeft;
			var b = typesLen * costWheel.itemWidth;
			costWheel.virtualContainer.scrollLeft = a - b;
		}
		costWheel.showContainer(true);
		costWheel.showVirtual(false);
	}, costWheel.scrollDuration*n+10);
}

function removeWhiteNode(elem) {
	var child = elem.getFirst();
	while(child) {
		var next = child.getNext();
		if (child.nodeType != 1) {
			elem.removeChild(child);
		}
		child = next;
	}
	return elem;
}

function displayPoint(data) {
	var content = "<p>看点：" + data.desc + "</p><p>地点："+data.address+"</p>";
	$('point_title').set('html', data.name);
	$('point_content').set('html', content);
	$('point_img').set('src', ROUTES.getImageDir() + data.img);
}

function loadRoutes() {
	var jSonRequest = new Request.JSON({
		url: 'routes.php', 
		onComplete: initRoutes
	}).send();
}

function initRoutes(obj){
	routes = obj;
	ROUTES.addData(obj);
	costWheel.initContent(obj);
}

var clickLocation;
var id = 0;
var map = null;

function center(data) {
	var arr = data.latlng.split(',');
	if (arr.length != 2 || arr[0].length ==0 || arr[1].length ==0) 
		return;
	lat = parseFloat(arr[0]);
	lng = parseFloat(arr[1]);
	var point = new GLatLng(lat, lng);
	map.setCenter(point, 16);
	createMarker(map, point, "<strong>"+data.name +"</strong><p>"+ data.desc+"</p>");
}

function loadMap() {
  if (GBrowserIsCompatible()) {
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GSmallMapControl());
	map.addControl(new GScaleControl());
	var point = new GLatLng(31.217609,121.45699);
	map.setCenter(point, 16);//39.917, 116.397
	createMarker(map, point, "Shanghai");
	return;
	GEvent.addListener(map, "click", function(overlay, latlng) {
		clickLocation = latlng;
		//alert("I'm here: " + map.fromLatLngToDivPixel(latlng));
		var point = new GLatLng(clickLocation.lat(), clickLocation.lng());
		createMarker(map, point, id++);
	});
	
	return;
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var lngSpan = northEast.lng() - southWest.lng();
	var latSpan = northEast.lat() - southWest.lat();
	for (var i = 0; i < 10; i++) {
	  var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
			southWest.lng() + lngSpan * Math.random());
		createMarker(map, point, id++);
	}
  }
}

function createMarker(map, point, desc) {
            var marker = new GMarker(point, {draggable: false});

            GEvent.addListener(marker, "click", function() {
                var p = marker.getLatLng();
                marker.openInfoWindowHtml(desc);
				//"<strong>XXXXX 专卖 Store #" + id + "</strong> + "<br/>Lat: "+p.lat() + ", Lng: " + p.lng()
            });

            map.addOverlay(marker);
}
