/* send json as array to save bandwidth. array keys: */
var k_id      = 0;
var k_name    = 1;
var k_lat     = 2;
var k_lng     = 3;
var k_address = 4;
var k_phone   = 5;
var k_url     = 6;
var k_teaser  = 7;
var k_main_category = 8;
var k_categories = 9;

/* globals */
var places;
var map; 
var clusterer;
var categories    = [];
var first_toggle  = true;
var category_toggle = [];

var current_place = 0;
var per_page      = 5;

var icons = gen_icons();

var url_target = '';
if (typeof(url_prefix)=='undefined') {
  var url_prefix = '';
  url_target = '_self';
} else {
  url_target = '_blank';
}

/* on DOM load */
$(initialize_map);

function initialize_places() {


/* cluster */
  var cluster_icon = new GIcon();
  cluster_icon.iconsize = new GSize(25,41);
  cluster_icon.iconAnchor = new GPoint(1,41);
  cluster_icon.infoWindowAnchor = new GPoint(1,41);
  cluster_icon.image = "/images/gm_icons_flat/cluster.png";

  clusterer = new Clusterer(map);
  clusterer.SetIcon(cluster_icon);


  for (var i=0; i<places.length; i++) {
      var latlng = new GLatLng(places[i][k_lat], places[i][k_lng]);
      var marker = new GMarker(latlng, { title: places[i][k_name], icon: get_icon([places[i][k_main_category]]) });
      addInfoWindowToMarker(marker, info_window_for(places[i]), null);
      marker.category = places[i][k_main_category];
      clusterer.AddMarker(marker, places[i][k_name]);
      // if (typeof categories[marker.category] == "undefined") {
      //   categories[marker.category] = [];
      // }
      // categories[marker.category].push(marker);
  }

  $('#loading').remove();
}




function initialize_places_for_print() {

/* cluster */
  var cluster_icon = new GIcon();
  cluster_icon.iconsize = new GSize(25,41);
  cluster_icon.iconAnchor = new GPoint(1,41);
  cluster_icon.infoWindowAnchor = new GPoint(1,41);
  cluster_icon.image = "/images/gm_icons_flat/cluster.png";

  clusterer = new Clusterer(map);
  clusterer.SetIcon(cluster_icon);



  for (var i=0; i<places.length; i++) {

    var greenIcon = new GIcon(G_DEFAULT_ICON);
    var ii = i+1;
    greenIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/green/marker"+ii+".png";
    // Set up our GMarkerOptions object
    markerOptions = { icon:greenIcon };

      var latlng = new GLatLng(places[i][k_lat], places[i][k_lng]);
      var marker = new GMarker(latlng, { title: places[i][k_name], icon: greenIcon });
//      addInfoWindowToMarker(marker, info_window_for(places[i]), null);
//      marker.category = places[i][k_main_category];
      clusterer.AddMarker(marker, places[i][k_name]);
      // if (typeof categories[marker.category] == "undefined") {
      //   categories[marker.category] = [];
      // }
      // categories[marker.category].push(marker);
  }

  $('#loading').remove();
}




/* return html content of info window for a marker */
function info_window_for(place) {
  var icon = get_icon(place[k_main_category]);
/*  var info = "<h3>"
  for (var i=0; i<place[k_categories].length; i++) {
    icon = get_icon(place[k_categories][i]);
    info += '<img src="' + icon.image_square + '" />';
  }  
  info += '<a href="/places/' + place[k_id] + '?locale=' + locale + '">' + place[k_name] + '</a></h3>';
*/
  var info = '<h3><img src="' + icon.image_square + '" /><a target="'+ url_target +'" href="'+ url_prefix +'/places/' + place[k_id] + '?locale=' + locale + '">' + place[k_name] + '</a></h3>';
  info += '<div class="address">' + place[k_address] + '</div>';
  info += '<div class="phone">' + place[k_phone] + '</div>';
  if (place[k_url]) {
    var myRegExp = /http:/;
    var matchPos1 = place[k_url].search(myRegExp);
    if(matchPos1 != -1)
      myRegExp = place[k_url];
    else
      myRegExp = "http://"+place[k_url];
    info += '<div class="web"><a target="_blank" href="' + myRegExp + '">' + place[k_url] + '</a></div>';
  }
  info += '<div class="desc">' + place[k_teaser] + '</div>';
  return info
}

