
/* Explore */
window.addEvent('domready', function(){
	$$('#explore_countries li').addEvent('click',function() {
		if ($(this).hasClass('active_country')) return false;
		
		var chosen = $(this).className.replace(/.*ec_/, '').replace(/\s.*/, '');
		var cid = chosen.replace(/_.*/, '');
		var station = chosen.replace(/[0-9]+_/, '');

		$$('#explore_content ul.categories').setStyle('display', 'none');
		$$('#explore_stations li.active_station').removeClass('active_station');		
		$$('#explore_stations li.station').setStyle('display', 'none');
		$$('#explore_stations li.cid_' + cid).setStyle('display', 'block');
		$$('#explore_stations li.station_' + station).addClass('active_station');
		$$('#explore_content ul.categories_' + station).setStyle('display', 'block');
		
		$$('#explore_countries li.active_country').removeClass('active_country');
		$(this).addClass('active_country');
		return false;
	});
		
	$$('#explore_stations li').addEvent('click', function(e){
		$$('#explore_content ul.categories').setStyle('display', 'none');
		$$('#explore_stations li.active_station').removeClass('active_station');
		var station = /station_\w+/.exec($(this).get('class')).toString().replace(/station_/g,'').trim();
		$$('#explore_content ul.categories_' + station).setStyle('display', 'block');
		$(this).addClass('active_station');
		return false;
	});
});

