$(document).ready(function() {
	var gMap = null;
	var gMarkers = [];
	var gBounds = null;
	
	var sMapLocation = '';

	var fetchInterval = 0;

	var nAnnonceID = 0;
	var nOffset = 0;

	var nMarqueID = 0;
	var nDetaillantID = 0;
	var nBanniereID = 0;

	var ajaxSrc = document.domain;

	// gMap
	function initialize() {
		var latlng = new google.maps.LatLng(45.532417, -73.584564);
		var myOptions = {
			zoom: 8,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		gMap = new google.maps.Map(document.getElementById('map'), myOptions);
	}

	function addMarker(location, title) {
		var marker = new google.maps.Marker({
			position: location,
			map: gMap,
			title: title
		});
		gMarkers.push(marker);
	}

	// Removes the overlays from the map, but keeps them in the array
	function clearOverlays() {
		if (gMarkers) {
			for (i in gMarkers) {
				gMarkers[i].setMap(null);
			}
		}
	}

	// Shows any overlays currently in the array
	function showOverlays() {
		if (gMarkers) {
			for (i in gMarkers) {
				gMarkers[i].setMap(gMap);
			}
		}
	}

	// Deletes all markers in the array by removing references to them
	function deleteOverlays() {
		if (gMarkers) {
			for (i in gMarkers) {
				gMarkers[i].setMap(null);
			}
			gMarkers.length = 0;
		}
	}
	
	function nl2br (str, is_xhtml) {
		var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
		return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
	}

	function fetchAnnonces() {
		$('a', '#mod-annonces').html('');
		$.ajax({
			url: 'ajax/annonces.php',
			data: {
					offset: nOffset
			},
			dataType: 'json',
			success: function(data) {
				if (data != null && data.Statut == '0' && data.Annonces != null) {
					if (data.Annonces.length > 0) {
						var element = $('li:first-child', '#mod-annonces .annonces');
						$.each(data.Annonces, function(i, item) {
							element.find('p').stop(false, true);
							var imgLogo = '';
							if (item.LogoMarque != null) {
								imgLogo = '<img alt="" title="" src="http://passionvelo.ca/media/image/' + item.LogoMarque + '" />';
							}
							element.find('a').html(	item.Marque + '<br />' +
													item.Modele + '<br />' +
													'$' + item.prix + '<br />' + imgLogo);
							element.data('id', item.id);
							element.find('p').fadeIn('slow');
							element = element.next();
						});
					} else {
						clearInterval(fetchInterval);
						$('#mod-annonces').slideUp('fast');
					}
				} else {
					// Panic (or retry a few times and then abandon if it keeps failing)
				}
			},
			error: function(request, status, errorThrown) {
				// Panic (really)
				//alert('Request: ' + request + ' Status: ' + status + ' Error: ' + errorThrown);
			}
		});
	}

	function fadeAnnonce() {
		$('p', '#mod-annonces .annonces li').fadeOut('slow');
		fetchAnnonces();
	}

	function setCoordonnees(id, data) {
		var sAdresse = data.adresse.length > 0 ? data.adresse + '<br />' : '';
		var sLieu = data.ville.length > 0 && data.province.length > 0 ? data.ville  + ', ' + data.province + '<br />' : '';
		var sCodePostal = data.codepostal.length > 0 ? data.codepostal + '<br />' : '';
		var sSite = data.site.length > 0 ? data.site : '';
		$('.coordonnees', id).empty().append('<span class="telephone">' + data.telephone + '</span><br />' +
			sAdresse + sLieu + sCodePostal + sSite
		);
	}

	$('#dialog-annonce, #dialog-banniere, #dialog-detaillant, #dialog-marque').dialog({
		autoOpen: false,
		draggable: false,
		modal: true,
		resizable: false,
		width: 750,
		height: 525,
		buttons: {
			'Fermer': function() {
				$(this).dialog('close');
			}
		},
		open: function() {
			if ($(this).find('#map').length > 0) {
				google.maps.event.trigger(gMap, 'resize');
				gMap.fitBounds(gBounds);
			}
		},
		close: function() {
			if ($(this).find('#map').length > 0) {
				$('#map-container').append($(sMapLocation));
				deleteOverlays();
			}
		}
	});

	$('li', '.annonces').live('click', function() {
		nAnnonceID = $(this).data('id');
		$.ajax({
			url: 'ajax/annonces.php',
			data: {
					id: nAnnonceID
			},
			dataType: 'json',
			success: function(data) {
				if (data != null && data.Statut == '0') {
					var sModele = data.Marque + ' ' + data.Modele + ' :: ' + data.Categorie + ' :: $' + data.prix;
					$('#dialog-annonce').dialog('option', 'title', sModele);
					$('#dialog-annonce').dialog('option', 'height', 'auto');
					$('.modele', '#dialog-annonce').html(sModele);
					$('.prix', '#dialog-annonce').html('$' + data.prix);
					$('.logo', '#dialog-annonce').attr('src', 'http://passionvelo.ca/media/image/' + data.LogoMarque);
					setCoordonnees('#dialog-annonce', data);
					$('#dialog-annonce').dialog('open');
				} else {
					// Retry a couple times and show a warning dialog if it keeps failing
				}
			},
			error: function(request, status, errorThrown) {
				// Show a warning dialog
			}
		});
		return false;
	});

	$('a', '.marques li').live('click', function() {
		nMarqueID = $(this).attr('class');
		$.ajax({
			url: 'ajax/marque.php',
			data: {
					id: nMarqueID
			},
			dataType: 'json',
			success: function(data) {
				if (data != null && data.Statut == '0') {
					$('#dialog-marque').dialog('option', 'title', data.nom);
					$('#dialog-marque').dialog('option', 'height', 525);
					$('.logo', '#dialog-marque').html('');
					if (data.Logo_Marque != null) {
						$('.logo', '#dialog-marque').html('<img alt="logo" src="http://passionvelo.ca/media/image/' + data.logo + ' title="' + data.nom + '" />');
					}
					$('.produits li', '#dialog-marque').remove();
					if (data.Categories != null) {
						$.each(data.Categories, function(i, item) {
							$('.produits', '#dialog-marque').append('<li>' + item + '</li>');
						});
					}
					$('.detaillants li', '#dialog-marque').remove();
					if (data.Detaillants != null) {
						$.each(data.Detaillants, function(i, item) {
							$('.detaillants', '#dialog-marque').append('<li>' + item.nom + '</li>');
						});
					}
					$('.coordonnees', '#dialog-marque').html(data.site);
					$('.logo-banniere', '.ui-dialog-buttonpane').remove();
					if (data.Banniere != null && data.Logo_Banniere != null) {
						$('#dialog-marque').next('.ui-dialog-buttonpane').prepend('<img class="logo-banniere" alt="logo" title="' + data.Banniere + '" src="http://passionvelo.ca/media/image/' + data.Logo_Banniere + '" />');
					}
					$('#dialog-marque').dialog('open');
				} else {
					// Retry a couple times and show a warning dialog if it keeps failing
				}
			},
			error: function(request, status, errorThrown) {
				// Show a warning dialog
			}
		});
		return false;
	});

	$('.logo a, .info a', '.detaillants li').live('click', function() {
		nDetaillantID = $(this).attr('class');
		$.ajax({
			url: 'ajax/detaillant.php',
			data: {
					id: nDetaillantID
			},
			dataType: 'json',
			success: function(data) {
				if (data != null && data.Statut == '0') {
					$('#dialog-detaillant').dialog('option', 'title', data.nom);
					$('#dialog-detaillant').dialog('option', 'height', 525);
					sMapLocation = '#dialog-detaillant .droite>#map';
					$('.droite', '#dialog-detaillant').prepend($('#map-container>#map'));
					$('.logo', '#dialog-detaillant').attr('src', 'http://passionvelo.ca/media/image/' + data.Logo_Detaillant)
					$('.marques li', '#dialog-detaillant').remove();
					if (data.Marques != null) {
						$.each(data.Marques, function(i, item) {
							$('.marques', '#dialog-detaillant').append('<li>' + item.nom + '</li>');
						});
					}
					var myLatLng = null;
					gBounds = new google.maps.LatLngBounds();
					$.each(data.Succursales, function(i, item) {
						myLatLng = new google.maps.LatLng(item.lat, item.lng);
						addMarker(myLatLng, '')
						gBounds.extend(myLatLng);
						if (i == 0) {
							item.site = data.site;
							setCoordonnees('#dialog-detaillant', item);
						}
					});
					$('.logo-banniere', '.ui-dialog-buttonpane').remove();
					if (data.Banniere != null && data.Logo_Banniere != null) {
						$('#dialog-detaillant').next('.ui-dialog-buttonpane').prepend('<img class="logo-banniere" alt="logo" title="' + data.Banniere + '" src="http://passionvelo.ca/media/image/' + data.Logo_Banniere + '" />');
					}
					$('#dialog-detaillant').dialog('open');
				} else {
					// Retry a couple times and show a warning dialog if it keeps failing
				}
			},
			error: function(request, status, errorThrown) {
				// Show a warning dialog
			}
		});
		return false;
	});

	$('.banniere a', '#liste li').live('click', function() {
		nBanniereID = $(this).attr('class');
		$.ajax({
			url: 'ajax/banniere.php',
			data: {
					id: nBanniereID
			},
			dataType: 'json',
			success: function(data) {
				if (data.Statut == '0') {
					$('#dialog-banniere').dialog('option', 'title', data.Banniere);
					$('#dialog-banniere').dialog('option', 'height', 525);
					sMapLocation = '#dialog-banniere>#map';
					$('.droite', '#dialog-banniere').prepend($('#map-container>#map'));
					$('p.description', '#dialog-banniere').html(nl2br(data.Description, true));
					$('.logo-banniere', '.ui-dialog-buttonpane').remove();
					$('#dialog-banniere').next('.ui-dialog-buttonpane').prepend('<a href="' + data.Site + '" target="_blank"><img class="logo-banniere" alt="logo" title="' + data.Banniere + '" src="http://passionvelo.ca/media/image/' + data.Logo + '" /></a>');
					var myLatLng = null;
					gBounds = new google.maps.LatLngBounds();
					$.each(data.Detaillants, function(i, item) {
						if (item.lat != null && item.lng != null) {
							myLatLng = new google.maps.LatLng(item.lat, item.lng);
							addMarker(myLatLng, item.nom)
							gBounds.extend(myLatLng);
						}
					});
					$('#dialog-banniere').dialog('open');
				} else {
					// Retry a couple times and show a warning dialog if it keeps failing
				}
			},
			error: function(request, status, errorThrown) {
				// Show a warning dialog
			}
		});
		return false;
	});

	if ($('#map').length > 0) {
		initialize();
	}
	fetchInterval = setInterval(fadeAnnonce, 10000);
	fetchAnnonces();
});
