window.addEvent('domready', function() {	
	if ((navigator.userAgent.toLowerCase()).indexOf('mobile') != -1)
		document.location = '/map-v3/';
	
	/* Initialisation des formulaires */
	if ($('content-form') != null) {
		var myForm = new Forms('content-form');
	}
	
	if ($('lastNews')) {
		var reqNews = new Request({method : 'get', 
									url :'/include/devspe.php?action=actualite_recente',
									onComplete: function(response) { $('lastNews').set('html', response); }
									}).send();
		var loc = document.location.toString();
		if ((loc).contains('actualite')) {
			$('leftbar').grab($('lastNews'),'bottom');
		}
	}
	
	if ($('commercantUne')) {
		var reqNews = new Request({method : 'get', 
									url :'/include/devspe.php?action=commercant_une',
									onComplete: function(response) { $('commercantUne').set('html', response); }
									}).send();
	}


	/* Création du carousel */
	horizontal = new Fx.Scroll.Carousel('primaryBanner',{
		mode: 'horizontal',
		onStart: function(){
			horizontal.getCurrent().tween('color','#000');
		},
		onComplete: function(){
			horizontal.getCurrent().tween('color','#fff');
		}
	});
	
	var show = function () { horizontal.toNext(); };
	show.periodical(5000);
	
	
	/* Champs de recherche */
	if ($('search') != null)  {
		$$('#search input[type=text]').each(function(e, i) { 
			e.addEvent('focus', function() { this.select(); }); 
		});
	
		$('search_mag_btn').addEvent('click', function (event) { 
		var form = $('search_enseigne').getElement('form'); 
		(form).set('action','http://www.clermontcommerce.fr/include/commercant.php?action=search_mag'); 
		form.submit();
		});
	
		
		$('search_act_btn').addEvent('click', function (event) { 
		var form = $('search_activite').getElement('form'); 
		(form).set('action','http://www.clermontcommerce.fr/include/commercant.php?action=search_act'); 
		form.submit();
		});


		var xmlDoc = parseXMLFile ('http://www.clermontcommerce.fr/include/commercant-xml.php');	
		var data_mag = []; var data_act = []; 
		var temp = [], tempMag = [], commercantTerm;
		
		var doc = xmlDoc.documentElement;
		var commercant = xmlDoc.getElementsByTagName('commercant');
		var ok = '';

		for (var i=0; i<commercant.length; i++) {
			commercantTerm = commercant[i].getElementsByTagName('libelle')[0].firstChild.data;
			if (tempMag.indexOf(commercantTerm) == -1) {
				data_mag.push({"value": i, "text": commercantTerm});
				tempMag.push(commercantTerm);
			}
			
			var activite = commercant[i].getElementsByTagName('activite');
			for (var j=0; j<activite.length; j++) {
				if (activite[j].firstChild!= null) {
					if (temp.indexOf(activite[j].firstChild.data) == -1) {
						data_act.push({"value": j, "text": activite[j].firstChild.data});
						temp.push(activite[j].firstChild.data);
					}
				}
			}

		}
									 

		var instanceMag = new Meio.Autocomplete($('search_mag'), data_mag, {
			selectOnTab: false,
			onNoItemToList: function(elements){
				elements.field.node.highlight('#ff0000');
			},
			filter: {
				type: 'contains',
				path: 'text'
			}
		});
		
		var instanceAct = new Meio.Autocomplete($('search_act'), data_act, {
			selectOnTab: false,
			onNoItemToList: function(elements){
				elements.field.node.highlight('#ff0000');
			},
			filter: {
				type: 'contains',
				path: 'text'
			}
		});
	}
	
});


function parseXMLFile (url) {
	var xmlDoc = null;
	var xmlhttp = null;

	if(navigator.appName == "Microsoft Internet Explorer"){
		var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		xmlhttp.open("GET",url,false);
		xmlhttp.send("");
		
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
  		xmlDoc.loadXML(xmlhttp.responseText);

	}else {
		var xmlhttp = new window.XMLHttpRequest();
		xmlhttp.open("GET",url,false);
		xmlhttp.send(null);
		xmlDoc = xmlhttp.responseXML.documentElement;
	}
	

	return xmlDoc;	
}


var Forms = new Class ({
		Implements: Options,
		
		options : {
			formValidInput : 'valid-form',
			errorClass : 'error'
		},

		initialize : function (container, options) {
			this.setOptions(options);
			this.validForm = $(this.options.formValidInput);
			
			this.container = $(container);

			this.obl = [];
			this.initUrl();
			this.initPopup();

			
			this.container.addEvent('submit', function(event) { 
				this.obl.empty();
				this.parseInput(this.container); 
				if (this.obl.length > 0) {
					event.preventDefault(); 
					this.displayObl();
				}
			}.bind(this));
		},
		
		initUrl : function () {
			this.action = this.container.get('action');
		},
		
		initPopup : function () {
			this.popup = new Element ('div', {'id' : 'popup'});
			this.popup.inject(document.body, 'top');
			
			this.popup.addEvents({
				'show' : function () { this.toggleClass('show'); },
				'hide' : function () { this.toggleClass('show'); }
			});
		},
		
		parseInput : function (container) {
			var bool = true;
			(container.getElements('input, textarea, select')).each(function (elt, i) {
				if (elt.hasClass('obligatoire') && this.testInput(elt) == false) {
					elt.addClass(this.options.errorClass);
					this.obl.push(elt);
				}else if (elt.hasClass('error')) elt.removeClass('error');
			}, this);
		},
		
		testInput : function (tag) {
			var result =  true;

			switch (tag.get('tag')) {
				case 'input'	:	if (tag.get('type') == 'text') {
										if (tag.get('value').trim() == '')
											result = false;
										tag.addEvent('click', function() { this.select(); });
									}
									else if (tag.get('type') == 'checkbox' && tag.checked == false) result = false;
									else if (tag.get('type') == 'radio' && tag.checked == false) result = false
									break;

				case "textarea"	:	if (tag.get('value').trim() == '') result = false;
									break;

				case "select"	:	if (tag.getSelected() == null) result = false;
									break
			}
			
			return result;
		},

		displayObl : function () {
			this.popup.empty();
			
			var background = new Element('div', {'class': 'background'});
			background.inject(this.popup);
			
			var message = new Element('div', {'class': 'message'});
			message.addEvent('click', function () { this.popup.fireEvent('hide'); }.bind(this));

			if (this.obl.length > 0) {
				(new Element('p', {'html' : 'Les champs du formulaire <span class="rouge">en rouge</span> contiennent des erreurs ou ne sont pas remplis correctement'})).inject(message);
				(new Element('p', {'html' : '&gt;&gt; Revenir sur le formulaire', 'class' : 'link'})).inject(message);
				(new Element('p', {'class' : 'footer'})).inject(message);
	
				message.inject(this.popup);
				
				this.popup.fireEvent('show');
			}
		},
		
		initDate : function (container, radical) {
			var current = ($('key-gen').get('value')).split('-');

			$$('#'+container+' input').each(function (e, i) {
				if (e.get('name') == radical+'_d') e.set('value', current[0]);
				else if (e.get('name') == radical+'_m') e.set('value', current[1]);
				else if (e.get('name') == radical+'_y') e.set('value', current[2]);
			})

		}
	});


	function display_viewer (url, w, h) {
		$('viewer').set('html','<img src="'+url+'" width="'+w+'" height="'+h+'" />');
	}
