function addInputFile(root)
{
	var br = document.createElement('br');
	var input = document.createElement('input');
	input.setAttribute('type', 'file');
	input.setAttribute('name', root+'[]');
	input.setAttribute('onchange', 'addInputFile("'+root+'")');
	var container = $(root);
	container.appendChild(input);
	input.className = 'text';
	container.appendChild(br);
}

function addBossInputText()
{
	addInputText('boss_firstname');
	addInputText('boss_name');
}

var nbInputText = [];
function addInputText(root)
{
	if(typeof nbInputText[root] == 'undefined') nbInputText[root] = 1;
	if(nbInputText[root] >= 10) return false;
	var br = document.createElement('br');
	var input = document.createElement('input');
	input.setAttribute('type', 'text');
	input.setAttribute('name', root+'[]');
	input.className = 'text';
	$(root).adopt(input);
	$(root).adopt(br);
	nbInputText[root]++;
}

function dump(obj)
{
	var text = '';
	for(idd in obj)
	{
		text += idd+" : "+obj[idd]+"\n";
	}
	alert(text);
}

function switchAlphaSearch(id)
{
	if(id == 'tabDirigeant')
	{
		$$('.tabDirigeant').each(function (item, index) { item.className = 'tabDirigeant tabActive'; });
		$$('.tabEntreprise').each(function (item, index) { item.className = 'tabEntreprise'; });
		$('alphaEntreprise').style.display = 'none';
		$('alphaDirigeant').style.display = 'block';
	}
	else
	{
		$$('.tabEntreprise').each(function (item, index) { item.className = 'tabEntreprise tabActive'; });
		$$('.tabDirigeant').each(function (item, index) { item.className = 'tabDirigeant'; });
		$('alphaEntreprise').style.display = 'block';
		$('alphaDirigeant').style.display = 'none';
	}
}

function changePaging()
{
    var p = document.getElementById('paging').options[document.getElementById('paging').selectedIndex].value;
    var params = window.location.search;
    var url = window.location.pathname;

    if(params.lastIndexOf('?') > -1 && params.length > 2)
    {
        params = params.replace(/\?/, ''); // On enlève le ?
        var prms = params.split(/\&/); // On récupère chaque paramètre

        for(i=0;i<prms.length;i++)
        {
            var temp = prms[i].split(/=/);
            if(temp[0] == 'p') prms[i] = 'p='+p;
        }

        url += '?'+prms.join('&');
    }
    else url += '?&p='+p;

    document.location = url;
}

function switchAdvSearch()
{
	var state = $('fastSearch').style.display;
	if(state == 'block' || state == '')
	{
		var local = '';
		if($('place') !== null) local = $('place').value;
		$('fastSearch').style.display = 'none';
		$('advancedSearch').style.display = 'block';
		$$('#actname', '#place').each(function (item, index) { item.value = ''; });
		if(local != '') $('locate').value = local;
	}
	else
	{
		var local = $('locate').value;
		var act = $('category').value + ' ' + $('name').value;
		$('fastSearch').style.display = 'block';
		$('advancedSearch').style.display = 'none';
		$$('#name', '#category', '#address', '#siret', '#locate', '#keywords').each(function (item, index) { item.value = ''; });
		$('department_id').options[0].selected = 1;
		if($('place') !== null) $('place').value = local;
		if($('actname') !== null) $('actname').value = act;
	}
}

