AP = {};

/***
 *	General
 ****/
AP.Widget = function(element) {
	this.element = element;
	if(this.element.retrieve('widget'))
		return true;
	this.element.store('widget', this);
	this.element.setProperty('widget', 'Widget');
	
	return false;
};
AP.Widget.prototype = {
	options: {},
	toElement: function() {
		return this.element;
	},
	destroy: function() {
		this.element.destroy();
	}
};

/**
 *	Gallery
 ******************/

AP.Widget.Gallery = function(element, options) {
	if(AP.Widget.apply(this, [element, options]))
		return this.element.retrieve('widget');
	this.element.setProperty('widget', 'Gallery');

	this.element.addEvent('click:relay(img)', function(e, target){
		e.preventDefault();
		this.show(target);
	}.bind(this));
};
Object.append(AP.Widget.Gallery.prototype, AP.Widget.prototype);
Object.append(AP.Widget.Gallery.prototype, {
	show: function(img) {
		this.current = img;
		this.gallery = new Element('div', {
			'class': 'fullscreen',
			'html': '<img src="images/control_left.jpg" id="gPrev" onclick="void(0)"><img src="images/pause_slider.png" id="gPlay" onclick="void(0)"><img src="images/closelabel.gif" id="gClose" onclick="void(0)"><img src="images/control_right.jpg" id="gNext" onclick="void(0)"><img id="bigPic" \><p id="gLabel">' + img.getProperty('alt') + '</p>',
			'events': {
				click: function(e) {
					switch(e.target.id) {
						case 'gNext':
							this.stopSlideShow();
							this.next();
						break;
						case 'gPrev':
							this.stopSlideShow();
							this.prev();
						break;
						case 'gClose':
							this.stopSlideShow();
							this.gallery.dispose();
						break;
						case 'gPlay':
							(this.slideId == null)?this.startSlideShow():this.stopSlideShow();
						break;
					}
				}.bind(this)
			}
		});
		
		document.body.grab(this.gallery);
		
		this.update();
		this.startSlideShow();
	},
	getSize: function() {
		var winSize = window.getSize();
		var winRatio = winSize.x / winSize.y;
		var eltSize = this.current.getSize();
		var eltRatio = eltSize.x / eltSize.y;
		var nEltSize = {x: 0, y: 0};
		var border = 50;
		if(eltRatio > winRatio) {
			nEltSize.x = winSize.x - (3 * border);
			nEltSize.y = Math.round((eltSize.y * nEltSize.x) / eltSize.x);
		} else {
			nEltSize.y = winSize.y - (2 * border);
			nEltSize.x = Math.round((eltSize.x * nEltSize.y) / eltSize.y);
		}
		return nEltSize;
	},
	update: function() {
		if(this.current) {
			this.prevImg = this.current.getParent('li').getPrevious();
			if(this.prevImg) {
				this.prevImg = this.prevImg.getElements('img')[0];
				$('gPrev').removeClass('hidden');
			} else
				$('gPrev').addClass('hidden');

			this.nextImg = this.current.getParent('li').getNext();
			if(this.nextImg) {
				this.nextImg = this.nextImg.getElements('img')[0];
				$('gNext').removeClass('hidden');
			} else
				$('gNext').addClass('hidden');
			var size = this.getSize();
			$('bigPic').set({src: this.current.src, width: size.x, height: size.y});
			$('gLabel').set('html', this.current.get('alt'));
		} else
			this.stopSlideShow();
	},
	next: function() {
		this.current = this.nextImg;
		this.update();
	},
	prev: function() {
		this.current = this.prevImg;
		this.update();
	},
	startSlideShow: function() {
		this.slideId = setInterval(this.next.bind(this), 4000);
		$('gPlay').set('src', 'images/pause_slider.png');
	},
	stopSlideShow: function() {
		clearInterval(this.slideId);
		this.slideId = null;
		$('gPlay').set('src', 'images/play_slider.png');
	}
});

/**
 *	Tabs
 * 	<ul widget="Tabs">
 * 		<li title="Onglet 1"></li>
 * 		<li title="Onglet 2"></li>
 * 	</ul>
 ******************/
AP.Widget.Tabs = function(element, options) {
	if(AP.Widget.apply(this, [element, options]))
		return this.element.retrieve('widget');
	this.element.setProperty('widget', 'Tabs');

	this.current = null;
	this.links = new Element('ul', {
		'class': 'Tabs_links'
	});
	this.links.store('widget', this);

	var tabs = this.element.getChildren('div.section');
	for (var i=0; i < tabs.length; i++) {
		var link = new Element('li', {
			'html': tabs[i].getProperty('title'),
			'class': 'Tabs_title',
			'onclick': 'void(0)'
		});
		link.store('panel', tabs[i]);
		this.links.appendChild(link);
	}

	this.element.parentNode.insertBefore(this.links, this.element);
	this.showPanel(this.links.getElement('li.Tabs_title'));
};
Object.append(AP.Widget.Tabs.prototype, AP.Widget.prototype);
Object.append(AP.Widget.Tabs.prototype, {
	showPanel: function(elt) {
		if(this.current != elt) {
			if(this.current) {
				this.current.removeClass('Tabs_active');
				this.current.retrieve('panel').removeClass('Tabs_active');
			}
			this.current = elt;
			this.current.addClass('Tabs_active');
			this.current.retrieve('panel').addClass('Tabs_active');
		}
		
		var panel = this.current.retrieve('panel');
		if((panel.id == 'map') && !panel.init) {
			init_map();
			panel.init = true;
		}
	}
});

