// variables
var loc = null, 		// pos du point en cas de recherche par lieu
	bmap = null,		// bitmap de la recherche
	cnt = null,			// nombre de résultats
	gmap = null, 		// google map
	geocoder = null, 	// pour accélerer le géocodage
	baseIcon = null,	// pour les markers
	band = null;		// galerie pour l'upsell

// doRegion
function doRegion(frm)
{
	for(i=0; i<frm.region.length; i++)
		frm.region[i].checked = false;
	frm.location.value = '';
	loc = null;
	search();
}

// add
Date.prototype.add = function(days)
{
	var d = new Date();
	d.setTime(this.getTime() + days * 86400 * 1000);
	return d;
}

// ISO 8601
Date.prototype.getWeekNumber = function() 
{
	var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
	var DoW = d.getDay();
	d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
	var ms = d.valueOf(); // GMT
	d.setMonth(0);
	d.setDate(4); // Thu in Week 1
	return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};

// getYearWeek (cf mySQL's YEARWEEK)
Date.prototype.getYearWeek = function()
{
	var w = this.getWeekNumber();
	return ((this.getFullYear() - (w == 53 && this.getMonth() == 0 ? 1 : 0)) * 100 + w);
}

// toISO : YYYY-MM-DD
Date.prototype.toISO = function()
{
	return this.getFullYear() + '-' + (this.getMonth() + 1) + '-' + this.getDate();
}

// substr(-n) ne fonctionne pas sous IE6
String.prototype.right = function(size)
{
	return this.substr(this.length - size);
}

// parcourir un bitmap
String.prototype.walk = function(action)
{
	for (var str='', i=0; i<this.length; i+=4)
	{
		for (y=parseInt(this.substr(i, 4), 16), j=0; j<16; j++)
			if ((y & (1 << j)) && (false == action(4 * i + (16 - j))))
				y &= ~(1 << j);
		str += ('0000' + y.toString(16)).right(4);
	}
	return str;
}

// newSearch
function newSearch()
{
	document.forms['form_rechercher'].reset();
	loc = null;
	search();
}

// search
function search()
{
	var frm = document.forms['form_rechercher'], 
		res = "", 
		bmap2 = null;

	// enregistrer la recherche
	save_to_cookie(frm, 'TRU001_LAST_SEARCH');

	// recharger les données gmap si nécessaire
	if (frm.location.value.length && !loc)
	{
		getlocation(frm.location);
		return;
	}

	// recherche sur les régions
	for(x=new Array(), bmap=map['*'].replace(/./g, '0'), i=0; i<frm.region.length; i++)
	{
		if (frm.region[i].checked)
		{
			x.push(frm.region[i].label.innerHTML);
			bmap = combine(bmap, map[frm.region[i].value], or);
		}
	}
	if (x.length)
		res += "<li><strong>" + x.join(', ') + "</strong></li>";

	// si bitmap vide
	if (!bmap || !count(bmap))
		bmap = map['*'];

	// recherche sur les options
	for(x=new Array(), i=0; i<frm.option.length; i++)
	{
		if (frm.option[i].checked)
		{
			x.push(frm.option[i].label.innerHTML);
			bmap = combine(bmap, map[frm.option[i].value], and);
		}
	}

	if (x.length)
		res += "<li>" + x.join(', ').toLowerCase() + "</li>\n";
/*
	// full text (v1)
	var w = frm.ft.value.split(' ');
	for (i=0; i<w.length; i++)
	{
		if (map['ft_' + w[i]])
			bmap = combine(bmap, map['ft_' + w[i]], and);
		else
			delete w[i];
	}
	var s = w.length ? w.join(' ') : '';
	if (s)
		res += "<li><strong>" + s + "</strong></li>";
	frm.ft.value = s;
*/		
	// full text (v2)
	if (frm.maison.value)
		bmap = combine(bmap, frm.maison.value, and);
		
	// distance maximum du point indiqué
	if (loc)
	{
		if (frm.rad.selectedIndex <= 0) frm.rad.selectedIndex = 2;
		var opt = frm.rad.options[frm.rad.selectedIndex], rad = opt.value;
		res += "<li>" + opt.text + " : " + frm.location.value + "</li>\n";
		bmap = bmap.walk (function(id) {
			pt = pos[id];
			return (Math.round(6378 * Math.acos(Math.cos(pt[0]) * Math.cos(loc.y) * Math.cos(loc.x-pt[1]) + Math.sin(pt[0]) * Math.sin(loc.y))) <= rad);
		});
	}

	// recherche sur les dates
	if (frm.debut.value && frm.fin.value)
	{
		res += "<li>" + frm.debut.label.innerHTML + ' ' + frm.debut.value + ' ' + frm.fin.label.innerHTML + ' ' + frm.fin.value + "</li>\n";
		var k = (frm.flexible.checked ? frm.flexible.value : 0),
			dw = $('#debut').datepicker('getDate').add(2).getYearWeek(), 
			fw = $('#fin').datepicker('getDate').add(1).getYearWeek(), 
			bm1 = map['*'].replace(/./g, '0');

		for (i=-k; i<=k; i++)
		{
			for (bm2=map['*'], j=dw+i; j<=fw+i; j=(j%100==53)?Math.ceil(j/100)*100+1:j+1)
				bm2 = combine(bm2, map['semaine_'+j], and);
			bm1 = combine(bm1, bm2, or)
		}
		bmap = combine(bmap, bm1, and);
	}

	// recherche sur la capacité
	if ((index = frm.cap.selectedIndex) > 0)
	{
		var opt = frm.cap.options[index];
		res += "<li>" + opt.text + "</li>\n";
		if (index < frm.cap.options.length - 1)
			bmap2 = combine(bmap, map[frm.cap.options[index + 1].value], and);
		bmap = combine(bmap, map[opt.value], and);
	}

	// afficher le résumé de la recherche
	if (!res.length)
		res = err_select;
	$('#resume').html('<ul>' + res + '</ul>');

	// afficher le résultat de la recherche
	display(bmap);

	// upsell
	showBandeau(bmap2);
}