function checkForm(type, page)
{
	var state = true;
	if(typeof page == 'undefined') page = 'default';
	if(type == 'fast')
	{
		switch(page)
		{
			case 'service':
				// Champs name obligatoire
				if(!switchFieldError('category') || !switchFieldError('place')) state = false;
				else if($('category_id').value == 0)
				{
					$('listCategoryPopup').empty();
					var name = $('category').value;
					var request = new Request.JSON({
							method: 'get', 
							url: 'ajax.php', 
							onSuccess:function (responseJSON, responseText) {
								responseJSON.each(function (item, index, all)
								{
									var className = '';
									if(index == 0) className = 'list-item-first';
									else if(index == (all.length-1))
									{
										className = 'list-item-last';
										if(index%2 == 0) className += '-g';
										else className += '-w';
									}
									else className = 'list-item-'+((index%2 == 0)?'1':'0');

									addCategoryList(item.category_id, item.name, className);
								});
								if(responseJSON.length > 0) $('listCategoryPopup').set({'styles':{'display':'block'}});
								else if($('place').value == '') $('placePopup').set({'styles':{'display':'block'}});
								else $('blockChamps-second').submit();
							}});
					request.send('module=category&category='+name);
					state = false;
				}
				break;

			case 'boss':
				if(!switchFieldError('identity')) state = false;
				break;

			case 'annuaire':
				if(!switchFieldError('phone')) state = false;
				break;

			case 'geoloc':
				state = false;
				if($defined($('noGResults'))) search();
				else state = true;
				break;

			default:
				// Champs actname + place obligatoires
				if(!switchFieldError('actname')) state = false;
				if(!switchFieldError('place')) state = false;
				break;
		}
	}
	else
	{
		var mustLoc = ['locate'];
		var mustOther = ['name', 'siret', 'keywords', 'category'];
		var tempOther = false;

		if(page == 'geoloc') $('advSearchForm').action = 'geolocalisation.html';

		mustLoc.each(function (item, index)
		{
			if(!switchFieldError(item)) state = false;
		});

		mustOther.each(function (item, index)
		{
			if($(item).value != '') tempOther = true;
		});
		
		if(!tempOther)
		{
			switchFieldError('category');
			state = false;
		}
	}
	return state;
}

function switchFieldError(field)
{
	var result = true;
	if($(field).value != '')
	{
		$(field+'Popup').style.display = 'none';
		if($defined($(field+'Ex'))) $(field+'Ex').style.display = 'inline';
	}
	else
	{
		$(field+'Popup').style.display = 'block';
		if($defined($(field+'Ex'))) $(field+'Ex').style.display = 'none';
		result = false;
	}
	return result;
}

function addCategoryList(category_id, name, className)
{
	var cat = new Element('span', {
		'html':name, 
		'class':className,
		'events': {'click': function() {
				$('category').value = name;
				$('category_id').value = category_id;
				$('listCategoryPopup').set({'styles':{'display':'none'}});
				$('listCategoryPopup').empty();
				if($('place').value == '') $('placePopup').set({'styles':{'display':'block'}});
				else $('blockChamps-second').submit();
				$('place').focus();
			}}
		});
	$('listCategoryPopup').adopt(cat);
}

function addFavorite(id)
{
	var myRequest = new Request({
			method: 'get', 
			url: 'ajax.php', 
			onSuccess:function (responseText, responseXML) {
				$('favorites').innerHTML = responseText; }
			});
	myRequest.send('module=favorite&action=add&id='+id);
	return false;
}

var searched = new Array;
var arg = new Array;

function search(old)
{
	$('noGResults').style.display = 'none';

	inProcess(true);

	if(typeof old == "undefined")
	{
		var all = new Hash({
				actname: {value:$('actname').value},
				place: {value:$('place').value},
				name: {value:$('name').value},
				address: {value:$('address').value},
				siret: {value:$('siret').value},
				locate: {value:$('locate').value},
				department_id: {value:$('department_id').options[$('department_id').selectedIndex].value},
				keywords: {value:$('keywords').value},
				category: {value:$('category').value}
				});
	}
	else all = searched[old];

	var arg = getSearchQueryString(all);

	var myRequest = new Request.JSON({
			method: 'get', 
			url: 'ajax.php', 
			onSuccess:function (responseJSON, responseText)
			{
				gmap.clear();
				if(responseJSON.results.length > 0)
				{
					responseJSON.results.each(function(item, index) 
					{
						var marker = gmap.makeMarker(item);
						marker['icon'] = 'default';
						gmap.createMarker(marker);
					});
					gmap.focusMap();
				}
				else
				{
					$('noGResults').style.display = 'block';
				}
				inProcess(false);
			}
		});
	var req = 'module=gmapSearch&'+arg+'&'+$time();
	myRequest.send(req);

	if(typeof old == "undefined") addHisto(all);
}

