//<![CDATA[
Event.observe(window, 'load', Gload, false);
Event.observe(window, 'unload', GInitCity, false);
/*Event.observe(window, 'load', AjaxLink, false);*/
var Gmap = null;
var Ggeocoder = new GClientGeocoder();
var Gcity = '';
var Gzoom = 5;
var Ginfo = '';
//var Gmap = new GMap2(document.getElementById("map"));
var Glocations = {};
var searchLoad = '<h3 style="text-align: center;"><img src="http://static.absolimmo.com/img/v2/pg/ajax-loader2.gif" atl="chargement" title="chargement" /> Chargement ...</h3>';
function Abso_searchAjax(x, y) {
  if(!x) {
    x = '/ajax.php?search&' + $('form-search').serialize();
    GshowAddress($F('city'));
  }
  var tggalston = new Ajax.Updater('classified-search', x, {
      method: 'get',
      onComplete: function() {
        $('classified-search-ajax').removeClassName('loading');
        absolimmo_elem($('classified-search'));
        Abso_adsSrv('c32-2', 'carre300');
        //Abso_adsSrv('p3', 'partners300');
        pageTracker._trackPageview("/resultajax" );
      },
      onLoading: function() {
        $('classified-search-ajax').addClassName('loading');
        $('searchLoading').update(searchLoad);
        new Effect.ScrollTo('searchLoading');
        //$('searchLoading').scrollTo();
      }
    }
  );
}
/*
function AjaxLink() {
  a = document.getElementsByClassName('ajax-link');
  for(i = 0; i < a.length; i++) {
    action = [i].onclick;
    a[i].onclick = function() {action};
  }
}*/


function searchControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
searchControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
searchControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var searchMap = document.createElement("div");
  this.setButtonStyle_(searchMap);
  container.appendChild(searchMap);
  searchMap.appendChild(document.createTextNode("Rechercher sur la carte"));
  GEvent.addDomListener(searchMap, "click", function() {
    if(Gmap.getZoom() >= 9 ) {
      var Gbound = Gmap.getBounds();
      var swLat = Gbound.getSouthWest().latRadians();
      var swLng = Gbound.getSouthWest().lngRadians();
      var neLat = Gbound.getNorthEast().latRadians();
      var neLng = Gbound.getNorthEast().lngRadians();
      var Aurl = '/ajax.php?search&map=true&swLat=' + swLat + '&swLng=' + swLng + '&neLat=' + neLat + '&neLng=' + neLng + '&' + $('form-search').serialize();
      Abso_searchAjax(Aurl);
    } else {
      alert('Veuillez zoomer sur la carte pour actualiser votre recherche');
    }
  });


  Gmap.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
searchControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(7, 7));
}

// Sets the proper CSS for the given button element.
searchControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "underline";
  button.style.color = "#fff";
  button.style.backgroundColor = "#e01129";
  button.style.font = "small Arial";
  button.style.border = "1px solid #fff";
  button.style.padding = "2px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = "8em";
  button.style.cursor = "pointer";
}


function Gload() {
  if (GBrowserIsCompatible()) {
    if($('gmap')) {
      Gmap = new GMap2($('gmap'));
      Gmap.setCenter(new GLatLng(0, 0), 13);
      Gmap.addControl(new GMapTypeControl());
      Gmap.addControl(new GSmallZoomControl3D());
      if($('re-search')) {
        Gmap.addControl(new searchControl());
        GEvent.addDomListener(Gmap, 'dragend', function() {
          uAS();
        });
        GEvent.addDomListener(Gmap, 'zoomend', function() {
          uAS();
        });
      } //
      GInitCity();
    }
  } //
} //