/* return html content of place listing for a marker */
function place_listing_for(place, i) {
  var icon = get_icon(place[k_main_category]);
  var info = '<div class="place"><h4><a href="/places/' + place[k_id] + '">' + i + ". " + place[k_name] + '</a></h4>';
  info += '<div class="desc">' + place[k_teaser] + '</div></div>';
  return info
}

/* returns the category GIcon for the given category */      
function get_icon(i) {
  if (icons[i]) {
    return icons[i];
  } else {
    return icons[0];
  }
}

/* Array.filter callback for filtering categories */
function isBigEnough(element, index, array) {
  return (element >= 10);
}

/* toggles display of markers in given category */
function toggle_category(cat) {
  
    // show only selected category if none have been toggled before
    if (first_toggle) {
      hide_markers(clusterer.markers);
      show_markers(categories[cat]);
      category_toggle[cat] = "on";      
      first_toggle = false;
      return;
    }
  
  
    if ((typeof category_toggle[cat] == "undefined") || (category_toggle[cat] == "off")) {
      show_markers(categories[cat]);
      category_toggle[cat] = "off";
    } else {
      hide_markers(categories[cat]);
      category_toggle[cat] = "on";      
    }
}

/* hide markers given in array */
function hide_markers(mks) {
  for (var i=0; i<mks.length; i++) {
    mks[i].hide();
  }
}

/* show markers given in array */
function show_markers(mks) {
  for (var i=0; i<mks.length; i++) {
    mks[i].show();
  }
}


/* generates category GIcons - needs update when categories change */
function gen_icons() {
  var icon_images = {
    0: 'landmark',
    1: 'farmerslocalmarket',
    2: 'greenstore',
    3: 'healthydining',
    4: 'ecoagriculturepermaculture',
    5: 'reuseshopmarket',
    6: 'fairtrade',
    7: 'ecotourismresource',
    8: 'recycling',
    9: 'rentalshare',
    10: 'repairshop',
    11: 'artisanartstudio',
    12: 'megujulo',
    13: 'greenbuilding',
    14: 'bicyclesite',
    15: 'bicycleparking',
    16: 'watertransport',
    17: 'parknridefacility',
    18: 'termeszeti',
    19: 'sportsiteplaywithnature',
    20: 'culturalsite',
    21: 'communitycenter',
    22: 'ecoinformation',
    23: 'greenschool',
    24: 'publiclibrary',
    25: 'volunteersite',
    26: 'drinkinwatersource',
    27: 'allatmenhely',
    57: 'telehaz',
    58: 'kisvasut',
    59: 'fogyasztovedelem'
}

  var icons = [];
  for (var i in icon_images) {
    icon = new GIcon();
    icon.iconsize = new GSize(25,41);
    icon.iconAnchor = new GPoint(1,41);
    icon.infoWindowAnchor = new GPoint(1,41);
    icon.image = "/images/gm_icons_flat/"+icon_images[i]+".png";
    icon.image_square = "/images/gm_icons_square/"+icon_images[i]+".png";
    icons[i] = icon;
  }
  
  return icons;
}

/* initializes sidebar place listing */
function list_setup() {
  /* list */
  populate_place_list();
  // $('#next_place_page').click(function() { 
  //   current_place += per_page;
  //   populate_place_list();
  //   return false;
  // });
  // 
  // $('#prev_place_page').click(function() { 
  //   current_place -= per_page;
  //   populate_place_list();
  //   return false;
  // });
  // 
  // $('#category-toggles a').click(function() {
  //   var n = this.id.substring(4);
  //   toggle_category(n);
  //   $(this).toggleClass("active");
  //   return false;
  // }); 
}

/* renders the place list in the sidebar */
function populate_place_list() {
 $("#box_results").show();
/* var html = '';
 for (var i=current_place; i < current_place + per_page; i++) {
   html += place_listing_for(places[i], i+1);
 }
 
 if (current_place < places.length - 10) {
   $("#next_place_page").show();
 } else {
   $("#next_place_page").hide();
 }
 
 if (current_place > 0) {
   $("#prev_place_page").show();
 } else {
   $("#prev_place_page").hide();
 }  
  $('#place_list').html(html);*/
 
 var query_string = window.location.search.substring(1);
 
 $('#place_list_box').load("/map/list?" + query_string);
 
 $('div.pagination a').live('click', function() {  /* AJAX will_paginate */
     $('#place_list_box').load(this.href)
     return false
 })
}

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}


// fade flash on map
$(function() { 
  $('#map-flash').fadeOut(2000);
});