// showBandeau
function showBandeau(bmap)
{
	if (bmap)
	{
		var photos = new Array();
		bmap.walk( function(id) {
			photos.push('<div><a href="../index.php?page=maison&id=' + id + '"><img src="../files/maison/' + id + '/s_sml_001.jpg" width="100" alt="" /></a></div>');
		});
		if (photos.length)
		{
			band.load(photos);
			$("#espace").show();
			return;
		}
	}
	$("#espace").hide();
}

// display
function display(bmap)
{
	// afficher les points
	gmap.clearOverlays();
	bmap.walk(function(id) { addMarker(id); });

	// afficher les compteurs
	cnt = count(bmap);
	$('#count').html(cnt.toString());
	for (i=2; i<=6; i++)
		$('#type_' + i).html(count(combine(bmap, map['type_' + i], and)).toString());
}

// and
function and(x, y) { return (x & y); }
function or(x, y) { return (x | y); }

// addMarker
function addMarker(id)
{
	if (!baseIcon)
	{
		baseIcon = new GIcon();
		baseIcon.iconSize = baseIcon.shadowSize = new GSize(45,44);
		baseIcon.iconAnchor = new GPoint(14,44);
		baseIcon.infoWindowAnchor = new GPoint(0,16);
		baseIcon.image = "../img/gmap_pointer.png";
		baseIcon.shadow = "../img/gmap_pointer_shadow.png";
	}

	var pt = pos[id],
		gpt = new GLatLng(pt[0] * 180 / Math.PI, pt[1] * 180 / Math.PI),
		marker = new GMarker(gpt, { title: pt[2], icon: baseIcon });
	GEvent.addListener(marker, "click", function() {
		window.location.href = "../index.php?page=maison&id=" + id;
	});
	gmap.addOverlay(marker);
}

// combine
function combine(x, y, fn)
{
	for(var i=0, r=''; i<Math.max(x.length, y.length); i+=4)
		r += ('0000' + (fn(parseInt(x.substr(i, 4), 16), parseInt(y.substr(i, 4), 16))).toString(16)).right(4);
	return r;
}

// count
function count(bmap)
{
	var n = 0;
	bmap.walk( function(id){ n++; } );
	return n;
}

// listResults
function listResults(page, sort)
{
	var frm = document.forms[0],
		arg = {
			'lg': 	lg, 
			'bmap': bmap, 
			'sort': (sort || ''), 
			'page': (page || 1),
			'debut':frm.debut.value.length ? $('#debut').datepicker('getDate').toISO() : '',
			'fin': 	frm.fin.value.length ? $('#fin').datepicker('getDate').toISO() : ''
			};
	$('#selection').load('../list.php', arg);
	(cnt > 0) ? $('#err_criteres').hide() : $('#err_criteres').show();
}

