// Variables globales
var aGmap;
var aGmap_zoom_min = 1;
var aGmap_zoom_max_view = 9;
var pointIcon;
var pointIconBold;
var pointIconUltraBold;
var locIcon;
var excIcon;
var tooltip;
var showSVC = false;
var geocoder;
var tabAccuracy = new Array(
    2,
    4,
    6,
    10,
    12,
    13,
    16,
    16,
    17,
    17
);

continents = {
    'w/0': {
	'lat': 46.9202,
	'lng': 10.8984,
	'zoom': 3
    },
    'w/1': {
	'lat': 50.2893,
	'lng': -99.1406,
	'zoom': 2
    },
    'w/2': {
	'lat': 20.5505,
	'lng': -75.3222,
	'zoom': 4
    },
    'w/3': {
	'lat': 2.4601,
	'lng': 15.8203,
	'zoom': 2
    },
    'w/4': {
	'lat': -27.8390,
	'lng': 145.0195,
	'zoom': 3
    },
    'w/5': {
	'lat': -18.3128,
	'lng': -70.3125,
	'zoom': 2
    },
    'w/6': {
	'lat': 1.4061,
	'lng': 73.3007,
	'zoom': 2
    },
    'w/7': {
	'lat': 32.9902,
	'lng': 33.0468,
	'zoom': 3
    },
    'w/8': {
	'lat': 8.9284,
	'lng': 110.0390,
	'zoom': 3
    },
    'w/9': {
	'lat': 33.7243,
	'lng': 97.0312,
	'zoom': 2
    },
    'w/10': {
	'lat': 42.5530,
	'lng': 14.0625,
	'zoom': 1
    },
    'w/11': {
	'lat': 39.5040,
	'lng': 43.1542,
	'zoom': 4
    }
}


// Chargement de la carte
googleLoad.include('aGmap');
google.load('maps', '2.184');//2.184

// Initialisation une fois la carte prête
google.setOnLoadCallback(googleInit);

// Initialisation
function aGmapInit()
{
    initIcons();

    // Création de la carte
    aGmap = new google.maps.Map2($('aGmap'), {
	draggableCursor: 'pointer'
    });

    geocoder = new GClientGeocoder();

    // Positionnement initial de la carte
    if ('en' == 'en') {
	var point = new google.maps.LatLng(20, 280);
    } else {
	var point = new google.maps.LatLng(20, 5);
    }
    aGmap.setCenter(point, aGmap_zoom_min);

    // Taille des controles à afficher
    if (aGmap_size == 'small' || aGmap_size == 'ultrasmall') {
	aGmap.addControl(new GSmallMapControl());
    } else {
	aGmap.addControl(new GLargeMapControl());
    }

    // Type de carte
    aGmap.setMapType(aGmap_type);

    // Permettre le changement de type de carte
    aGmap.addControl(new GMenuMapTypeControl());
    aGmap.addMapType(G_PHYSICAL_MAP);

    // Affichage de l'échelle en bas à droite de la carte
    aGmap.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(5, 25)));

    // Préparation des tooltips
    tooltip = new Element('div', {
	'id' : 'tooltip',
	'style': 'position:relative;z-index:1;background-color:#FFFFFF;border:1px solid #000000;width:100px;font-size:10px;visibility:hidden;',
	'class': 'centrer'
    });
    tooltip.injectInside($('aGmap'));

    // Fonction à appeler en fonction du mode
    switch (aGmap_mode) {
	case 'search':
	    aGmapSearch();
	    break;
	case 'results':
	    aGmapResults();
	    break;
	case 'admin':
	    aGmapAdmin();
	    break;
	case 'view':
	    aGmapView();
	    break;
    }
}

