jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.event.special

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});

$(document).ready(function(){
	// parametros
	
	$.buildMarker = function(estacion,orden,links,zona,coinc,ambit,corresp,serveis,name,url,markerOptions){
		var texto = "<h1 style='font-size:16px;margin:0px;padding:0px;'>" + estacion + "</h1><br />";
		texto += "<h2 style='font-size:12px;margin:0px;padding:0px;'>" + name + "</h2><br />";
		texto += "<b>Correspondencias :</b><br />" + $.buildImgTag(corresp) + "<br />";
		texto += "<b>Servicios :</b><br />" + $.buildImgTag(serveis);
		var p = $.split_map_params(url);
		var ll = p['ll'].split(',');
		var point = new GLatLng(ll[0],ll[1]);
		var mrkr = new GMarker(point,markerOptions);
		mrkr.texto = texto;
		return mrkr;
	};
	$.buildImgTag = function(imgs){
		if(imgs == "" )return "";
		var imgs = imgs.split(',');
		var bfr = '';
		$(imgs).each(function(i, el){
			bfr += '<img style="padding:4px;" src="../downloads/info_estacions/codi/' + el.toLowerCase() + '.gif" />';
		})
		return bfr;
	};
	$.split_map_params = function(str){
		var params = {};
		
		var prms = str.indexOf('?')>-1 ?
			str.split('?')[1].indexOf('&')>-1 ?
				str.split('?')[1].split('&'):
				[str.split('?')[1]]:
			[];
			
		$(prms).each(function(i,el){
			el.indexOf('=')>-1?
				params[el.split('=')[0]] = el.split('=')[1]!=undefined?el.split('=')[1]:''
				:false;
		})
		return params;
	}
	
	var showMapa = function(id,node,size){
		var width = size["width"];//650;
		var height = size["height"];//516;
		var top = $(node).offset().top+'px';
		if($.browser.msie && node=='#main .resultados'){
			top = '0px';
		}
		$(node).append('<div class="overlay"><div class="contenido"><a class="cerrar" href="javascript:void(0);">Cerrar</a><div id="mapa_google"></div></div></div>').find('.overlay').css({
			display:'block',
			zIndex:9999,
			position:'absolute',
			backgroundColor:'white',
			//opacity:'.7',
			top:top,
			left:"7px",
			width:$(node).width(),
			height:$(node).height()
		})
		.find('.contenido').css({
			display:'block',
			position:'absolute',
			width:width+'px',
			height:height+'px',
			left:'20px',
			//left:($('#main .resultados').width()-width)/2+'px',
			top:'18px',
			//top:($('#main .resultados').height()-height)/2+'px',
			border:'2px solid #DDDDDD',
			backgroundColor:'#ffffff',
			padding:'10px',
			paddingTop:'24px'
		})
		.find('a.cerrar').css({
			position:'absolute',
			right:'3px',
			top:'3px'
		})
		.bind('click',function(){
			$(this).parent().parent().remove();
		})
		.parent()
		.find('#mapa_google').css({
			width:'auto',
			height:height-10+'px',
			border:'1px solid black'
		})
		if (GBrowserIsCompatible()) {
			var id_inicial = id;
			
			// creamos el geocoder
			var geocoder = new GClientGeocoder();
			var fgcIcon = new GIcon(G_DEFAULT_ICON);
			fgcIcon.image = "../media/img/xarxa_fgc/fgcico_googlemaps.png";
			fgcIcon.iconSize = new GSize(14, 14);
			fgcIcon.iconAnchor = new GPoint(7,7);
			fgcIcon.shadowSize = new GSize(14, 14);
			var markerOptions = { icon:fgcIcon, draggable:false };
			// creamos el mapa
			
			$.mapa = new GMap2($('#mapa_google')[0]);
			//$.mapa.setCenter(new GLatLng( start_ll[0], start_ll[1]), 17);
			
			$.mapa.enableScrollWheelZoom();
			$.mapa.addControl(new GMapTypeControl());
			$.mapa.addControl(new GSmallMapControl());
			markers = {};
			//ides = [1,2,3,4,5,6];
			
			url_to_data = '../media/aspflash/accesos_test.php';
			$.get(url_to_data,{idestacio:id_inicial},function(datos){
				$("estaciones estacion",datos).each(function(){
					var acces1 = $("acces1",this).text();
					var maplink1 = $("maplink1",this).text();
					var acces2 = $("acces2",this).text();
					var maplink2 = $("maplink2",this).text();
					var acces3 = $("acces3",this).text();
					var maplink3 = $("maplink3",this).text();
					var acces4 = $("acces4",this).text();
					var maplink4 = $("maplink4",this).text();
					var acces5 = $("acces5",this).text();
					var maplink5 = $("maplink5",this).text();
					var acces6 = $("acces6",this).text();
					var maplink6 = $("maplink6",this).text();
					
					var nom = $("nom",this).text();
					var ordre = $("ordre_general",this).text();
					var links = $("links",this).text();
					var zona = $("zona",this).text();
					var coinc = $("coincideix",this).text();
					var ambit = $("ambit",this).text();
					var corresp = $("corresp",this).text();
					var serveis = $("serveis",this).text();
					
					var markers = [];
					acces1!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces1,maplink1,markerOptions)):false;
					acces2!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces2,maplink2,markerOptions)):false;
					acces3!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces3,maplink3,markerOptions)):false;
					acces4!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces4,maplink4,markerOptions)):false;
					acces5!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces5,maplink5,markerOptions)):false;
					acces6!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces6,maplink6,markerOptions)):false;
					
					var bounds = new GLatLngBounds();
	
					$(markers).each(function(i,el){
						GEvent.addListener(el, "click", function(){
							el.openInfoWindowHtml(el.texto);
							$.mapa.panTo(el.getPoint())
						});
						$.mapa.addOverlay(el);
						bounds.extend(el.getPoint());
					})
					!bounds.getCenter() ? 
						$.mapa.setCenter(markers[0].getPoint(),17):
						$.mapa.setCenter(bounds.getCenter(),17);
						
					$.get(url_to_data,function(datos){
						var times = $("estaciones estacion",datos).length
						$(document).everyTime(150,function(i){
							dt = $("estaciones estacion",datos)[i];
							if($(dt).attr('idestacion')!=id_inicial){
								var acces1 = $("acces1",dt).text();
								var maplink1 = $("maplink1",dt).text();
								var acces2 = $("acces2",dt).text();
								var maplink2 = $("maplink2",dt).text();
								var acces3 = $("acces3",dt).text();
								var maplink3 = $("maplink3",dt).text();
								var acces4 = $("acces4",dt).text();
								var maplink4 = $("maplink4",dt).text();
								var acces5 = $("acces5",dt).text();
								var maplink5 = $("maplink5",dt).text();
								var acces6 = $("acces6",dt).text();
								var maplink6 = $("maplink6",dt).text();
								
								var nom = $("nom",dt).text();
								var ordre = $("ordre_general",dt).text();
								var links = $("links",dt).text();
								var zona = $("zona",dt).text();
								var coinc = $("coincideix",dt).text();
								var ambit = $("ambit",dt).text();
								var corresp = $("corresp",dt).text();
								var serveis = $("serveis",dt).text();
								
								var markers = [];
								acces1!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces1,maplink1,markerOptions)):false;
								acces2!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces2,maplink2,markerOptions)):false;
								acces3!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces3,maplink3,markerOptions)):false;
								acces4!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces4,maplink4,markerOptions)):false;
								acces5!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces5,maplink5,markerOptions)):false;
								acces6!=''?markers.push($.buildMarker(nom,ordre,links,zona,coinc,ambit,corresp,serveis,acces6,maplink6,markerOptions)):false;
					
								$(markers).each(function(i,el){
									GEvent.addListener(el, "click", function(){
										el.openInfoWindowHtml(el.texto);
										$.mapa.panTo(el.getPoint())
									});
									$.mapa.addOverlay(el);
									bounds.extend(el.getPoint());
								})
							}
						},times)
					});
				});
			});
		}
		return false;
	}
	
	$('a[id^=mapa_google_link]').bind('click',function(e){
		var id = $(this).attr('id').split('-')[1];
		size = {
			width:650,
			height:516
		};
		showMapa(id,'#main .resultados',size)
		return false;
	});
	
	fromFlash = function(id){
		size = {
			width:910,
			height:446
		};
		showMapa(id,'.mapa',size)
	}
	
})

function ___pause(ms) {
	var date = new Date(); 
	curDate = null;
	do { var curDate = new Date(); }
	while ( curDate - date < ms);
};
