
var parkings = new Array();
var map,centermarker,curcenter;
var maxdistance = 5;
var selattribute = '0';
var map_inited = false;
var bounds;
function init_map() {  
  if (GBrowserIsCompatible()) {
	jQuery('#searchform').hide();
	jQuery('#leftcontent').hide();
	jQuery('#results').show();
	jQuery('#results ul').html('');
	jQuery('#map').show();
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(37.4419, -122.1419), 13);
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
  }
  else { alert('Votre navigateur n\'est pas compatible avec les maps de google.'); }
}

function findparkings() {
var search_city = document.getElementById('ddlCity').value;
	geocoder = new GClientGeocoder();
	geocoder.getLatLng($('dest').value+', ' + search_city ,function(point) { 			
	if (point) {
		lat=point.lat();
		lon=point.lng();
	}
	else {
		lat=999;
		lon=999;
	}
	var x = new Ajax.Request('queryfast.php?city='+search_city+'&lat='+lat+'&lon='+lon+'&lan='+_lan+'&q='+escape($('dest').value)+'&date='+escape($('date').value)+'&distance='+maxdistance+'&attr='+selattribute+'&hstart='+$('hstart').value+'&mstart='+$('mstart').value,{ onSuccess	: function(r) {
		try {

			eval(r.responseText);
			$('searchform').enable();
			$('searchinprogress').hide();
		} catch(e) { 
			alert('Une erreur est survenue lors de la recherche. '+"\n\n"+e.message);$('searchform').enable();
			$('searchinprogress').hide();
		}
	}});


	});

	$('searchform').disable();
	$('searchinprogress').show();
}

// Simulates PHP's date function
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return(((this.getFullYear()%4==0)&&(this.getFullYear()%100!=0))||(this.getFullYear()%400==0))?'1':'0';},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+'00';},P:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+':'+(Math.abs(this.getTimezoneOffset()%60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()%60));},T:function(){var m=this.getMonth();this.setMonth(0);var result=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,'$1');this.setMonth(m);return result;},Z:function(){return-this.getTimezoneOffset()*60;},c:function(){return this.format("Y-m-d")+"T"+this.format("H:i:sP");},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};

function show_partner(name,address,icon) {

	var html = "<div style='margin:20px 0 20px 10px; padding:5px;'>";
	if(icon.length) { html += "<div style='float:left; margin: 0 5px 5px 0;'><img src='/fichiers/Partners/Icons/"+icon+"' /></div>"; }
	html += "<h4>"+name+"</h4>";
	if(address.length) { html += "<div>"+address+"</div>"; }
	html += "<div style='clear:both;'></div>";
	html += "</div>";
	

	jQuery("#results").prepend(html);
}


function loadPartner(q) {

	
	var date = new Date();
	date.setDate(date.getDate() + 1);
	date = date.format('Y-m-d');
	
	jQuery("#contentbox").fadeTo(1,0.2);
	jQuery("#home_news").fadeTo(1,0.2);
	var x = new Ajax.Request('/v2/queryfast.php?lan='+_lan+'&partner='+escape(q)+'&date='+date+'&distance='+maxdistance+'&attr='+selattribute,{ onSuccess	: function(r) {
		
		jQuery("#contentbox").fadeTo(1,1);
		jQuery("#home_news").fadeTo(1,1);
		try {
			eval(r.responseText);
			jQuery("#home_news").hide();
			if(jQuery('#searchform').length) { jQuery('#searchform').getInputs().attr("disabled",""); }
			jQuery('#searchinprogress').hide();
		} catch(e) { 
			alert('Une erreur est survenue lors de la recherche. '+"\n\n"+e.message);
			if(jQuery('#searchform').length) { jQuery('#searchform').getInputs().attr("disabled",""); }
			jQuery('#searchinprogress').hide();
		}
	}});

	if(jQuery('#searchform').length) { jQuery('#searchform').getInputs().attr("disabled","disabled"); }
	jQuery('#searchinprogress').show();
}

// 20x34
function createcentermarker(latt,longi,textval,icon) {
	curcenter = new GLatLng(latt,longi);
	map.setCenter(curcenter, 15);
	var blueIcon = new GIcon(G_DEFAULT_ICON);
	if (icon == '')
		blueIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
	else
	{
		blueIcon.iconSize = new GSize();
		blueIcon.image = "http://"+location.host+"/fichiers/Partners/Icons/" + icon;	
	}		
	markerOptions = { icon:blueIcon };
	centermarker = new GMarker(curcenter,markerOptions);
	map.addOverlay(centermarker);
	GEvent.addListener(centermarker, "click", function() {
        if (_lan=='en') centermarker.openInfoWindowHtml("<b>Your destination</b><br />"+textval);
		else centermarker.openInfoWindowHtml("<b>Votre destination</b><br />"+textval);
	});	
	if (_lan=='en') centermarker.openInfoWindowHtml("<b>Your destination</b><br />"+textval);
	else  centermarker.openInfoWindowHtml("<b>Votre destination</b><br />"+textval);
	map_inited = true;
}