/* Touristic Destinations */
window.addEvent('domready', function(){
	$$('#dest_link_list a').addEvent('click', function() {
		$$('#dest_link_list a').setStyle('font-weight', 'normal');
		var a = $(this), ct = $('dest_list');
		if (!a || !ct) return true;
		a.setStyle('font-weight', 'bold');
		ct.set('html', '<img src="' + appPath + 'web_root/img/ajax-loader.gif" alt="" style="display: block; position: absolute; top: 100px; left: 150px;" />');
		
		var key = a.href.replace(appPath, '').replace(/\//g, '__').replace(/-/g, '___').replace(/\W/g, '');
		//console.log('url ='+key)
		
		var cache = eval('window.' + key);
		if (cache) {
			showDests(cache);
		}
		else {			
			var jsonRequest = new Request.JSON({
				url: a.href,
				onSuccess: function(r) {
					if (!r) location.href = a.href;
					showDests(r);
					eval('window.' + key + ' = r');
				},
				onFailure: function(){
					location.href = a.href;
				}
			}).get({'js' :1});
		}
		return false;
	});
});

function getXpxForG(g) {
	return (g - 26.4783063616) / 0.00982491629466;
}

function getYpxForG(g) {
	return (48.4796979886 - g) / 0.00679388204047;
}

function showDests(r) {
	var ct = $('dest_list');
	ct.set('html', '');
	$each(r.destinations, function(d) {
		if (d.dest_long == "0" || d.dest_lat == "0") return;
		ct.adopt(new Element('div', {
			'id': 'dest_wrap_' + d.dest_id,
			'styles': {
				'background-image': 'url("/web_root/img/destinatiituristice/' + d.dest_tip_id + '.png")',
				'background-repeat': 'no-repeat',
				'width': '27px',
				'height': '27px',
				'position': 'absolute',
				'left': getXpxForG(d.dest_long) - 5,
				'top': getYpxForG(d.dest_lat) - 5,
				'cursor': 'pointer',
				'z-index': 2004
			},
			'alt': d.dest_title,
		    'events': {
		        'click': function(){
		            location.href = d.dest_link;
		        },
		        'mouseenter': function(){
		        	var info = $('dest_info_' + d.dest_id);
		        	if (info) {
		        		
		        	}
		        	else {
			            var info = new Element('div', {
				            'id': 'dest_info_' + d.dest_id,
							'styles': {
								'position': 'absolute',
								'padding' : '5px',
								'width': '270px',
								'height': '145px',
								'border': 'none',
								'background-image':  'url("/web_root/img/explore_box/calota_dreapta.png")', 	
								'opacity': 0,
								'left': -280,
								'top': -65
							}
			            });
			            info.set('html', d.dest_info);
			            $(this).adopt(info);
		        	}
		            $(this).setStyle('z-index', 2005);
		            info.morph({
		            	'opacity': 1
		            });
		        },
		        'mouseleave': function(){
		        	var wrap = $(this);
		            ct.getElements('div[id^=dest_info_]').morph({
		            	'duration': 'short',
		            	'complete': function(){ wrap.setStyle('z-index', 2004);},
		            	'opacity': 0
		            });
		        }
		    }
		}));
	});
}

/* Events */
window.addEvent('domready', function(){
	var mid = new Date(), mad = new Date();
	mad.setDate(mad.getDate() + 30);
	
	var d = $('upcoming_events_date').getCoordinates(),
	mids = (mid.getFullYear() * 100 + (mid.getMonth() + 1)) * 100 + mid.getDate(),
	mads = (mad.getFullYear() * 100 + (mad.getMonth() + 1)) * 100 + mad.getDate(),
	picker = new DatePicker($('upcoming_events_date'), {
		pickerClass: 'datepicker_vista datepicker_vista_calendar radius5',
		allowEmpty: true,
		useFadeInOut: false,
		calendarMode: true,
		minDate: { date: mids, format: 'Ymd'},
		maxDate: { date: mads, format: 'Ymd'},
		onSelect: function(d) {
			$('upcoming_events_big_date').set('text', d.getDate());
			$('upcoming_events_sel_date').set('text', d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear());
			$('upcoming_events_sel_date').int_date = (d.getFullYear() * 100 + (d.getMonth() + 1)) * 100 + d.getDate();
			$('upcoming_events_clear_date').setStyle('display', 'block');
			updateEventList();
		},
		onPrevious: function() {
			if (!$('upcoming_events_sel_date').int_date) picker.newContents.getElements('div.selected').removeClass('selected');
		},
		onNext: function() {
			if (!$('upcoming_events_sel_date').int_date) picker.newContents.getElements('div.selected').removeClass('selected');
		}
	});
	picker.newContents.getElements('div.selected').removeClass('selected');
	$('upcoming_events_clear_date').addEvent('click', function(){
		$('upcoming_events_big_date').set('text', '');
		$('upcoming_events_sel_date').set('text', '');
		$('upcoming_events_sel_date').int_date = null;
		this.setStyle('display', 'none');
		picker.newContents.getElements('div.selected').removeClass('selected');
		updateEventList();
	});
	
	$('upcoming_events_big_date').set('text', mid.getDate());
	
	$$('#upcoming_events_types li').addEvent('click', function(){
		if ($(this).hasClass('upcoming_event_type_active')) return false;
		$$('#upcoming_events_types li').removeClass('upcoming_event_type_active');
		$(this).addClass('upcoming_event_type_active');
		updateEventList();
		return false;
	});
	var evnt_station_select = new MavSelectBox({
		elem: $('upcoming_events_stations'),
		alternate: true,
		onSelect: function(elem) {
			updateEventList();
		}
	});
	var evnt_cntry_select = new MavSelectBox({
		elem: $('upcoming_events_countries'),
		alternate: true,
		onSelect: function(elem) {
			evnt_station_select.elementOptions.getChildren().dispose();
			var cnt = 0, cid = this.element.value.replace('event_country_', '');
			var st = $('upcoming_events_stations').value;
			$each(stations, function(s, i) {
				if (cid != 'all' && cid != s.c && s.n != 'all') return;
				var o = new Element('option', {
					'value': 'event_station_' + s.n,
					'text': s.rn
				});
				if (s.c == '0') o.setStyle('font-weight', 'bold');
				if (st == o.value) o.selected = true;
				evnt_station_select.create_option(o, cnt++);
			});
			var sli = evnt_station_select.elementOptions.getElement('li.' + evnt_station_select.options.selectClass);
			if (!sli) sli = evnt_station_select.elementOptions.getElements('li')[0];
			evnt_station_select.select(sli);
			updateEventList();
		}
	});
	evnt_station_select.elementSelect.addClass('radius5');
	evnt_cntry_select.elementSelect.addClass('radius5');
	var cid = $('upcoming_events_countries').value.replace('event_country_', ''),
	stn = $('upcoming_events_stations').value.replace('event_station_', '');
	window.events_loaded = {};
	if (cid == 'all') {
		window.events_loaded.all = true;
	}
	else if (stn == 'all') {
		eval('window.events_loaded.c' + cid + '_all = true;');
	}
	else {
		eval('window.events_loaded.c' + cid + '_' + stn + ' = true;');
	}
});

function loadMissingEvents() {
	var cid = $('upcoming_events_countries').value.replace('event_country_', ''),
	stn = $('upcoming_events_stations').value.replace('event_station_', '');
	
	if (window.events_loaded.all ||
			eval('window.events_loaded.c' + cid + '_all') ||
			eval('window.events_loaded.c' + cid + '_' + stn)) return false;
	showEventsOverlay();
	new Request.JSON({
		url: appPath + 'ajax/events/',
		onSuccess: function(r) {
			if (!r) return;
			if ($('upcoming_events_list')) $('upcoming_events_list').set('html', $('upcoming_events_list').get('html') + r.data);
			updateEventList();
			hideEventsOverlay();
		},
		onFailure: function(){
			hideEventsOverlay();
		}
	}).post({'country': cid, 'station': stn, 'loaded': window.events_loaded});
	
	if (cid == 'all') window.events_loaded.all = true;
	else if (stn == 'all') eval('window.events_loaded.c' + cid + '_all = true;');
	else eval('window.events_loaded.c' + cid + '_' + stn + ' = true;');
	return true;
}

function updateEventList() {
	var c = $('upcoming_events_countries').value,
	s = $('upcoming_events_stations').value,
	t = $('upcoming_events_types').getElement('li.upcoming_event_type_active').className.replace(/\s*upcoming_event_type_active\s*/, ''),
	d = $('upcoming_events_sel_date').int_date;
	
	if (!c || !s || !t || loadMissingEvents()) return;
	
	$$('#upcoming_events_list li').setStyle('display', 'none');
	
	$$('#upcoming_events_list li').each(function(l){
		if ((c != 'event_country_all' && !l.hasClass(c)) || (s != 'event_station_all' && !l.hasClass(s)) || (t != 'event_all' && !l.hasClass(t))) return;
		if (!d) {
			l.setStyle('display', 'list-item');
			return;
		}
		
		var m = false, i;
		if (/event_date_permanent/.test(l.className)) {
			m = true;
		}
		else if (/event_date_/.test(l.className)) {
			i = l.className.match(/event_date_\d+_\d+/g);
			if (i) for(var x = 0, sed = null; x < i.length; x ++) {
				sed = i[x].match(/\d+/g);
				if (i && d >= sed[0] && d <= sed[1]) {
					m = true;
					break;
				}
			}				
		}
		if (m) l.setStyle('display', 'list-item');
	});
	
	if ($('upcoming_events_list')) $('upcoming_events_list').scrollTo(0,0);
}

function showEventsOverlay() {
	var l = $('upcoming_events_list'), c = $('upcoming_events'), ct = $('ct');
	if (!l || !c || !ct) return;
	var p = c.getPosition();
	ct.adopt( (new Element('div', {
			'class': 'events_overlay radius5',
			'styles': {
				'position': 'absolute',
				'top': p.y,
				'left': p.x,
				'width': c.getStyle('width'),
				'height': c.getStyle('height'),
				'margin-top': 1,
				'background-color': 'black',
				'opacity': 0.3,
				'z-index': 5
			},
			'events': {
				'mousedown': function(e) {
					return false;
				}
			}
		})).adopt(new Element('img', {
			'src': appPath + 'web_root/img/ajax-loader.gif',
			'styles': {
				'display': 'block',
				'margin': '0 auto',
				'margin-top': l.getStyle('height').toInt() / 2 - 50 
			}
		}))
	);
}

function hideEventsOverlay() {
	$$('div.events_overlay').dispose();
}