function getLatLng() {
    var bounds = aGmap.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();
    var tabLatLng = new Array();
    tabLatLng.push(southWest.lat());
    tabLatLng.push(southWest.lat() + latSpan);
    tabLatLng.push(southWest.lng());
    tabLatLng.push(southWest.lng() + lngSpan);
    tabLatLng.push(aGmap.getZoom());

    /*if (tabLatLng[3] < tabLatLng[2]) {
	p('Longitude inversion !');
	var tmpLng = tabLatLng[2];
	tabLatLng[2] = tabLatLng[3];
	tabLatLng[3] = tmpLng;
    }*/

    return tabLatLng;
}

function getIcon(icon)
{
    switch (icon) {
	case 'pointIcon':
	    return pointIcon;
	    break;
	case 'pointIconBold':
	    return pointIconBold;
	    break;
	case 'pointIconUltraBold':
	    return pointIconUltraBold;
	    break;
	case 'excIcon':
	    return excIcon;
	    break;
	case 'locIcon':
	default:
	    return locIcon;
	    break;
    }
}

function initIcons()
{
    pointIcon = new GIcon(G_DEFAULT_ICON);
    pointIcon.image = baseUrl + '/images/gmap_light.png';
    pointIcon.iconSize = new GSize(3,3);
    pointIcon.shadowSize = new GSize(0,0);
    pointIcon.iconAnchor = new GPoint(0,0);
    
    pointIconBold = new GIcon(G_DEFAULT_ICON);
    pointIconBold.image = baseUrl + '/images/gmap_bold.png';
    pointIconBold.iconSize = new GSize(6,6);
    pointIconBold.shadowSize = new GSize(0,0);
    pointIconBold.iconAnchor = new GPoint(0,0);
    
    pointIconUltraBold = new GIcon(G_DEFAULT_ICON);
    pointIconUltraBold.image = baseUrl + '/images/gmap_ultrabold.png';
    pointIconUltraBold.iconSize = new GSize(8,8);
    pointIconUltraBold.shadowSize = new GSize(0,0);
    pointIconUltraBold.iconAnchor = new GPoint(0,0);
    
    locIcon = new GIcon(G_DEFAULT_ICON);
    locIcon.image = baseUrl + '/images/gmap_loc.png';
    locIcon.iconSize = new GSize(14,15);
    locIcon.shadowSize = new GSize(0,0);
    locIcon.iconAnchor = new GPoint(7,15);
    
    excIcon = new GIcon(G_DEFAULT_ICON);
    excIcon.image = baseUrl + '/images/gmap_loc.png';
    excIcon.iconSize = new GSize(14,15);
    excIcon.shadowSize = new GSize(0,0);
    excIcon.iconAnchor = new GPoint(7,15);
}

function posFromAddress(address, newMarker)
{
    if ($chk($('worldregion')) && $('worldregion').get('value') && $chk($('country')) && !$('country').get('value')) {
	posFromContinent();
    } else {
	address = address.replace(/\((.*)\)/g, '');
	if (aGmap_mode != 'admin' && $chk($('country'))) {
	    address += $('country').options[$('country').selectedIndex].text.replace(/\((.*)\)/g, '');
	}
	geocoder.getLocations(address, function(retdata)
	{
	    if (retdata.Status.code == 200) {
		aGmap.doMove = false;
		var place = retdata.Placemark[0];
		aGmap.setCenter(new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]), tabAccuracy[place.AddressDetails.Accuracy]);
		aGmap.doMove = true;
		if (newMarker) {
		    setMarker();
		}
	    } else {
		divAlert("We weren't able to locate your address. You can move the 'home' cursor manually on the map");
	    }
	});
    }
}

function posFromContinent()
{
    if ($chk($('worldregion')) && $('worldregion').get('value')) {
	var continent = $('worldregion').get('value');
	aGmap.setCenter(new GLatLng(continents[continent].lat, continents[continent].lng));
	aGmap.setZoom(continents[continent].zoom);
    }
}