function uAS() {
  Gmap.clearOverlays();
  Glocations = {};
  if(Gmap.getZoom() >= 9 ) {
    var GlgLat = Gmap.getCenter();
    var Gbound = Gmap.getBounds();
    var swLat = Gbound.getSouthWest().latRadians();
    var swLng = Gbound.getSouthWest().lngRadians();
    var neLat = Gbound.getNorthEast().latRadians();
    var neLng = Gbound.getNorthEast().lngRadians();
    //alert('/xml/cf.php?&long=' + GlgLat.lngRadians() +'&lat=' + GlgLat.latRadians() + '&swLat=' + swLat + '&swLng=' + swLng + '&neLat=' + neLat + '&neLng=' + neLng + '&' + $('form-search').serialize());
    GDownloadUrl('/xml/cf.php?km=20&long=' + GlgLat.lngRadians() +'&lat=' + GlgLat.latRadians() + '&swLat=' + swLat + '&swLng=' + swLng + '&neLat=' + neLat + '&neLng=' + neLng + '&' + $('form-search').serialize(), function(data) {
    var xml = GXml.parse(data);
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("name");
      var address = markers[i].getAttribute("address");
      var type = markers[i].getAttribute("type");
      var count = markers[i].getAttribute("count");
      var idcity = markers[i].getAttribute("idcity");
      var latlng = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                              parseFloat(markers[i].getAttribute("lng")));
                              
      var store = {latlng: latlng, name: name, address: address, type: type, count: count, idcity: idcity};
      //var latlngHash = (latlng.lat().toFixed(6) + "" + latlng.lng().toFixed(6));
      var latlngHash = (latlng.lat() + '' + latlng.lng());
      latlngHash = latlngHash.replace('.', '').replace('.', '').replace('-','');
      if (Glocations[latlngHash] == null) {
        Glocations[latlngHash] = []
      }
      Glocations[latlngHash].push(store);
    }
    for (var latlngHash in Glocations) {
      var stores = Glocations[latlngHash];
      if (stores.length > 1) {
        //Gmap.addOverlay(createClusteredMarker(stores));
        Gmap.addOverlay(createMarker(stores));
      } else {
        Gmap.addOverlay(createMarker(stores));
      }
    }
  });
  }
}

function createMarker(stores) {
  var store = stores[0];
  var newIcon = MapIconMaker.createMarkerIcon({width: 32, height: 32, primaryColor: "#e01129"});
  var marker = new GMarker(store.latlng, {icon: newIcon});
  var html = '<b>' + store.name + '</b> <br />' + store.count + ' annonce(s) <br /><br />'
           + '<a href="javascript: gr(\'' + store.address + '\', \'' + store.idcity  + '\');">Voir les annonces</a>';
  GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowHtml(html);
  });
  return marker;
}

function createClusteredMarker(stores) {
  var newIcon = MapIconMaker.createMarkerIcon({width: 44, height: 44, primaryColor: "#e01129"});
  var marker = new GMarker(stores[0].latlng, {icon: newIcon});
  var html = "";
  for (var i = 0; i < stores.length; i++) {
    html += "<b>" + stores[i].name + "</b> <br/>" +  + "<br/>";
  }
  GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowHtml(html);
  });
  return marker;
}

function gr(a, i) {
  $('city').value = a;
  $('idcity').value = i;
  Abso_searchAjax();
}

function initCity(city, zoom, info) {
  Gcity = city;
  Gzoom = zoom;
  Ginfo = info;
}
function initCityNoInfo(city, zoom) {
  Gcity = city;
  Gzoom = zoom;
}
function GInitCity() {
  if(Gcity != '') {
    GshowAddress(Gcity);
  }
}
function GshowAddress(address) {
  if (!Ggeocoder) {
    var Ggeocoder = new GClientGeocoder();
  }
  Ggeocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        //alert(address + " n'existe pas");
      } else {
        Gmap.setCenter(point, Gzoom);
        var marker = new GMarker(point);
        Gmap.addOverlay(marker);
        if(Ginfo != '') {
          marker.openInfoWindowHtml(Ginfo);
        }
      }
    }
  );
}

function c(txt) {
  return confirm(txt);
}

function cc(txt, h) {
	if(confirm(txt)) {
		document.location.href = h;
	} else {
		return false;
	}
}

function orderCf() {
  $('o').value = $('order').value;
  Abso_searchAjax();
}

var init_lb = new Array();
function lb(o) {
	if(!isset(init_myrtille_lb[o.getAttribute('id')])) {
		new lightbox(o);
	}
	init_lb[o.getAttribute('id')] = true;
}

function acp(l, uid) {
  Abso_searchAjax('/ajax.php?search&' + $('form-search').serialize() + '&p=' + l);
  return false;
}

function cAf(y, g) {
  Abso_searchAjax('/ajax.php?search&' + $('form-search').serialize() + '&vs=' + y + '&p=' + g);
}