function getSearchQueryString(all)
{
	var arg = [];
	var stringQuery = [];
	all.each(function(element, key)
	{
		if(typeof element.value != 'undefined' && element.value != 0 && element.value != '')
		{
			arg.push('search['+key+']='+element.value);
			if(key != 'department_id') stringQuery.push(element.value);
			else stringQuery.push($('department_id').options[element.value].text);
		}
	});
	$('searchQuery').set('text', stringQuery.join(' + '));
	return arg.join("&");
}

function inProcess(state)
{
	if(state) $('mapOverlay').style.display = 'block';
	else $('mapOverlay').style.display = 'none';
}

function addHisto(all)
{
	searched[searched.length] = all;
}

function addInHtmlList(item, index)
{
	var liEl = new Element('li');
	var aEl = new Element('a', {'href':item.url, 'text':item.name});
	aEl.inject(liEl.inject($('results')));
}

function razHtmlList()
{
	$('results').getElements('li').each(function(item, index)
	{
		item.destroy();
	});
}

function checkOffers(form_id)
{
	var test = $(form_id).toQueryString() != '';	
	if(!test) $('visibilityError').style.display = 'block';
	return test;
}

function switchVisibility(id)
{
	if($(id).style.display == "none" || $(id).style.display == "") $(id).style.display = 'block';
	else $(id).style.display = 'none';
	return false;
}

function tweenVisibility(id, min, max)
{
	var state = false;
	if($(id).getStyle('height') == max+'px') $(id).tween('height', min);
	else
	{
		$(id).tween('height', max);
		state = true;
	}
	return state;
}

function tweenInfoVisibility(id, min, max)
{
	var show = tweenVisibility(id, min, max);
	var button = $$('button.dashboard');
	if(!show) button[0].style.display = 'none';
	else button[0].style.display = 'inline';
}

function addEtaInputText()
{
	addInputText('eta_designation');
	addInputText('eta_address');
	addInputText('eta_city');
	addInputText('eta_zip');
}

function chooseNaf(item)
{
	$('naf').value = item.code;
	$('listSelectcategory_id').empty();
	$('listSelectcategory_id').set('text', item.name);
	$('company_category_id_value').value = item.category_id;
	$('nafList').empty();
}

function generateNafList(value)
{
	if(value.length >= 3)
	{
		var myRequest = new Request.JSON({
				method: 'post', 
				url: 'ajax.php', 
				onSuccess:function (responseJSON, responseText)
				{
					if(responseJSON.length > 0)
					{
						var result = [];
						responseJSON.each(function(item, index) 
						{
							var line = new Element('span').set(
							{
								'html': '<b>'+item.code+'</b> : '+item.name,
								'events': { 'click': function () { chooseNaf(item); } }
							});

							result.push(line);
						});
						$('nafList').empty();
						$('nafList').adopt(result);
					}
					else
					{
						$('nafList').empty();
						$('nafList').set('html', "<span class='fieldComment'>Ce code NAF n'existe pas dans notre fichier<br/>Vérifiez qu'il est au bon format (xx.xx)</span>");
					}
				}
			});
		var req = 'module=nafList&naf='+value+'&'+$time();
		myRequest.send(req);
	}
	else $('nafList').empty();
}

function checkGeoloc()
{
	var result = true;
	if($('geoActname').value == '')
	{
		result = false;
		$('geoError').style.display = 'block';
	}
	return result;
}


/*
	Fonctions Google AFS
*/