function showTooltip(marker, nb) {
    nb = (nb <= 100) ? nb : '100+';
    tooltip.innerHTML = nb + ' ads';
    var point = aGmap.getCurrentMapType().getProjection().fromLatLngToPixel(aGmap.getBounds().getSouthWest(), aGmap.getZoom());
    var offset = aGmap.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(), aGmap.getZoom());
    var anchor = marker.getIcon().iconAnchor;
    var width = marker.getIcon().iconSize.width;
    var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y + 5));
    pos.apply(tooltip);
    tooltip.setStyle('visibility', 'visible');
}

function infoBulle(gmark, marker_infos) {
    GEvent.addListener(gmark, 'click', function() {
        $clear(timer);
	requestBulle(gmark, marker_infos);
    });
    GEvent.addListener(gmark, 'mouseover', function() {
        $clear(timer);
	var delayedFunction = function() {requestBulle(gmark, marker_infos)};
	timer = delayedFunction.delay(1000);
    });
    GEvent.addListener(gmark, 'mouseout', function() {
	$clear(timer);
    });
}

function requestBulle(gmark, marker_infos) {
    coordsBeforeInfoWindow = aGmap.getBounds().getCenter();
    var jSonRequest = new Request.JSON({
	url: baseUrl + '/ajax/get_aGmap_infoBulle.php',
	onComplete: function(retdata) {
	    iW++;
	    aGmap.doMove = false;
	    gmark.openInfoWindowHtml(retdata);
	}
    }).post({'rep': marker_infos.rep, 'id': marker_infos.id});
    if (!gmark.iW) {
	gmark.iW = true;
	GEvent.addListener(gmark, 'infowindowclose', function() {
	    iW--;
	    aGmap.setCenter(coordsBeforeInfoWindow);
	    if (!iW) {
		aGmap.doMove = true;
	    }
	});
    }
}
// Variables globales
var timer;
var coordsBeforeInfoWindow;
var iW = 0;
var queries = 0;
var changedFields = new Array();

//Initialisation du mode recherche
function aGmapSearch()
{
    // On ajoute les évènements zoom et déplacement
    aGmap.doMove = true;
    GEvent.addListener(aGmap, 'moveend', function(oldZoom, newZoom) {
	if (aGmap.doMove) {
	    showSVC = true;
	    aGmapUpdateResults();
	}
    });

    // Et on lance la mise à jour de la carte
    if ($chk(mod)) {
	aGmapUpdateResults(null, 1);
    } else {
	aGmapUpdateResults(null, null, null, 1);
    }
}

// Ajoute une liste de marqueurs à la carte et la positionne au plus près
function aGmapDisplayMarkers(tab, centerBounds)
{
    var markers = tab.markers;
    var icon;
    var gmark;

    var latLngMinMax = getLatLng();
    var latMin = latLngMinMax[0];
    var latMax = latLngMinMax[1];
    var lngMin = latLngMinMax[2];
    var lngMax = latLngMinMax[3];
    var zoom = (centerBounds && tab.phpZoom) ? tab.phpZoom : latLngMinMax[4];

    aGmap.clearOverlays();

    markers.each(function(marker)
    {
	icon = getIcon(marker.icon);
	var point = new GLatLng(marker.lat, marker.lng);
	var gmark = new GMarker(point, { icon: icon });
	if (zoom > aGmap_zoom_min) {
	    infoBulle(gmark, marker);
	} else {
	    GEvent.addListener(gmark, 'mouseover', function() {
		showTooltip(gmark, marker.nb);
	    });        
	    GEvent.addListener(gmark, 'mouseout', function() {
		tooltip.setStyle('visibility', 'hidden');
	    });
	}
	gmark.iW = false;
	aGmap.addOverlay(gmark);
	if (centerBounds) {
	    aGmap.bounds.extend(point);
	}
    });

    if (centerBounds) {
	aGmap.doMove = false;
	aGmap.setCenter(aGmap.bounds.getCenter());
	//var newZoom = aGmap.getBoundsZoomLevel(aGmap.bounds);
	var newZoom = zoom;
	(newZoom >= aGmap_zoom_min) ? aGmap.setZoom(newZoom) : aGmap.setZoom(aGmap_zoom_min);
	aGmap.doMove = true;
    }
}