function cd(i, f) {
  var xfe = document.getElementsByClassName('fulllink');
	for(c = 0; c < xfe.length; c++) { 
    xfe[c].removeClassName('selected');
  }
  $('fulllink' + i).addClassName('selected');
  var tggalston = new Ajax.Updater('classified-full-content', '/ajax.php?classifiedfull&no&t=' + i + '&cfid=' + f, {
      method: 'get',
      evalScripts: true,
      onComplete: function() {
        $('classified-full-content').removeClassName('loading');
        $('classified-full-loader').update('');
        absolimmo_elem($('classified-full-content'));
        pageTracker._trackPageview("/classifiedfull" );
      },
      onLoading: function() {
        $('classified-full-content').addClassName('loading');
        $('classified-full-loader').update(searchLoad);
        //$('searchLoading').scrollTo();
      }
    }
  );
}

function Abso_submitFormContact(a) {
  $('f-contact').submit = function() { return false; };
  var fsbc = new Ajax.Updater('form-contact-update', '/ajax.php?formcontact&no&cfid=' + a, {
      method: 'post',
      parameters: $('f-contact').serialize(),
      onComplete: function() {
        $('form-contact-update').removeClassName('loading');
        /*absolimmo_elem($('classified-search'));*/
        pageTracker._trackPageview("/formcontact");
      },
      onLoading: function() {
        $('form-contact-update').addClassName('loading');
        $('form-contact-update').update(searchLoad);
      }
    }
  );
  return false;
}
function Abso_deleteDoc(a) {
  var fsbc = new Ajax.Updater('form-contact-update', '/ajax.php?deletephoto&no&doid=' + a, {
      method: 'post',
      onComplete: function() {
        /*$('form-contact-update').removeClassName('loading');*/
        /*absolimmo_elem($('classified-search'));*/
        new Effect.Fold('user-photo-' + a);
        pageTracker._trackPageview("/deletephoto" );
      },
      onLoading: function() {
        $('user-photo-' + a).addClassName('loading');
      }
    }
  );
}

function ptt(i) {
  new Effect.BlindUp('vtc' + i, {fps: 60, duration: 1});
}

function Abso_adsSrv(t, v) {
  var fsbc = new Ajax.Updater(v, '/absads/srv.php?ads=' + t + '&' + $('form-search').serialize(), {
      method: 'get',
      onComplete: function() {
        $(v).removeClassName('loading');
        alert($(v).evalScripts());
        pageTracker._trackPageview("/AdsSrvAjax" );
      },
      onLoading: function() {
        $(v).addClassName('loading');
      }
    }
  );
}
if (!window.Effect) var Effect = {};

Effect.ScrollTo = function(element) {
  var options = arguments[1] || { },
  scrollOffsets = document.viewport.getScrollOffsets(),
  elementOffsets = $(element).cumulativeOffset();

  if (options.offset) elementOffsets[1] += options.offset;

  return new Effect.Tween(null,
    scrollOffsets.top,
    elementOffsets[1],
    options,
    function(p){ scrollTo(scrollOffsets.left, p.round()) }
  );
};

function Abso_connect() {
  $('fbcx').value = 1;
  new Ajax.Request('/ajax.php?loginfb&no', {
    onSuccess: function(response) {
      // Note how we brace against null values;
      //alert(response.responseText);
      g = response.responseText.substring(0, 4);
      if (g == 'goto') {
        t = response.responseText.split(":");
        document.location.href = t[1];
      } else {
        $('div-facebook-connect').update(response.responseText);
        new Effect.Highlight('div-facebook-connect', {startcolor: '#ffff99', endcolor: '#ffffff' });
      }
    }
  });
}

function Abso_login() {
  new Ajax.Request('/ajax.php?logincheck&no', {
    method: 'post',
    parameters: $('form-login').serialize(true),
    onLoading: function() {
      $('login_loader').show();
    }, 
    onSuccess: function(response) {
      $('login_loader').hide();
      g = response.responseText.substring(0, 4);
      if (g == 'goto') {
        t = response.responseText.split(":");
        document.location.href = t[1];
      } else {
        $('passwd').value = '';
        $('login-message').update(response.responseText);
        new Effect.Highlight('login-message', {duration: 1, fps: 60, from:0.0, to:1.0, startcolor:'#ffff99', endcolor:'#ffffff'});
      }
    }
  });
}

function Abso_connectPart() {
  document.location.href = '/inscription-particulier';
}

function Abso_connectPro() {
  $('form-pro-reload').submit();
}

function Abso_country() {
  if($F('country') == 83) {
    $('pluscity').show();
  } else {
    $('pluscity').hide();
  }
}

//]]>
