
// the geocoder
var geocoder;
// the map
var map;

var fisheye_menu;

var right_page_fx;
var selection_menu_markers_fx;
var search_menu_fx;

// status of view: clusters or spots
var view_status = 'undefined';

// request to refresh data
var request_data = new Request();
var dirtySpots = new Array();

// base icon of markers
var base_icon = new GIcon(G_DEFAULT_ICON);
//base_icon.shadow = "/images/marker/shadow.png";
base_icon.iconSize = new GSize(21, 25);
base_icon.iconAnchor = new GPoint(10, 25);
//base_icon.infoWindowAnchor = new GPoint(5, 2);
base_icon.poly="0,0,21,0,21,25,0,25";

var cluster_icon = new GIcon(G_DEFAULT_ICON);
cluster_icon.image = '/images/cluster.png';
//cluster_icon.shadow = "/images/marker/shadow.png";
cluster_icon.iconSize = new GSize(56, 55);
cluster_icon.iconAnchor = new GPoint(28, 27);
//cluster_icon.infoWindowAnchor = new GPoint(5, 2);
cluster_icon.poly="0,0,56,0,56,55,0,55";

// last bounds of map
var last_bounds;

// map is zoomed (needed that refresh is not done twice)
var is_zoom = false;

var is_first_load = true;

// needed that refresh ist not done twice on use of my set center funtion
var is_my_set_center = false;

// array of spots
var spots = new Array();

// array of clusters
var clusters = new Array();

// array of active activities
var active_activities = new Array();

// scroller for detail-tab-headers
// var scroller = new Fx.Scroll('details_tab_headers_holder', {duration: 0});
// array of all displayed tabs
var details_tabs = new Array();

// google analytics
try{
   var pageTracker = _gat._getTracker("UA-xxxxxx-x");
} catch(err) {}

// init spots and active activities
  spots["bowling"] = new Array();
  active_activities["bowling"] = new Object();
  active_activities["bowling"].name = 'Bowling';
  active_activities["bowling"].detailsUrl = 'details-bowling';
  spots["leisureparks"] = new Array();
  active_activities["leisureparks"] = new Object();
  active_activities["leisureparks"].name = 'Freizeitparks';
  active_activities["leisureparks"].detailsUrl = 'details-leisurepark';
  spots["golfcourses"] = new Array();
  active_activities["golfcourses"] = new Object();
  active_activities["golfcourses"].name = 'Golfplätze';
  active_activities["golfcourses"].detailsUrl = 'details-golfcourse';
  spots["indoorplaygrounds"] = new Array();
  active_activities["indoorplaygrounds"] = new Object();
  active_activities["indoorplaygrounds"].name = 'Hallenspielplätze';
  active_activities["indoorplaygrounds"].detailsUrl = 'details-indoorplayground';
  spots["high_ropes_courses"] = new Array();
  active_activities["high_ropes_courses"] = new Object();
  active_activities["high_ropes_courses"].name = 'Hochseilgärten';
  active_activities["high_ropes_courses"].detailsUrl = 'details-highropescourse';
  spots["karttracks"] = new Array();
  active_activities["karttracks"] = new Object();
  active_activities["karttracks"].name = 'Kart Bahnen';
  active_activities["karttracks"].detailsUrl = 'details-karttrack';
  spots["climbinggyms"] = new Array();
  active_activities["climbinggyms"] = new Object();
  active_activities["climbinggyms"].name = 'Kletterhallen';
  active_activities["climbinggyms"].detailsUrl = 'details-climbinggym';
  spots["mtb_parks"] = new Array();
  active_activities["mtb_parks"] = new Object();
  active_activities["mtb_parks"].name = 'MTB-Parks';
  active_activities["mtb_parks"].detailsUrl = 'details-mtbpark';
  spots["swimming_facilities"] = new Array();
  active_activities["swimming_facilities"] = new Object();
  active_activities["swimming_facilities"].name = 'Schwimmbäder';
  active_activities["swimming_facilities"].detailsUrl = 'details-swimmingfacilities';
  spots["ski_regions"] = new Array();
  active_activities["ski_regions"] = new Object();
  active_activities["ski_regions"].name = 'Ski-Gebiete';
  active_activities["ski_regions"].detailsUrl = 'details-skiregion';
  spots["wakeboard_lifts"] = new Array();
  active_activities["wakeboard_lifts"] = new Object();
  active_activities["wakeboard_lifts"].name = 'Wakeboard';
  active_activities["wakeboard_lifts"].detailsUrl = 'details-wakeboardlift';
  spots["zoos"] = new Array();
  active_activities["zoos"] = new Object();
  active_activities["zoos"].name = 'Zoos';
  active_activities["zoos"].detailsUrl = 'details-zoo';