function aGmapUpdateResults(changed, centerBounds, address, cache)
{
    changedFields.combine([
	$('fdatedep'),
	$('fdatearr'),
	$('envsea_dist'),
	$('envmountain_dist'),
	$('envcity_dist')
    ]);

    if (changed) {
	var toInclude = false;
	switch (changed.get('tag')) {
	    case 'input':
		switch (changed.type) {
		    case 'checkbox':
			if (changed.checked) {
			    toInclude = true;
			}
			break;
		    case 'text':
		    case 'hidden':
			if (changed.value && changed.value != defaultText) {
			    toInclude = true;
			}
			break;
		    case 'radio':
			if (changed.checked) {
			    toInclude = true;
			}
			break;
		}
		break;
	    case 'select':
		if (changed.value || changed.getAttribute('multiple') != null) {
		    toInclude = true;
		}
		break;
	}

	if (changed.getParent().get('id') == '5levels_selector') {
	    toInclude = false;
	}

	if (toInclude && changed.get('name') != 'ski_resort') {
	    changedFields.include(changed);
	} else if (toInclude && changed.get('name') == 'ski_resort') {
	    return false;
	} else {
	    changedFields.erase(changed);
	}
    }

    var tempForm = new Element('form');
    changedFields.each(function(el)
    {
	if (el) {
	    if (el.hasAttribute && el.hasAttribute("multiple")) {
		var cloneEl = el.clone(true);
		var values = new Array();
		cloneEl.getChildren().each(function(subel) { 
		    values.push(subel.value);
		});
		var elHTML = '';
		values.each(function(val) {
		    elHTML += '<option value="' + val + '" selected="selected">';
		});
		$empty(cloneEl);
		cloneEl.set('html', elHTML);
		tempForm.adopt(cloneEl.clone(true));
	    } else {
		tempForm.adopt(el.clone(true));
		if ((tempForm.getChildren('input[type=checkbox]').length) && (Browser.Engine.trident4)) {
		    if (el.checked == true) {
			var elclone = tempForm.getChildren('input[type=checkbox]').getLast();
			elclone.set('checked', true);
		    }
		}
	    }
	}
    });

    if ($chk($('5levels_selector'))) {
	tempForm.adopt($('5levels_selector').clone(true));
    }

    if ($chk($('places-selection'))) {
	tempForm.adopt($('places-selection').clone(true));
    }

    var tabLatLng = getLatLng();
    var mapLatLng = new Element('input', {
	'type': 'hidden',
	'id': 'mapLatLng',
	'name': 'mapLatLng',
	'value' : tabLatLng[0] + ',' + tabLatLng[1] + ',' + tabLatLng[2] + ',' + tabLatLng[3] + ',' + aGmap.getZoom()
    }).injectInside(tempForm);

    if (!queries && $chk($('aGmap_loader'))) {
	$('aGmap_loader').loader = new Loader($('aGmap_loader'));
    }
    queries++;
    if (centerBounds) {
	aGmap.bounds = null;
	aGmap.bounds = new GLatLngBounds();
	var url = baseUrl + '/ajax/get_aGmap_markers.php?cb=1&rep=' + aGmap_rep + '&s=' + aGmap_size;
    } else {
	var url = baseUrl + '/ajax/get_aGmap_markers.php?rep=' + aGmap_rep;
    }
    if (cache) {
	url += '&cache=1';
    }
    url += '&l=en';

    if($chk($('searchFormResults')) && showSVC){
	if ($('searchFormResults').getStyle('display') == 'none') {
	    $('searchFormResults').setStyle('display', 'block');
	}
    }

    tempForm.set('send', {
	url: url,
	method: 'post',
	onComplete: function(retdata)
	{
	    queries--;
	    if (!queries && $chk($('aGmap_loader'))) {
		$('aGmap_loader').loader.destroy();
		$('aGmap_loader').loader = null;
	    }
	    var tab = JSON.decode(retdata);
	    if (tab && tab.nbResults > 0) {
		aGmapDisplayMarkers(tab, centerBounds);
	    } else {
		aGmap.clearOverlays();
		if (address) {
		    posFromAddress(address);
		} else {
		    //aGmap.doMove = false;
		    //aGmap.setZoom(aGmap_zoom_min);
		    aGmap.doMove = true;
		}
	    }
	    displayResults(tab);
	}
    });
    
    tempForm.send();

    tempForm.dispose();
    mapLatLng.dispose();
}