function createparking(latt,longi,name,desc,attributes,idparking,distance,icon,iwidth,iheight,price,ispartner) {
	var cur = parkings.length;
	parkings[cur] = { 
		lat : latt,
		lng : longi,
		name : name,
		desc : desc,
		attributes : attributes,
		idparking : idparking,
		distance : distance,
		icon : icon,
		iwidth : iwidth,
		iheight : iheight,
		price : price,
		ispartner : ispartner
	}
	var myIcon = new GIcon(G_DEFAULT_ICON);
	if (icon=='') {
		myIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/red/marker"+(cur+1)+".png";
		parkings[cur].icon = "http://gmaps-samples.googlecode.com/svn/trunk/markers/red/marker"+(cur+1)+".png";
	}
	else myIcon.image = icon;
	myIcon.iconSize = new GSize(iwidth,iheight);
	markerOptions = { icon:myIcon };
	bounds.extend(new GLatLng(latt,longi));
	parkings[cur].glatlng = new GLatLng(latt,longi);
	parkings[cur].html="<b>"+name+"</b><br />"+desc+"<br /><div style='text-align:center;'>"+attributes+'<br />';
	if (ispartner) {
		parkings[cur].html+='<b>'+price+'</b><br />';
		parkings[cur].html+="<a href='javascript:;' onclick=\"Lightview.show({ href: 'parking.php?lan="+_lan+"&a=info&id="+idparking+"&date='+jQuery('#date').val()+'&h='+jQuery('#hstart').val()+'&m='+jQuery('#mstart').val(), rel: 'iframe', options: { width: 500, height: 500 }});\">"+((_lan!='en') ? 'Détails' : 'Details') + "</a> &mdash; <a href=\"javascript:;\" onclick=\"reserver("+idparking+",jQuery('#date').val());\">"+((_lan=='en')? 'Reserve!' : 'Réserver!')+"</a>";
	}
	parkings[cur].html+="</div>";
	if (!ispartner) {
		if (_lan=='fr') parkings[cur].html+="<p style='width:300px;'>Désolé,<br /><br />MaPlace ne détient pas encore de partenariat avec ce stationnement, c'est pourquoi il nous est impossible de vous offrir la réservation à cet endroit. Nous vous invitons à revenir souvent afin de vérifier les nouveaux partenaires dans votre région d'intérêt.<br /><br />Merci et bonne route.</p>"; 	
		else parkings[cur].html+="<p style='width:300px;'>Sorry,<br /><br />MaPlace does not have a partnership agreement with this parking yet, this is why it's impossible for us to offer reservation at this place. We invite you to come back frequently in order to check the new partners within your area of interest.<br /><br />Thank you and have a nice trip.</p>"
	}
	parkings[cur].gmarker = new GMarker(parkings[cur].glatlng,markerOptions);
	map.addOverlay(parkings[cur].gmarker);
	GEvent.addListener(parkings[cur].gmarker, "click", function() {
        parkings[cur].gmarker.openInfoWindowHtml(parkings[cur].html);
		Lightview.updateViews();
	});
	
	GEvent.addListener(parkings[cur].gmarker, "infowindowopen", function() {
		Lightview.updateViews();
	});																		 
	var leli = '<li style="background-image:url(' + parkings[cur].icon + ');"><span class="opt">';
	if (ispartner) leli += '<a href="javascript:;" onclick=\'Lightview.show({ href: "parking.php?lan='+_lan+'&a=info&id='+idparking+'&date="+jQuery("#date").val()+"&h="+jQuery("#hstart").val()+"&m="+jQuery("#mstart").val(), rel: "iframe", options: { width: 500, height: 500 }});\'>'+((_lan!='en') ? 'Détails' : 'Details') +'</a>';
	leli += '</span><a href="javascript:;" onclick="parkings['+cur+'].gmarker.openInfoWindowHtml(parkings['+cur+'].html);"><b>'+name+'</b></a> ('+((_lan!='en') ? '&Agrave;' : 'At') +' '+distance+' km)<br /><i>'+desc+'</i><span class="clear"></span></li>';																	 
	jQuery('#results ul').html(jQuery('#results ul').html()+leli);
}

function zoomAllParkings() {
	map.setZoom(map.getBoundsZoomLevel(bounds));
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
    map.setCenter(new GLatLng(clat,clng));	
}

function clearmarkers() {
	try {
		map.removeOverlay(centermarker);
	}
	catch(e) { init_map(); }
	try {
		for(var x=0;x<=parkings.length;x++) map.removeOverlay(parkings[x].gmarker);		
	}
	catch(e) { }
	parkings = new Array();
	bounds = new GLatLngBounds();
}

function reserver(idp,datereserv) {
	Lightview.show({ href: 'reservation.php?lan='+_lan+'&id='+idp+'&date='+datereserv+'&hstart='+jQuery('#hstart').val()+'&mstart='+jQuery('#mstart').val(), rel: 'iframe', options: { width: 750, height: 300 }});
}

function inscription(idp,datereserv,idslot) {
	Lightview.show({ href: 'inscription.php?id='+idp+'&date='+datereserv+'&slot='+idslot, rel: 'iframe', title: 'Inscription MaPlace.ca',options: { width: 500, height: 500 }});
}

function init_reservation(q) {
	Lightview.show({ href: 'https://'+location.host+'/v2/init_reservation.php?'+q, rel: 'iframe', title: ((_lan=='fr') ? '<div style="float:left; line-height:19px; height:19px; vertical-align:middle;">Réservation MaPlace.ca</div>' + '<div style="float:right; line-height:19px; height:19px; vertical-align:middle;"><img src="images/https_icon.gif" alt="https_icon.gif" />Cette page est sécurisée https.</div>' : '<div style="float:left; line-height:19px; height:19px; vertical-align:middle;">MaPlace.ca : Reservation infos.</div>' + '<div style="float:right; line-height:19px; height:19px; vertical-align:middle;"><img src="images/https_icon.gif" alt="https_icon.gif" />This page is secure https.</div>'),options: { width: 500, height: 400 }});
}

function set_options(dist,attr) {
	maxdistance = dist;
	selattribute  = attr;
	Lightview.hide();
	if (map_inited) {
		$('searchform').enable();
		findparkings();
	}
}

function saveprefs() {
	jQuery.ajax({url:'/v2/options.php?'+jQuery('#soption').serialize()});
}