function init_extra_tab_links()
{
  if ($('new_link_exta_tab'))
  {
    $('new_link_exta_tab').addEvent('click', function(){
      SqueezeBox.open('/de/spot/newEntryWiz', {handler:'iframe',size:{x:900,y:480}, onClose: load_menu});
      write_to_stats('de/extra-tab/new');
    });
  }
}

// function to init states of checkboxes (checked/unchecked)
function init_checkbox_states(activity)
{
  if(activity)
  {
          if ('bowling' == activity || 'all' == activity)
      {
          $('selection_bowling').checked = true;
      }
      else
      {
          $('selection_bowling').checked = false;
      }
          if ('leisureparks' == activity || 'all' == activity)
      {
          $('selection_leisureparks').checked = true;
      }
      else
      {
          $('selection_leisureparks').checked = false;
      }
          if ('golfcourses' == activity || 'all' == activity)
      {
          $('selection_golfcourses').checked = true;
      }
      else
      {
          $('selection_golfcourses').checked = false;
      }
          if ('indoorplaygrounds' == activity || 'all' == activity)
      {
          $('selection_indoorplaygrounds').checked = true;
      }
      else
      {
          $('selection_indoorplaygrounds').checked = false;
      }
          if ('high_ropes_courses' == activity || 'all' == activity)
      {
          $('selection_high_ropes_courses').checked = true;
      }
      else
      {
          $('selection_high_ropes_courses').checked = false;
      }
          if ('karttracks' == activity || 'all' == activity)
      {
          $('selection_karttracks').checked = true;
      }
      else
      {
          $('selection_karttracks').checked = false;
      }
          if ('climbinggyms' == activity || 'all' == activity)
      {
          $('selection_climbinggyms').checked = true;
      }
      else
      {
          $('selection_climbinggyms').checked = false;
      }
          if ('mtb_parks' == activity || 'all' == activity)
      {
          $('selection_mtb_parks').checked = true;
      }
      else
      {
          $('selection_mtb_parks').checked = false;
      }
          if ('swimming_facilities' == activity || 'all' == activity)
      {
          $('selection_swimming_facilities').checked = true;
      }
      else
      {
          $('selection_swimming_facilities').checked = false;
      }
          if ('ski_regions' == activity || 'all' == activity)
      {
          $('selection_ski_regions').checked = true;
      }
      else
      {
          $('selection_ski_regions').checked = false;
      }
          if ('wakeboard_lifts' == activity || 'all' == activity)
      {
          $('selection_wakeboard_lifts').checked = true;
      }
      else
      {
          $('selection_wakeboard_lifts').checked = false;
      }
          if ('zoos' == activity || 'all' == activity)
      {
          $('selection_zoos').checked = true;
      }
      else
      {
          $('selection_zoos').checked = false;
      }
      }
  else
  {
                    $('selection_bowling').checked = false;
                          $('selection_leisureparks').checked = false;
                          $('selection_golfcourses').checked = false;
                          $('selection_indoorplaygrounds').checked = false;
                          $('selection_high_ropes_courses').checked = false;
                          $('selection_karttracks').checked = false;
                          $('selection_climbinggyms').checked = false;
                          $('selection_mtb_parks').checked = false;
                          $('selection_swimming_facilities').checked = false;
                          $('selection_ski_regions').checked = false;
                          $('selection_wakeboard_lifts').checked = false;
                          $('selection_zoos').checked = false;
            }
}

// function to get all active activiteis in an array
function getDisplayedActivities()
{
  displayed_activities = new Array();
  $$('.active_activities').each(function(el){
    if (el.checked)
    {
      displayed_activities.push(el.value);
    }
  });
  return displayed_activities;
}

// function to get all active activities in one string
function getDisplayedActivitiesString()
{
  return getDisplayedActivities().join('');
}

// function to init the map
function init_map(lt, ln, z, has_town_lat_lng, town)
{
  // positions for map-controls
  var typeControlPos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(210,110));
  var mapControlPos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(165,110));

  // init geocoder
  geocoder = new GClientGeocoder();

  // init the map
  map = new GMap2(document.getElementById("map_canvas"));

  // enable scroolwheelzoom
  map.enableScrollWheelZoom();

  // add overview
  //map.addControl(new GOverviewMapControl());

  // set and add maptype
  map.setMapType(G_PHYSICAL_MAP);
  map.addMapType(G_PHYSICAL_MAP);

  // add map controls
  map.addControl(new GSmallMapControl, mapControlPos);
  map.addControl(new GMenuMapTypeControl(), typeControlPos);

  //set map center
  setCenter(new GLatLng(lt, ln), z, true);
  if(town && !has_town_lat_lng)
  {
    zoomToPlace(town, 10);
  }

  // event if map was moved
  GEvent.addListener(map, "moveend", function() {
    // after zoom, moveend ist automatically fired. only call refresh_shown_list once
    /*if (is_zoom)
    {
      is_zoom = false;
    }
    else if (is_my_set_center)
    {
      is_my_set_center = false;
    }
    else*/
    {
      refresh_displayed_data();
    }
  });

  // event if map was zoomed
  GEvent.addListener(map, "zoomend", function() {
    is_zoom = true;
refresh_displayed_data()  });

  // init info_box
  $('info_box').addEvent('mouseover', function(){
    $('info_box').setStyle('display', 'block');
  });
  $('info_box').addEvent('mouseout', function(){
    $('info_box').setStyle('display', 'none');
  });
}