function displayResults(tab)
{
    var tabLatLng = getLatLng();
    var more = (loadedModule == 'biblio' || loadedModule == 'shareresults') ? "Zoom on the map to view more." : "Zoom on the map to view more properties.";
    if (aGmap_size == 'small') {
	$('aGmap_nbResults').set('text', limitResults(tab.nbResults, 'short'));
	 if (tabLatLng[4] <= 1) {
	    $('svc').set('html', more);
	} else if (tab.nbMarkersAll && tab.nbMarkers < tab.nbMarkersAll) {
	    $('svc').set('html', more);
	} else {
	    $('svc').set('html', '');
	}
    } else {
	$('aGmap_nbResults').set('text', limitResults(tab.nbResults, 'long'));

	$('latMin').set('value', '');
	$('latMax').set('value', '');
	$('lngMin').set('value', '');
	$('lngMax').set('value', '');

	if ($chk($('SVCMap'))) {
	    if (tabLatLng[4] <= 1) {
		$('SVCMap').set('html', more);
	    } else if (tab.nbMarkersAll) {
		var nb = tab.nbMarkersAll;
		if (nb == 1) {
		    if (loadedModule == 'biblio' || loadedModule == 'shareresults') {
			$('SVCMap').set('html', "In the perimeter of the map:" + nb + " result found.");
		    } else {
			$('SVCMap').set('html', "In the perimeter of the map:" + nb + " ad found.");
		    }
		} else {
		    if (loadedModule == 'biblio' || loadedModule == 'shareresults') {
			$('SVCMap').set('html', "In the perimeter of the map:" + limitResults(nb) + " results found.");
		    } else {
			$('SVCMap').set('html', "In the perimeter of the map:" + limitResults(nb) + " ads found.");
		    }
		}
		$('SVCMap').set('html', $('SVCMap').get('html') + '<br /><input type="submit" value="View" name="submit" class="gmapSubmit" />');
		if (tab.nbMarkers < tab.nbMarkersAll) {
		    if (loadedModule == 'biblio' || loadedModule == 'shareresults') {
			$('SVCMap').set('html', $('SVCMap').get('html') + "<br /><br /><span class=\"tips\">Zoom on view more.</span>");
		    } else {
			$('SVCMap').set('html', $('SVCMap').get('html') + "<br /><br /><span class=\"tips\">All are not displayed, zoom to view more.</span>");
		    }
		}
		$('latMin').set('value', tabLatLng[0]);
		$('latMax').set('value', tabLatLng[1]);
		$('lngMin').set('value', tabLatLng[2]);
		$('lngMax').set('value', tabLatLng[3]);
	    } else {
		$('SVCMap').set('html', "No results found in the perimeter of the map.");
	    }
	} else if (aGmap_size == 'large') {
	    $('latMin').set('value', tabLatLng[0]);
	    $('latMax').set('value', tabLatLng[1]);
	    $('lngMin').set('value', tabLatLng[2]);
	    $('lngMax').set('value', tabLatLng[3]);
	} else {
		if ((tab.nbMarkers && tab.nbMarkers < tab.nbMarkersAll)) {
		    $('svc').set('text', more);
		} else {
		    $('svc').set('html', "&nbsp;");
		}
	}
	$$('[class=gmapSubmit]').removeEvents('click');
	$$('[class=gmapSubmit]').addEvent('click', function (event) {
	    this.inject($('searchform'));
	    this.setStyle('display', 'none');
	});
    }
}

