// register ajaxnotifier for the whole app
Ajax.Responders.register({
      onCreate: function(rq, xml){ 
        if(rq.container && rq.container.success == 'pm-count') return;
        Element.show('indicator'); 
      }, 
      onComplete: function(){ Element.hide('indicator'); }
});
document.onkeydown = function(event) {
  if(event) {
    if(event.keyCode == Event.KEY_ESC) {
        if($('grossbild').visible()) 
          $('grossbild').hide();
        else
          closeView();
        
        return false;
      }
  }
};

var categories = ['', 
      'Bücher, CDs & Filme',    
      'Büro & Arbeit',    
      'Computer & Elektronik',  
      'Haushalt & Hof',
      'Hobbys & Sammeln',
      'Kleidung & Mode',
      'Möbel & Antiquitäten',
      'Sport & Freizeit',
      'Spielzeug',
      'Tierwelt',
      'Sonstiges & Kurioses'
    ];


var windowSize = getInnerSize();
window.onresize = function () {  
  windowSize = getInnerSize();
  if($('content-scroll')) $('content-scroll').style.maxHeight = (windowSize[1] - 182) + 'px';
  if($('content-iframe')) $('content-iframe').style.maxHeight = (windowSize[1] - 182) + 'px';
  if($('onmaplist-scroll')) $('onmaplist-scroll').style.maxHeight = (windowSize[1] - 182) + 'px';
  if($('grossbild-img'))    $('grossbild-img').style.maxHeight = (windowSize[1] - 182) + 'px';  
}
window.onload = window.onresize;

function fetch_article(id) {
  map.map.savePosition();
  new Ajax.Updater('mp_content',
  '/article/fetcharticle/' + id,  // TODO URL
  {
    method:'get',
    evalScripts: true,    
    onComplete: function () {
      if(!$("mp_container").visible()) Effect.BlindDown("mp_container");
      pageTracker._trackPageview("/article/fetcharticle/"+id);
    }    
  });
}

/**
 * position the searchnotifier depending on whether the
 * normalnotifier is visible (they should not overlap!)
 */
function repositionSearchNotifier(forceDown) {
  if($('notifier').visible() || forceDown) {
    $('search-notifier').style.top = "165px";
  } else {
    $('search-notifier').style.top = "135px";
  }
}

var notifierEffect = null;
function notify(msg) {  
  if(msg == '' && $('notifier')) {
    $('notifier').hide();
    repositionSearchNotifier();
  } else {
    $('notifier-content').innerHTML = msg;
    if(notifierEffect) {
      notifierEffect.cancel();
    } 
    repositionSearchNotifier(true);
    new Effect.Appear('notifier');
    notifierEffect = new Effect.Fade('notifier', 
      {
      duration: 7,
      from: 1.0,
      queue: "end",
      afterFinish: function () { repositionSearchNotifier(); }
      });
  }
}

var geocoder = new GClientGeocoder();
var germany = new GLatLng(51.165,10.455278);
function gotoZip(zip) { 
  geocoder.setBaseCountryCode('DE')
  geocoder.getLatLng(zip +', germany', 
    function(point) { 
      if (!point)
        notify(zip + ' nicht gefunden. ');
      else if((point.distanceFrom(germany) / 1000) > 700) {
        notify(zip + ' nicht gefunden. ');
      }else { 
        map.map.setCenter(point);  
        if( map.map.getZoom()  < 11  ) {
          map.map.setZoom(11);
        }
        
        map.fetch(false);
      }
    }
  );
}

function gotoZipRegister(zip) { 
  geocoder.setBaseCountryCode('DE')
  geocoder.getLatLng(zip +', germany', 
    function(point) { 
      if (!point)
        notify(zip + ' nicht gefunden. ');
      else if((point.distanceFrom(germany) / 1000) > 700) {
        notify(zip + ' nicht gefunden. ');
      } else { 
        newMap.setCenter(point);  
        if( newMap.getZoom()  < 11  ) {
          newMap.setZoom(11);
        }
      }
    }
  );
}


var nrFavsSaved = 0;
function add_fav(id) {
  new Ajax.Updater('favlist',
  '/article/fetchfavs',
  {
    method:'post',
    parameters: { add: id },
    onComplete: function () { if($('fav_'+id)) new Effect.Highlight('fav_' + id, {startcolor:'#fac0ff'}); },
    evalScripts: true
  });
  pageTracker._trackPageview("/addfav");
  return false;
}

function del_fav(id) {
  new Ajax.Request('/article/fetchfavs',
  { 
    method:'get',
    parameters: { del: id }
  });
  nrFavsSaved --;
  new Effect.Fade('fav_'+ id, {
      afterFinish: function() {
        if(nrFavsSaved == 0)
          $('fav_0').show();
      }
  });
  pageTracker._trackPageview("/delfav");
}
function show_article(id, lat, lng, clear) {
  if(map.map.getZoom() < 11) {
    map.map.setZoom(11);
  }
  if(clear) {
    $('cat_filter').category.selectedIndex = 0;
    $('search').value = 'Artikel finden...';
    new Ajax.Request('/map/clearall',
      {
        method: 'get',
        onComplete: function () {
          map.map.setCenter(new GLatLng(lat, lng));
          map.setOpenId(id);
          map.fetch(true);          
        }
      });
  } else {
    map.map.panTo(new GLatLng(lat, lng));
    map.setOpenId(id);
  }
}

function refetch() {
  map.clear();
  map.fetch(true);
}

function clearAllFilter() {
  $('search').value = 'Artikel finden...';
  $('cat_filter').category.selectedIndex = 0;
  $('search-notifier').hide();
  new Ajax.Updater('search-notifier', '/map/clearall',
    {
      method: 'get',
      evalScripts: true
    });
}