// function to init checkbox events
// the map needs to be initialized before checkbox events because the map variable is used here
function init_checkbox_events()
{
      $('selection_bowling').addEvent('click', function() {
      if(!$('selection_bowling').checked)
      {
        hide_spots('bowling');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
      $('selection_leisureparks').addEvent('click', function() {
      if(!$('selection_leisureparks').checked)
      {
        hide_spots('leisureparks');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
      $('selection_golfcourses').addEvent('click', function() {
      if(!$('selection_golfcourses').checked)
      {
        hide_spots('golfcourses');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
      $('selection_indoorplaygrounds').addEvent('click', function() {
      if(!$('selection_indoorplaygrounds').checked)
      {
        hide_spots('indoorplaygrounds');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
      $('selection_high_ropes_courses').addEvent('click', function() {
      if(!$('selection_high_ropes_courses').checked)
      {
        hide_spots('high_ropes_courses');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
      $('selection_karttracks').addEvent('click', function() {
      if(!$('selection_karttracks').checked)
      {
        hide_spots('karttracks');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
      $('selection_climbinggyms').addEvent('click', function() {
      if(!$('selection_climbinggyms').checked)
      {
        hide_spots('climbinggyms');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
      $('selection_mtb_parks').addEvent('click', function() {
      if(!$('selection_mtb_parks').checked)
      {
        hide_spots('mtb_parks');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
      $('selection_swimming_facilities').addEvent('click', function() {
      if(!$('selection_swimming_facilities').checked)
      {
        hide_spots('swimming_facilities');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
      $('selection_ski_regions').addEvent('click', function() {
      if(!$('selection_ski_regions').checked)
      {
        hide_spots('ski_regions');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
      $('selection_wakeboard_lifts').addEvent('click', function() {
      if(!$('selection_wakeboard_lifts').checked)
      {
        hide_spots('wakeboard_lifts');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
      $('selection_zoos').addEvent('click', function() {
      if(!$('selection_zoos').checked)
      {
        hide_spots('zoos');
      }
      // refresh shownlist for all activities because clustering might be needed
      refresh_data(getDisplayedActivitiesString(), true);
    });
  }

// function to hide all spots (remove all marker overlays from the map)
function hide_spots(activity)
{
  spots[activity].each(function (spot){
    map.removeOverlay(spot.marker);
  });
}

function init_search_menu()
{
  search_menu_fx = new Fx.Tween('search_menu', {duration: 100});

  $('search_menu').addEvent('mouseover', function(){
    $('search_menu_content').setStyle('background','#222222');
    search_menu_fx.cancel();
    search_menu_fx.start('width', 540).chain(function(){
      search_menu_fx.start('height', 450);
    });
  });

  $('search_menu').addEvent('mouseout', function(){
    search_menu_fx.cancel();
    search_menu_fx.start('height', 180).chain(function(){
      search_menu_fx.start('width', 170).chain(function(){
        $('search_menu_content').setStyle('background','transparent url(/images/1x1_24_06_2010.png) repeat');
      });
    });
  });
}

// function
function init_selection_menu()
{
  selection_menu_markers_fx = new Fx.Morph('selection_menu_markers', {duration: 1000});
  animate_selection_menu();

  $('checkAllActivitiesBtn').addEvent('click', function(){
    checkAllActivities();
    refresh_displayed_data();
  });
  $('uncheckAllActivitiesBtn').addEvent('click', function(){
    uncheckAllActivities();
    // hide all markers
          hide_spots('bowling');
          hide_spots('leisureparks');
          hide_spots('golfcourses');
          hide_spots('indoorplaygrounds');
          hide_spots('high_ropes_courses');
          hide_spots('karttracks');
          hide_spots('climbinggyms');
          hide_spots('mtb_parks');
          hide_spots('swimming_facilities');
          hide_spots('ski_regions');
          hide_spots('wakeboard_lifts');
          hide_spots('zoos');
      });
}

function animate_selection_menu()
{
  var duration = 3000;
  var length = 63;
  var count = 0;
  var tweener = $('selection_menu_markers').set('tween',{ duration: duration, transition: 'linear' });

  //showtime!
  var run = function() {
    tweener.tween('background-position','-' + (++count * length) + 'px -360px');
  };

  run();
  run.periodical(duration);
}

// function to init details-tabs
function init_details()
{
  $('openTabsMenu').set('tween', {duration: 150});

  $('openTabsMenuCaption').addEvent('mouseover', function(){
    $('openTabsMenu').tween('width', 440);
  });

  $('openTabsMenuCaption').addEvent('mouseout', function(){
    $('openTabsMenu').tween('width', 40);
  });

  $('openTabsList').addEvent('mouseover', function(){
    $('openTabsMenu').tween('width', 440);
  });

  $('openTabsList').addEvent('mouseout', function(){
    $('openTabsMenu').tween('width', 40);
  });

  right_page_fx = new Fx.Morph('right_page', {duration: 500});
  $('details_minimize').addEvent('click', function(){
    right_page_fx.start({
      'width': 0,
      'height' : 0,
      'top': 250
    }).chain(function(){
        $$('.details_tab_content').setStyle('display', 'none');
    });
    return false;
  });

  $('details_close').addEvent('click', function(){
    $('right_page').setStyle('width', 0);
    $('right_page').setStyle('height', 0);
    $('right_page').setStyle('top', 250);
    $$('.details_tab_content').each(function(item,index){
    if (item.getStyle('display') == 'block')
      {
        $('openTabsListItem_'+item.window_id).dispose();
        item.dispose();
      }
    });
  });
}

// function to init search field
function init_searchfield()
{
  /* clear search-field */
  $('map_search_cancel').addEvent('click', function(){
    $('quick_search_str').setProperty('value', '');
  });
}

// function to refresh data for all displayed activities
function refresh_displayed_data()
{
  
  map.checkResize();
  refresh_data(getDisplayedActivitiesString(), true);
}

// function to refresh shwonlist for a set of activities
function refresh_data(displayed_activities, check_full_map)
{
  var mapBounds = map.getBounds();
  var swLatLng = mapBounds.getSouthWest();
  var neLatLng = mapBounds.getNorthEast();
  var zoom = map.getZoom();
  var square_size = 50;;
  var map_size = map.getSize();
  var cluster_nr_x = Math.ceil(map_size.width / square_size);
  var cluster_nr_y = Math.ceil(map_size.height / square_size);

  request_data = new Request({
    url: '/de/refresh-list',
    method: 'get',
    onComplete: function(data) {
      var rows = data.split("\n");
      var status = rows[0];
      var data_bounds = rows[1].split("|");
      if (status == "spots")
      {
        renewSpotsCollection(data_bounds, rows);
      }
      else
      {
        var bounds = map.getBounds();
        if (data_bounds[0] == bounds.getSouthWest().lat() &&
            data_bounds[1] == bounds.getSouthWest().lng() &&
            data_bounds[2] == bounds.getNorthEast().lat() &&
            data_bounds[3] == bounds.getNorthEast().lng())
        {
          renewClustersCollection(rows);
        }
      }
    }
  });

  if (last_bounds != null && (typeof(check_full_map) == "undefined" || check_full_map == false))
  {
    request_data.send('da='+displayed_activities+
                            '&vs='+view_status+
                            '&z='+zoom+
                            '&x='+cluster_nr_x+
                            '&y='+cluster_nr_y+
                            '&swLat1='+swLatLng.lat()+
                            '&swLng1='+swLatLng.lng()+
                            '&neLat1='+neLatLng.lat()+
                            '&neLng1='+neLatLng.lng()+
                            '&swLat2='+last_bounds.getSouthWest().lat()+
                            '&swLng2='+last_bounds.getSouthWest().lng()+
                            '&neLat2='+last_bounds.getNorthEast().lat()+
                            '&neLng2='+last_bounds.getNorthEast().lng());
  }
  else
  {
    request_data.send('da='+displayed_activities+
                            '&vs='+view_status+
                            '&z='+zoom+
                            '&x='+cluster_nr_x+
                            '&y='+cluster_nr_y+
                            '&swLat1='+swLatLng.lat()+
                            '&swLng1='+swLatLng.lng()+
                            '&neLat1='+neLatLng.lat()+
                            '&neLng1='+neLatLng.lng());
  }

  last_bounds = mapBounds;
}

function renewSpotsCollection(data_bounds, rows)
{
  var mapBounds = map.getBounds();

  if (data_bounds[0] == mapBounds.getSouthWest().lat() &&
      data_bounds[1] == mapBounds.getSouthWest().lng() &&
      data_bounds[2] == mapBounds.getNorthEast().lat() &&
      data_bounds[3] == mapBounds.getNorthEast().lng())
  {
    if (view_status != "spots")
    {
      toggleClustersToMarkers();
    }

    createSpots(rows, true);
  }
  else
  {
    if (view_status == "clusters")
    {
      createSpots(rows, false);
    }
    else
    {
      createSpots(rows, true);
    }
  }
}

function renewClustersCollection(rows)
{
  toggleMarkersToClusters();
 
  deleteClusters();
  createClusters(rows);
}

function toggleMarkersToClusters()
{
  // set view status to clusters
  view_status = "clusters";

  // hide all markers
      hide_spots('bowling');
      hide_spots('leisureparks');
      hide_spots('golfcourses');
      hide_spots('indoorplaygrounds');
      hide_spots('high_ropes_courses');
      hide_spots('karttracks');
      hide_spots('climbinggyms');
      hide_spots('mtb_parks');
      hide_spots('swimming_facilities');
      hide_spots('ski_regions');
      hide_spots('wakeboard_lifts');
      hide_spots('zoos');
  }

// function to toggle from clusters to markers
function toggleClustersToMarkers()
{
  // set view status to spots
  view_status = "spots";
  // selete all clusters from map and clusters array
  deleteClusters();
}

// function to delete all clusters
function deleteClusters()
{
  while (clusters.length)
  {
    map.removeOverlay(clusters.pop());
  }
}

// function to create clusters
function createClusters(rows)
{
  var i;
  for (i=3; i<rows.length; i++)
  {
    // get cluster data
    var cluster = rows[i].split("|");

    // create cluster marker
    var marker = createClusterMarker(cluster);
    
    // add marker to clusters array
    clusters.push(marker);
  }
}

// function to create one cluster marker
function createClusterMarker(cluster)
{
  // create cluster-icon
  //var icon = new GIcon(cluster_icon);

  var text = '<table>';
  var i;
  for (i=3; i<cluster.length; i+=2)
  {
    text += '<tr><td>' + active_activities[cluster[i]].name + ':</td><td style="text-align:right; margin-left:10px;">' + cluster[i+1] + '</td></tr>';
  }
  text += '<tr><td style="border-top:1px solid white;">gesamt:</td><td style="border-top:1px solid white;">' + cluster[2] + '</td></tr></table>';


  //create marker
  var marker = new M4FCluster(new GLatLng(cluster[0], cluster[1]), cluster_icon, text, cluster[2]);
  
  // add marker to map
  map.addOverlay(marker);

  return marker;
}

// function to create all spots
function createSpots(rows, areShown)
{
  var i;
  for(i=2; i<rows.length; i++)
  {
    var activity = rows[i].split("||");
    var activity_data = activity[0].split("|");

    if (activity_data[0])
    {
      if ($('selection_' + activity_data[0]).checked == true)
      {
        var j;
        for(j=1; j<activity.length; j++)
        {
          var spot = activity[j].split("|");

          var s = getSpotIfExists(spot[0], activity_data[0]);
          if (s == null)
          {
            s = createSpot(spot, activity_data);
          }
          if (!areShown)
          {
            map.removeOverlay(s.marker);
          }
        }
      }
    }
  }
}

// function to create a spot
function createSpot(spot, activity_data)
{
  var s = new Object;
  spot[0] = spot[0].substring(1,spot[0].length);
  s.token = spot[0];
  s.marker = create_marker(spot, activity_data);
  spots[activity_data[0]].push(s);

  return s;
}

// function to get and display spot if exists
function getSpotIfExists(token, activity_slug)
{
  var result = null;
  spots[activity_slug].each(function(spot)
  {
    if (spot.token == token)
    {
      map.addOverlay(spot.marker);
      result = spot;
      return result;
    }
  });
  
}

// function to create on spot marker
function create_marker(spot, activity)
{
  var text = '<table><tr><td><div class="marker marker_' + activity[0] + '" style="float: left; margin-right:5px;"></div></td><td>' + spot[1] + '</td></tr></table>';

  var u = 'http://' + 'www.maps4fun.eu' + '/index.php' + '/' + 'de' + '/' + active_activities[activity[0]].detailsUrl + '/' + spot[0];
  var marker = new M4FMarker(new GLatLng(spot[2], spot[3]), activity[0], text, spot[0], spot[1], u);

  map.addOverlay(marker);
  return marker;
}

// function to create details tab
function create_details_tab(id, name, content_url, activity)
{
  // check activity
  //i$('selection_zoos').checked = true;


  var window = $('window_' + id);
  var openTabsListItem = $('openTabsListItem_' + id);
  if(window == null)
  {
    // create window
    window = new Element('div', {
      'id' : 'window_' + id,
      'class' : 'details_tab_content',
      'styles' : {
        'display' : 'none'
      }
    });

    window.window_id = id;

    // insert into page
    window.inject($('details_content'), 'bottom');

    $('details_spinner').setStyle('display', 'block');
    // get data
    new Request.HTML({
      url: content_url,
      method: 'get',
      update: 'window_' + id,
      evalScripts: true,
      onComplete: function(){
        $('details_spinner').setStyle('display', 'none');
        write_to_stats(content_url);
      }
    }).send();

    // create open tabs list item
    openTabsListItem = new Element('div', {
      'id' : 'openTabsListItem_' + id,
      'class' : 'openTabsListItem',
      'html' : name,
      'events' : {
        'click' : function(){
          $('openTabsMenu').setStyle('width', '40px');
          open_window(id);
          write_to_stats('reopen: '+id);
        }
      }
    });

    var icon = new Element('div', {
      'class' : 'openTabsListItemImg marker marker_'+activity
    });

    icon.inject(openTabsListItem, 'top');

    // insert into page
    openTabsListItem.inject($('openTabsList'), 'bottom');
  }

  return open_window(id);
}

function open_window(window_id)
{
  var window = $('window_' + window_id);

  $$('.adtiger_'+window_id).each(function(item, index){
    item.src = item.src;
  });
  
  
  if (window.getStyle('display') != 'block')
  {
    var height = $('map_canvas').getSize().y;


    if ($('right_page').getSize().x > 0)
    {
      right_page_fx.start({
        'width': 0,
        'height' : 0,
        'top': 250
      }).chain(function(){
          $$('.details_tab_content').setStyle('display', 'none');
          window.setStyle('display', 'block');
          right_page_fx.start({
            'width': 600,
            'height' : height-30,
            'top': 10
          }).chain(function (){
              $('right_page').setStyle('bottom','20px');
              $('right_page').setStyle('height','');
            });
      });
    }
    else
    {
      $$('.details_tab_content').setStyle('display', 'none');
      window.setStyle('display', 'block');

      right_page_fx.start({
        'width': 600,
        'height' : height-30,
        'top': 10
      }).chain(function (){
              $('right_page').setStyle('bottom','20px');
              $('right_page').setStyle('height','');
            });
    }
  }

  return false;
}

// function to toggle nearby activities
var toggleFunction_near_by_activities = function(content_class, content_id) {
  $$(content_class).setStyle('display', 'none');
  $(content_id).setStyle('display', 'block');
}

// function to write to stats in piwik (can also be used vor pagelogger or another statscounter)
function write_to_stats(piwik_action_name)
{
  _gaq.push(['_trackPageview', "/" + piwik_action_name]);
}

// function to perform a serach
function quick_search()
{
  var place = $('quick_search_str').getProperty('value'); // + ', ' + $('quick_search_country').getProperty('value');
  zoomToPlace(place, 10);
  
  refresh_data(getDisplayedActivitiesString(), true);

  new Request.HTML({
    url: 'http://' + 'www.maps4fun.eu' + '/index.php' + '/' + 'de' + '/map/searchTown',
    method: 'post',
    evalScripts: true
  }).send('town=' + encodeURIComponent(place));
}

// function to zoom map to a place with given zoom-level
function zoomToPlace(place, zoom)
{
  if(geocoder)
  {
    geocoder.getLatLng(
    place,
    function(point)
    {
      if (!point)
      {
        alert(place + ' Diese Location konnte nicht gefunden werden!');
      }
      else
      {
        setCenter(point, zoom)
      }
    });
  }
  else
  {
     alert('Es ist kein Google-Maps-Geocoder verfügbar! Die Suche kann leider nicht durchgeführt werden!');
  }
}

// function to load menu
function load_menu()
{
  new Request.HTML({
    url: '/de/map-top-menu',
    method: 'post',
    update: 'top_menu',
    onComplete: function(){
      init_top_links();
    }
  }).send();
}

function refreshOpenSpots()
{
  if(dirtySpots != null)
  {
    maxIndex = dirtySpots.length;
    for (var i= maxIndex - 1; i >= 0; i--) 
    {
      var item = dirtySpots.pop();
      refresh_spot(item[0],item[1]);
    }
  }
}

function addDirtySpot(url, token)
{
  var arr = new Array(url, token);
  dirtySpots.push(arr);
}


function refresh_spot(url, token)
{
  $('window_'+token).spin();
  new Request.HTML({
    url: url,
    method: 'get',
    update: 'window_'+token,
    evalScripts: true,
    onComplete: function(){
        $('window_'+token).unspin();
    }
  }).send();
 
}

function show_editSpot()
{
  SqueezeBox.open($('spot_list').value, {handler:'iframe',size:{x:600,y:600}})
}

function show_newEntry(url)
{
   SqueezeBox.open(url, {handler:'iframe',size:{x:800,y:600}});
}

function init_footer()
{
  
  $('footer_btn_navi').addEvent('click', function()
  {
    return create_details_tab('navi',
                              'Freizeit-Navigator',
                              '/de/static/navi',
                              'navi');
  });

  $('footer_btn_navi').addEvent('mouseover', function()
  {
    $('footer_menu_info_text').set('html', 'Wählen Sie direkt aus unserer Liste der größten Städte in jedem Bundesland...');
    $('footer_menu_info_text').setStyle('display', 'block');
  });

  $('footer_btn_navi').addEvent('mouseout', function()
  {
    $('footer_menu_info_text').setStyle('display', 'none');
  });

  $('footer_btn_partner').addEvent('click', function()
  {
    return create_details_tab('partner',
                              'Partner von maps4fun',
                              '/de/static/partner',
                              'partner');
  });

  $('footer_btn_partner').addEvent('mouseover', function()
  {
    $('footer_menu_info_text').set('html', 'Hier erfahren Sie mehr dazu, wie Ihre Homepage Partner von maps4fun werden kann...');
    $('footer_menu_info_text').setStyle('display', 'block');
  });

  $('footer_btn_partner').addEvent('mouseout', function()
  {
    $('footer_menu_info_text').setStyle('display', 'none');
  });

  $('footer_btn_ad').addEvent('click', function()
  {
    return create_details_tab('ads',
                              'Werben auf maps4fun',
                              '/de/static/ads',
                              'ads');
  });

  $('footer_btn_ad').addEvent('mouseover', function()
  {
    $('footer_menu_info_text').set('html', 'Sie möchten Ihre Werbung auf maps4fun platzieren?');
    $('footer_menu_info_text').setStyle('display', 'block');
  });

  $('footer_btn_ad').addEvent('mouseout', function()
  {
    $('footer_menu_info_text').setStyle('display', 'none');
  });

  $('footer_btn_shop').addEvent('click', function()
  {
    return create_details_tab('shop',
                              'Schnäppchen-Shop',
                              '/de/static/shop',
                              'shop');
  });

  $('footer_btn_shop').addEvent('mouseover', function()
  {
    $('footer_menu_info_text').set('html', 'Besuchen Sie den maps4fun-Shop...');
    $('footer_menu_info_text').setStyle('display', 'block');
  });

  $('footer_btn_shop').addEvent('mouseout', function()
  {
    $('footer_menu_info_text').setStyle('display', 'none');
  });

  // init footer links
  $$('.impressumLink').addEvent('click', function(){
    write_to_stats('de/footer/impressum');
    var url = "/de/static/impressum";
    SqueezeBox.open(url, {handler: 'iframe', size:{x:700,y:400}});
  });

  $$('.agbsLink').addEvent('click', function(){
    write_to_stats('de/footer/agbs');
    var url = "/de/static/agbs";
    SqueezeBox.open(url, {handler: 'iframe', size:{x:700,y:400}});
  });
}

function init_fisheye_menu()
{
  fisheye_menu = new iFishEye({
    container: $("iFishEye_menu"),
    norm: "L2"
  });
}

function init_start_tab()
{
  $$('.newEntryWizLink').addEvent('click', function(){
    write_to_stats('de/static/new_entry');
    var url = "/de/spot/newEntryWiz";
    SqueezeBox.open(url, {handler: 'iframe', size:{x:900,y:500}, onClose: load_menu});
  });

  $$('.registerLink').addEvent('click', function(){
    write_to_stats('de/register');
    var url = "/de/apply";
    SqueezeBox.open(url, {handler: 'iframe', size:{x:750,y:400}, onClose: load_menu});
  });

  $$('.tippsLink_register').addEvent('click', function(){
    write_to_stats('de/static/tipps_register');
    var url = "/de/static/tipps_register";
    SqueezeBox.open(url, {handler: 'iframe', size:{x:750,y:500}});
  });


  $$('.comingSoonLink').addEvent('click', function(){
    write_to_stats('de/static/coming_soon');
    var url = "/de/static/coming_soon";
    SqueezeBox.open(url, {handler: 'iframe', size:{x:500,y:400}});
  });
}

function setCenter(point,zoom,force_refresh)
{
  //320 = total-width/2 - (total-width - (right-page-width + menu-caption-width))/2 = (right-page-width + menu-caption-width)/2 = (600+40)/2
  //var dif_x = -($('right_page').getSize().x + $('openTabsMenuCaption').getSize().x)/2;
  if ( force_refresh === undefined ) {
      force_refresh = false;
   }

  if (force_refresh)
  {
    is_my_set_center = false;
  }
  else
  {
    is_my_set_center = true;
  }

  map.setCenter(point,zoom);
  map.panBy(new GSize(-320,0));
}

function checkAllActivities()
{
      $('selection_bowling').checked = true;
      $('selection_leisureparks').checked = true;
      $('selection_golfcourses').checked = true;
      $('selection_indoorplaygrounds').checked = true;
      $('selection_high_ropes_courses').checked = true;
      $('selection_karttracks').checked = true;
      $('selection_climbinggyms').checked = true;
      $('selection_mtb_parks').checked = true;
      $('selection_swimming_facilities').checked = true;
      $('selection_ski_regions').checked = true;
      $('selection_wakeboard_lifts').checked = true;
      $('selection_zoos').checked = true;
    return true;
}

function uncheckAllActivities()
{
      $('selection_bowling').checked = false;
      $('selection_leisureparks').checked = false;
      $('selection_golfcourses').checked = false;
      $('selection_indoorplaygrounds').checked = false;
      $('selection_high_ropes_courses').checked = false;
      $('selection_karttracks').checked = false;
      $('selection_climbinggyms').checked = false;
      $('selection_mtb_parks').checked = false;
      $('selection_swimming_facilities').checked = false;
      $('selection_ski_regions').checked = false;
      $('selection_wakeboard_lifts').checked = false;
      $('selection_zoos').checked = false;
  
  deleteClusters();
  
  return true;
}

function openInSqueezeBox()
{
  var url;
  switch (this.get('id'))
  {
    case 'mnu_apply':
      url = "/de/apply";
      SqueezeBox.open(url, {handler:'iframe',size:{x:600,y:530}});
      write_to_stats('de/top-menu/register');
      break;
    case 'mnu_login':
      url = "/de/loggedin";
      SqueezeBox.open(url, {handler:'iframe',size:{x:350,y:200},onClose: load_menu});
      write_to_stats('de/top-menu/login');
      break;
    case 'mnu_logout':
      url = "/de/logout";
      SqueezeBox.open(url, {handler: 'iframe', size:{x:350,y:160}, onClose: load_menu});
      write_to_stats('de/top-menu/logout');
      break;
    case 'mnu_contact':
      url = "/de/contact";
      SqueezeBox.open(url, {handler: 'iframe', size:{x:450,y:450}});
      write_to_stats('de/top-menu/contact');
      break;
    case 'mnu_newentry_wiz':
      url = "/de/spot/newEntryWiz";
      SqueezeBox.open(url, {handler: 'iframe', size:{x:900,y:480}, onClose: load_menu});
      write_to_stats('de/top-menu/new-entry');
      break;
    case 'mnu_user_settings':
      url = "/de/settings"
      SqueezeBox.open(url, {handler: 'iframe', size:{x:550,y:600}});
      break;
    case 'mnu_my_spots':
      url = "/de/manage-spot";
      SqueezeBox.open(url, {handler: 'iframe', size:{x:800,y:600}, onClose: load_menu});
      write_to_stats('de/top-menu/mySpots');
      break;
  }
}

function init_top_links()
{
   var mnuApply = $('mnu_apply');
   var mnuLogin = $('mnu_login');
   var mnuLogout = $('mnu_logout');
   var mnuContact = $('mnu_contact');
   var mnuNewEntryWiz = $('mnu_newentry_wiz');
   var mnuSettings = $('mnu_user_settings');
   var mnuManageSpot = $('mnu_my_spots');

   if(mnuApply != null)
   {
      mnuApply.addEvent('click', openInSqueezeBox.bind(mnuApply));
   }
   if(mnuLogin != null)
   {
      mnuLogin.addEvent('click', openInSqueezeBox.bind(mnuLogin));
   }

   if(mnuLogout != null)
   {
     mnuLogout.addEvent('click',openInSqueezeBox.bind(mnuLogout));
   }

   if(mnuSettings != null)
   {
      mnuSettings.addEvent('click',openInSqueezeBox.bind(mnuSettings));
   }

   if(mnuManageSpot != null)
   {
     mnuManageSpot.addEvent('click', openInSqueezeBox.bind(mnuManageSpot));
   }

   if(mnuNewEntryWiz != null)
   {
     mnuNewEntryWiz.addEvent('click', openInSqueezeBox.bind(mnuNewEntryWiz));
   }

   if(mnuContact != null)
   {
     mnuContact.addEvent('click', openInSqueezeBox.bind(mnuContact));
   }
}