/* Pushup
 * Copyright (c) 2008 Nick Stakenburg (www.nickstakenburg.com)
 *
 * License: MIT-style license.
 * Website: http://www.pushuptheweb.com
 *
 */

var Pushup = {
  Version: '1.0.3',
  options: {
    appearDelay: .5,
    fadeDelay: 6,
    images: '/images-pushup/',
    message: "An important update is available for your browser",
    reminder: {
      hours: 6,
      message: "Remind me in #{hours}"
    },
    skip: false
  },
  updateLinks: {
    IE: 'http://www.microsoft.com/windows/downloads/ie/',
    Firefox: 'http://www.getfirefox.com',
    Safari: 'http://www.apple.com/safari/download/',
    Opera: 'http://www.opera.com/download/'
  },
  Browser: {
    IE: !!(window.attachEvent &&
      navigator.userAgent.indexOf('Opera') === -1),
    Firefox: navigator.userAgent.indexOf('Firefox') > -1,
    Safari: navigator.userAgent.indexOf('AppleWebKit/') > -1 &&
      /Apple/.test(navigator.vendor),
    Opera: navigator.userAgent.indexOf('Opera') > -1
  }
};

Pushup.conditions = {
  IE: (function(agent) {
    var version = /MSIE ([\d.]+)/.exec(agent);
    return version && parseFloat(version[1]) < 7;
  })(navigator.userAgent),
  Firefox: Pushup.Browser.Firefox &&
    parseFloat(navigator.userAgent.match(/Firefox[\/\s](\d+)/)[1]) < 3,
  Safari: Pushup.Browser.Safari &&
    parseFloat(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1]) < 500,
  Opera: Pushup.Browser.Opera && (!window.opera.version ||
    parseFloat(window.opera.version()) < 9.5)
};