AP.Widget.Tree = function(element, options) {
	if(AP.Widget.apply(this, [element, options]))
		return this.element.retrieve('widget');
	this.element.setProperty('widget', 'Tree');
	//new Tree(this.element);
};
Object.append(AP.Widget.Tree.prototype, AP.Widget.prototype);
Object.append(AP.Widget.Tree.prototype, {
	options: {
		animate: true,
		fadeOpacity: 1,
		selector: 'img.expand',
		listSelector: 'li',
		childSelector: 'ul',
		textSelector: 'span'
	}
});

function init_map() {
	var position = new google.maps.LatLng(POSITION.lat, POSITION.lon);
	
	map = new google.maps.Map($('map'), {
		center: new google.maps.LatLng(CENTER.lat, CENTER.lon),
		zoom: 4,
		mapTypeId: google.maps.MapTypeId.TERRAIN
	});
	
//	var layer = new google.maps.KmlLayer('http://maps.google.com/maps/ms?ie=UTF8&hl=fr&t=p&source=embed&authuser=0&msa=0&output=kml&msid=203541511413260171897.000443be2e7a4e0ffb12f', {map: map, preserveViewport: true});
//  au dessus: ancien code de couche d'importation du fichier KML de l'itineraire
//  en dessous: nveau code d'importatin de l itineraire voia la fusion table 
	var layer = new google.maps.FusionTablesLayer({
		query: {select: 'col2', from: '2766021'},
		map: map
	});
	
	for(var i=0; i < POSTS.length; i++) {
		var post = POSTS[i];
		if(post.latitude && post.longitude) {
			var marker = new google.maps.Marker({
				map: map,
				icon: 'images/text.png',
				position: new google.maps.LatLng(post.latitude, post.longitude),
				title: post.title,
				post_id: post.id
			});
			google.maps.event.addListener(marker, 'click', function() {
				location.href = 'http://www.enrouteavecaile.com/post.php?lang=' + LANG + '&id=' + this.post_id;
			});
		}
	}

// en dessous: position du vélo (position actuelle)
	var latestPosition = new google.maps.Marker({
		map: map,
		icon: 'images/cycling.png',
		position: position,
		title: 'Last recorded position'
	});
	google.maps.event.addListener(latestPosition, 'click', function() {
		var infowindow = new google.maps.InfoWindow({
			content: 'Il s\'agit de la dernière position enregistrée'
		});
		infowindow.open(map, this);
	});
	/*
	var imgs = $$('ul.Widget.gallery img');
	if((imgs.length == 0) && $('big'))
		imgs.push($('big'));
	for (var i=0; i < imgs.length; i++) {
		var img = imgs[i];
		var marker = new google.maps.Marker({
			map: map,
			icon: new google.maps.MarkerImage(img.src, null, null, null, new google.maps.Size(30, 30)),
			position: new google.maps.LatLng(img.getProperty('latitude'), img.getProperty('longitude')),
			title: img.getProperty('alt'),
			src: img.src
		});
		google.maps.event.addListener(marker, 'click', function() {
			var infowindow = new google.maps.InfoWindow({
				content: '<img height="300px" src="' + this.src + '"/>' + (this.title?'<br/>'+this.title:'')
			});
			infowindow.open(map, this);
		});
	};
	*/
}

window.addEvent('domready', function() {
	document.addEvent('click', function(e) {
		var elt = e.target;
// Tabs
		if($(elt).match('li.Tabs_title')) {
			elt.parentNode.retrieve('widget').showPanel(elt);
			e.stop();
			return;
		}
	});
	
	var widgets = $(document.body).getElements('[widget]');
	for (var i=0; i < widgets.length; i++) {
		var widget = widgets[i];
		new AP.Widget[widget.getProperty('widget')](widget);
	}
	
	$$('form.jaxform').each(function(form) {
		form.addEvent('submit', function(e) {
			e.stop();
			var req = new Form.Request(e.target, e.target.getParent(), {
				extraData: {moojax: true},
				requestOptions: {method: 'post', url: 'action.php'},
				onFailure: function(xhr) {alert(xhr.responseText);}
			});
			req.send();
		});
	});
});