// showResults
function showResults(page, sort)
{
	var frm = document.forms[0];
	
	// si une date est renseignée l'autre doit l'être aussi
	if ((frm.debut.value.length > 0) != (frm.fin.value.length > 0))
	{
		alert(errDate);
		return;
	}
	
	listResults(page, sort);
	location.hash = 'selection';	
	if(pageTracker)
	{
		pageTracker._trackPageview('/' + lg + '/rechercher/btn_voir');
		pageTracker._trackEvent("rechercher", "btn_voir " + lg);
	}
}

// getlocation
function getlocation(fld)
{
	loc = null;
	if (GBrowserIsCompatible())
	{
		if (!geocoder)
			geocoder = new GClientGeocoder();
		geocoder.getLatLng(fld.value, function(pt) {
			loc = pt ? {x: pt.x * Math.PI / 180, y: pt.y * Math.PI / 180} : null;
			search(fld.form);
		});
	}
}

// onload
window.onload = function()
{
	// googlemap
	if (GBrowserIsCompatible())
	{
		// creation de la carte
		var centerPoint = new GLatLng(43.731414, 11.337891);
		gmap = new GMap2(document.getElementById("googlemap"));
		gmap.setCenter(centerPoint, 6);
		gmap.setMapType(G_PHYSICAL_MAP)
		gmap.addControl(new GSmallMapControl());
	}

	// bandeau
	band = new bandeau(null, 100, $('#band_p'), 0);
	$("#next").click( function(){ band.move(-1); return false; } );
	$("#prev").click( function(){ band.move(+1); return false; } );

	var frm = document.forms['form_rechercher'];
	add_label_properties(frm);
	load_from_cookie(frm, 'TRU001_LAST_SEARCH');

	// calendrier
	var dayNames = ['di','lu','ma','me','je','ve','sa'],
		monthNames = ['janvier','février','mars','avril','mai','juin','juillet','août','septembre','octobre','novembre','décembre'];
		
	$.datepicker.setDefaults ({ dateFormat: 'dd-mm-yy', firstDay: 1, dayNamesMin: dayNames, monthNames: monthNames });
	$('#debut').datepicker( {onSelect: selectDateDebut, beforeShowDay: checkDateDebut} );
	$('#fin').datepicker( {onSelect: selectDateFin, beforeShowDay: checkDateFin} );
	$('.date .btn_dp').css('cursor', 'pointer').click(function() { $('#' + this.id.replace('btn_', '')).datepicker('show'); });

	search();
	listResults();
};

// checkDateFin
function checkDateFin(d)
{
	var debut = $('#debut').datepicker('getDate');
	return [(!debut || d.getTime() >= debut.getTime()), ''];
}

// checkDateDepart : vérifie la validité de la date de départ
function checkDateDebut(d)
{
	return [(d.getTime() >= (new Date()).getTime()), ''];
}

// changer la date de début
function selectDateDebut(d)
{
	var d = $('#debut').datepicker('getDate'), f = $('#fin').val() ? $('#fin').datepicker('getDate') : new Date();
	if (d.getTime() > f.getTime())
	{
		f.setTime(d.getTime() + 7*864e5);
		$('#fin').datepicker('setDate', f);
	}
	search();
}

// changer la date de fin
function selectDateFin(d)
{
	search();
}

// libérer la mémoire
window.onunload = GUnload;

// add_label_properties
function add_label_properties (frm)
{
	if (typeof frm.getElementsByTagName == 'undefined')
		return;
	var label, elem, i=0, j=0, labels = frm.getElementsByTagName("label");
	while (label = labels[i++])
	{
		if (typeof label.htmlFor == 'undefined')
			return;
		elem = frm.elements[label.htmlFor];
		if (typeof elem != 'undefined' && typeof elem.label == 'undefined')
		{
			if (typeof elem.length != 'undefined' && elem.length > 1 && elem.nodeName.toUpperCase() != 'SELECT' )
			{
				for (j=0; j<elem.length; j++)
					elem.item(j).label = label;
			}
			else
			{
				elem.label = label;
			}
		}
	}
}