(function() {
// find current browser and check if it needs an update
for (var browser in Pushup.Browser)
  if (Pushup.Browser[browser]) Pushup._browserUsed = browser;
Pushup._updateBrowser = Pushup.conditions[Pushup._browserUsed] &&
  Pushup._browserUsed;

// stop if no update is required and we want to skip build
if (!Pushup._updateBrowser && Pushup.options.skip) return;

function Extend(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
}

Extend(Pushup, {
  start: function() {
    // get the image directory
    if (/^(https?:\/\/|\/)/.test(this.options.images))
      this.images = this.options.images;
    else {
      var srcMatch = /pushup(?:-[\w\d.]+)?\.js(.*)/,
       scripts = document.getElementsByTagName('script');
      for (var i = 0, l = scripts.length; i < l; i++) {
        var s = scripts[i];
        if (s.src && s.src.match(srcMatch))
          this.images = s.src.replace(srcMatch, '') + this.options.images;
      }
    }
    if (Pushup._updateBrowser) this.show();
  },

  build: function() {
    this.pushup = document.createElement('div');
    Opacity.set(this.pushup, 0);
    this.pushup.id = 'pushup';

    this.messageLink = this.pushup.appendChild(document.createElement('a'));
    this.messageLink.className = 'pushup_messageLink';
    this.messageLink.target = '_blank';

    this.messageLink.appendChild(this.icon = document.createElement('div'));
    this.icon.className = 'pushup_icon';

    this.messageLink.appendChild(this.message = document.createElement('span'));
    this.message.className = 'pushup_message';
    this.message.innerHTML = this.options.message;

    // reminder message if cookies are enabled
    var hours = this.options.reminder.hours;
    if (hours && Pushup.cookiesEnabled) {
      this.pushup.appendChild(this.reminder = document.createElement('a'));
      this.reminder.href = '#';
      this.reminder.className = 'pushup_reminder';
      this.pushup.className = 'withReminder';
      //var H = hours + " hour" + (hours > 1 ? 's' : ''),
      var H = hours + " " + ((hours == 1) ? "hour" : "hours");
       message = this.options.reminder.message.replace('#{hours}', H);
      this.reminder.innerHTML = message;
    }

    // Older Opera doesn't handle float correctly
    if (Pushup.Browser.Opera &&
       (!window.opera.version || parseFloat(window.opera.version()) < 9.25)) {
      this.messageLink.style.cssFloat = 'none';
      this.reminder.style.cssFloat = 'none';
    }

    Pushup.setBrowser(Pushup._updateBrowser);
    document.body.appendChild(this.pushup);
    Pushup.addEvents();
  },

  addEvents: function() {
    if (this.reminder) {
      Event.add(this.reminder, 'click', function(event) {
        Event.stop(event);
        Pushup.setReminder(Pushup.options.reminder.hours);
        Pushup.fade();
      });
    }
    Event.add(this.pushup, 'mouseover', Pushup.clearFade);
    Event.add(this.pushup, 'mouseout', function() {
      Pushup.fade({ delay: Pushup.options.fadeDelay })
    });
  },

  setBrowser: function(browser) {
    browser = browser || 'IE';
    setPngBackground(this.icon, this.images + browser.toLowerCase() + '.png');
    this.messageLink.href = this.updateLinks[browser];
  },

  show: function() {
    // default to IE if no browser was detected
    var browser = typeof arguments[0] == 'string' ?
      arguments[0] : Pushup._browserUsed || 'IE',
     options = arguments[browser ? 1 : 0] || {};

    if (options.resetReminder) Pushup.resetReminder();

    // show if not blocked by cookie
    if (!options.ignoreReminder && Pushup.cookiesEnabled &&
      Cookie.get('_pushupBlocked')) return;

    if (!Pushup.pushup) Pushup.build();
    Opacity.set(Pushup.pushup, 0);
    Pushup.pushup.style.display = 'block';
    if (browser) Pushup.setBrowser(browser);
    this.appear({ fadeAfter: true, delay: Pushup.options.appearDelay });
  },

  appear: function(delay) {
    Pushup.clearFade();
    var options = arguments[0] || {};
    return window.setTimeout(function() {
      Appear(Pushup.pushup, { afterFinish: function() {
        if (options.fadeAfter)
          Pushup.fade({ delay: Pushup.options.fadeDelay });
      }});
    }, (options.delay || 0.01) * 1000);
  },

  clearFade: function() {
    if (Pushup._fadeTimer) {
      window.clearTimeout(Pushup._fadeTimer);
      Pushup._fadeTimer = null;
    }
  },

  fade: function() {
    var options = arguments[0] || {};
    Pushup._fadeTimer = window.setTimeout(function() {
      Fade(Pushup.pushup);
    }, (options.delay || 0.01) * 1000);
  },

  setReminder: function(hours) {
    Cookie.set('_pushupBlocked', 'blocked', { duration: 1 / 24 * hours })
  },

  resetReminder: function() { Cookie.remove('_pushupBlocked') }
});

// Opacity adapted from the Prototype JavaScript framework
// http://www.prototypejs.org
var Opacity = {
  set: function(element, value) {
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;
  },

  get:  function(element) {
    var opacity = element.style.opacity;
    return opacity ? parseFloat(opacity) : 1.0;
  }
};

if (Pushup.Browser.IE) {
  Opacity.get = function(element) {
    var opacity = element.style.opacity;
    if (!opacity && element.currentStyle) opacity = element.currentStyle[opacity];

    if (opacity = (element.style.filter || '').match(/alpha\(opacity=(.*)\)/))
      if (opacity[1]) return parseFloat(opacity[1]) / 100;
    return 1.0;
  };

  Opacity.set = function(element, value) {
    function stripAlpha(filter) {
      return filter.replace(/alpha\([^\)]*\)/gi,'')
    }
    var currentStyle = element.currentStyle;
    if ((currentStyle && !currentStyle.hasLayout) ||
      (!currentStyle && element.style.zoom == 'normal'))
        element.style.zoom = 1;
    var filter = element.style.filter,
     style = element.style;
    if (value == 1 || value === '') (filter = stripAlpha(filter)) ?
      style.filter = filter : style.filter = '';
    else style.filter = stripAlpha(filter) +
      'alpha(opacity=' + (value * 100) + ')';
  };
}

function Appear(element) {
  var current = Opacity.get(element),
   options = arguments[1] || {};
  if (element.style.display != 'block')
    element.style.display = 'block';
  if (current < 1) {
    setTimeout(function() {
      Opacity.set(element, current += 0.05);
      Appear(element, options);
    }, 0.01);
  }
  else {
    if (Pushup.Browser.IE && element.style.filter)
      element.style.removeAttribute('filter');
    if (options.afterFinish) options.afterFinish.call();
  }
}

function Fade(element) {
  var current = Opacity.get(element),
   options = arguments[1] || {};
  if (current > 0) {
    setTimeout(function() {
      Opacity.set(element, current -= 0.05);
      Fade(element, options);
    }, 0.01);
  }
  else {
    element.style.display = 'none';
    if (options.afterFinish) options.afterFinish.call();
  }
}

function setPngBackground(element, url) {
  var options = Extend({
    align: 'top left',
    repeat: 'no-repeat',
    sizingMethod: 'crop',
    backgroundColor: ''
  }, arguments[2] || {});

  Extend(element.style, arguments.callee.IEBelow7 ? {
    filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' +
      url + '\'\', sizingMethod=\'' + options.sizingMethod + '\')'
  } : {
    background: options.backgroundColor + ' url(' + url + ') ' +
      options.align + ' ' + options.repeat
  });
}
setPngBackground.IEBelow7 = Pushup.Browser.IE &&
  parseFloat(/MSIE ([\d.]+)/.exec(navigator.userAgent)[1]) < 7;

// Based on the work of Peter-Paul Koch - http://www.quirksmode.org
var Cookie = {
  set: function(name, value) {
    var expires = '', options = arguments[2] || {};
    if (options.duration) {
      var date = new Date();
      date.setTime(date.getTime() + options.duration * 1000 * 60 * 60 * 24);
      value += '; expires=' + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
  },

  remove: function(name) { this.set(name, '', -1) },

  get: function(name) {
    var cookies = document.cookie.split(';'), nameEQ = name + "=";
    for (var i = 0, l = cookies.length; i < l; i++) {
      var c = cookies[i];
      while (c.charAt(0) == ' ')
        c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0)
        return c.substring(nameEQ.length, c.length);
    }
    return null;
  }
};

// check if cookies are enabled
Pushup.cookiesEnabled = (function(test) {
  if (Cookie.get(test)) return true;
  Cookie.set(test, 'test', { duration: 15 });
  return Cookie.get(test);
})('_pushupCookiesEnabled');

var Event = {
  add: function(obj, type, fn) {
    if (obj.attachEvent) {
      obj['e' + type + fn] = fn;
      obj[type + fn] = function(){ obj['e' + type +fn](window.event) };
      obj.attachEvent('on' + type, obj[type + fn]);
    }
    else obj.addEventListener(type, fn, false);
  },

  stop: function(event) {
    if (Pushup.Browser.IE) {
      event.cancelBubble = true;
      event.returnValue = false;
    }
    else {
      event.preventDefault();
      event.stopPropagation();
    }
  }
};

Event.add(window, 'load', function() { Pushup.start() });
})();