/*
* Cette fonction est obligatoire. Elle traite l'objet google_ads JavaScript,
* qui comprend des annonces AdSense pour les recherches en rapport avec la recherche de l'utilisateur. Le nom de cette
* cette fonction <i> doit</i> être <b>google_afs_request_done</b>. Si le nom de la fonction
* est incorrect, votre page n'affichera pas correctement les annonces AdSense pour les recherches.
*/

function google_afs_request_done(google_ads)
{
	var google_num_ads = google_ads.length;
	if(google_num_ads <= 0) return;

	var wideAds = ""; // texte html d'ensemble d'annonces grand format
	var narrowAds = ""; // texte html d'ensemble d'annonces petit format

	var top_ads = '';
	var bottom_ads = '';

	for(i=0;i<google_num_ads;i++)
	{
		if(google_ads[i].type=="text/wide")
		{
			temp_text ='<a style="text-decoration:none" onmouseover="javascript:window.status=\'' +
				google_ads[i].url + '\';return true;" ' +
				'onmouseout="javascript:window.status=\'\';return true;" ' +
				'href="' + google_ads[i].url + '">' +
				'<span class="ad_line1">' + google_ads[i].line1 + '</span></a><br>' +
				'<span class="ad_text">' + google_ads[i].line2 + '</span><br>' +
				'<a style="text-decoration:none" onmouseover="javascript:window.status=\'' +
				google_ads[i].url + '\';return true;" ' +
				'onmouseout="javascript:window.status=\'\';return true;" ' +
				'href="' + google_ads[i].url + '">' +
				'<span class="ad_url">' + google_ads[i].visible_url + '</span><br><br></a>';

			if(i<3) top_ads += temp_text;
			else bottom_ads += temp_text;
		}
		else
		{
			// produire une annonce petit format
			narrowAds+='<a style="text-decoration:none" onmouseover="javascript:window.status=\'' +
				google_ads[i].url + '\';return true;" ' +
				'onmouseout="javascript:window.status=\'\';return true;" ' +
				'href="' + google_ads[i].url + '">' +
				'<span class="ad_line1">' + google_ads[i].line1 + '</span></a><br>' +
				'<span class="ad_text">' + google_ads[i].line2 + '</span><br>' +
				'<span class="ad_text">' + google_ads[i].line3 + '</span><br>' +
				'<a style="text-decoration:none" onmouseover="javascript:window.status=\'' +
				google_ads[i].url + '\';return true;" ' +
				'onmouseout="javascript:window.status=\'\';return true;" ' +
				'href="' + google_ads[i].url + '">' +
				'<span class="ad_url">' + google_ads[i].visible_url + '</span><br><br></a>';
		}
	}

	if(narrowAds != "")
	{
		narrowAds = '<a style="text-decoration:none" ' +
			'href="https://www.google.com/adsense/support/bin/request.py?contact=afs_violation">' +
			'<span class="ad_header" style="text-align:left"> Annonces Google</span><br><br></a>' + narrowAds;
	}

	if(top_ads != "")
	{
		top_ads = '<a style="text-decoration:none" ' +
			'href="https://www.google.com/adsense/support/bin/request.py?contact=afs_violation">' +
			'<span class="ad_header" style="text-align:left"> Annonces Google</span><br><br></a>' + top_ads;
	}

	if(bottom_ads != "")
	{
		bottom_ads = '<a style="text-decoration:none" ' +
			'href="https://www.google.com/adsense/support/bin/request.py?contact=afs_violation">' +
			'<span class="ad_header" style="text-align:left"> Annonces Google</span><br><br></a>' + bottom_ads;
	}


	// Écrire du code HTML pour des annonces grand format ou petit format dans les éléments <div> appropriés
	document.getElementById("top_ad_unit").innerHTML = top_ads;
	document.getElementById("bottom_ad_unit").innerHTML = bottom_ads;
	document.getElementById("narrow_ad_unit").innerHTML = narrowAds;
}