function clearFilter() {
  $('search').value = 'Artikel finden...';
  new Ajax.Updater('search-notifier', '/map/clearfilter',
    {
      method: 'get',
      evalScripts: true
    });
}

// set a filter on the map *then reload
function filterCategory(id) {
  new Ajax.Updater('search-notifier', '/map/category',
    {
      method: 'get',
      parameters: { category: id },
      evalScripts: true,
      onComplete:  function() {refetch();}
    });
}

// close open threads in pm view
var openThread = 0;
function toggleThreads(threadId) {
  // thread oeffnen und klasse setzen
  $('thread_' + threadId).addClassName('activethread');
  $('thread_' + threadId).removeClassName('thread');
  Effect.SlideDown('thread_container_' + threadId, {duration: 0.4});
  // bold wegmachen (wegen NEU etc)
  Element.setStyle('thread_title_' + threadId, {fontWeight: 'normal'});
  // alten thread schliessen
  if(openThread != 0 && openThread != threadId) {
    $('thread_' + openThread).removeClassName('activethread');
    $('thread_' + openThread).addClassName('thread');
    // antwort formular verstecken im schliessenden thread
    if($('new_'+threadId)) Effect.Fade('new_' + threadId);
    Effect.BlindUp('thread_container_' + openThread, {duration: 0.4});
  }
  openThread = threadId;
}

function markOpenTab(tab) {
  for(var i = 1; i < 8; i++) {
    if($('tab-' + i) ) $('tab-' + i).removeClassName('active'); 
  }
  if(tab != 0 && $('tab-' + tab)) $('tab-' + tab).addClassName('active'); 
  // not for special Anbieten tab
  if(tab != 4) abortNew();
}


// reloadMarker control whether the map markers
// are reloaded when the current content is closed.
// it defaults to true
// every content page that dont need reload (article details etc)
// can set reloadMarker to false (vie set_title helper!)
// nothing needs to be changed at all for default behavior (that is reload)
var reloadMarker = false;
function closeView() {
  abortNew();
  if($('mp_container').visible()) {
    if(reloadMarker) {
      map.clear(); map.fetch(true);
    }
    reloadMarker = false;
    Effect.BlindUp('mp_container',
      { afterFinish: function() {
        $("sub").removeClassName("contentopen");
      }});
    $('contentClose').addClassName('invisible');
    $('contentTitle').innerHTML = '';
    markOpenTab(1);
  }
}

var onMapListOpen = true;
function toggleOnMapList() {
  Effect.toggle('listContainer', 'blind', 
    {afterFinish: function() {
      if(onMapListOpen) {
        $('sub').removeClassName('listopen');
        $('viewOnmapList').removeClassName('isOpen');
        map.map.removeControl(fakeOnMapListControl);
      }
      onMapListOpen = !onMapListOpen;
      },
      beforeStart: function () {
        if(!onMapListOpen) {
          $('sub').addClassName('listopen');
          $('viewOnmapList').addClassName('isOpen');    
          map.map.addControl(fakeOnMapListControl);
        }
    }});
  return false;
}

function getInnerSize() {
  var x,y;
  if (window.innerHeight) // all except Explorer
  {
    x = window.innerWidth;
    y = window.innerHeight;
  }
  else if (document.documentElement && document.documentElement.clientHeight)
    // Explorer 6 Strict Mode
  {
    x = document.documentElement.clientWidth;
    y = document.documentElement.clientHeight;
  }
  else if (document.body) // other Explorers
  {
    x = document.body.clientWidth;
    y = document.body.clientHeight;
  }
  return new Array(x, y);
}


/**
 *code fuer: neuen artikel ueber die haupkarte anlegen
 */
var clickHandler = null;
var formerOnMapListState = true;
function startNew() {
  map.setMapControlPositionUp(false);
  if(clickHandler === null) {
    formerOnMapListState = onMapListOpen;
    if(onMapListOpen) toggleOnMapList();    
    clickHandler = GEvent.addListener(map.map, "click", function(o, point) {
      if(!o) {
        abortNew();
        new Ajax.Updater('mp_content',
            '/article/createFrame',
            {
              method:'get',
              parameters: { lat: point.lat(), lng: point.lng() },
              onComplete: function () {
                if(!$("mp_container").visible())Effect.SlideDown("mp_container");
              },
              evalScripts: true
            });
      }
    });
  }
}

function abortNew() {
  if(clickHandler) {
    map.setMapControlPositionUp(true);
    GEvent.removeListener(clickHandler);
    clickHandler = null;
    if(formerOnMapListState != onMapListOpen) {
      toggleOnMapList();
    }
  }
}

/**
 * pagelets blaettern (zb bei article create)
 */
function showPagelet(toOpen, nrOfPagelets, url) {
  for(var i = 1; i <= nrOfPagelets; i++) {
    if(i == toOpen) continue;
    $('pagelet' + i).hide();
    $('pagelink' + i).removeClassName('active');
  }
  $('pagelet' + toOpen).show();
  $('pagelink' + toOpen).addClassName('active');
  if(toOpen == 1) {
    fixPicker();
  }
  //google analytics for pagelets
  pageTracker._trackPageview(url+"/pagelet"+toOpen);
}


var newMap;
function fixPicker() {
  var lng = document.forms["picker"].longitude.value;
  var lat = document.forms["picker"].latitude.value;
  newMap.checkResize();
  if(lat && lng) {
    newMap.setCenter(new GLatLng(lat, lng));
  }
  
}