var $j = jQuery.noConflict();
var id = 0;
var premier = "";
var nom ="";
var time = 0;
var str = "La saisie doit &ecirc;tre compris entre {0} et {1} caract&egrave;res.";
var msg_required = "Ce champ est obligatoire.";
var LPays = {"1":"fr","2":"de","3":"lu", "4":"be","5":"ch"};
var LIPays = {"FR":"1","DE":"2","LU":"3", "BE":"4","CH":"5"};


$j(document).ready(function(){
	$j('a.Amenu').click(function(){
		$j('#conteneur').slideUp();
		$j('#conteneur').html('');
		location.href = (this).href;
		return false;
	});
	
    $j("#RDate_Depart").datepicker({
		beforeShow: function(input) { input.value=""; },
        dateFormat: 'dd/mm/yy',
        showButtonPanel: true,
        currentText: "Aujourd'hui",
        closeText: 'Fermer',
        dayNamesMin: semaineShort,
        monthNames: mois,
		minDate: 0, 
		maxDate: '+3M',
		firstday:1
   
    });
    $j('#RDate_Depart').attr('class','valid');
	//$j("RDate_Depart").blur();
//	$j('.timeP').focus(function(){alert('oui');});
	$j('.timeP').timePicker({
		step:15
	});
	$j.each($j('.timeP'),function(item,i){
		i.value = "07:00";
	});
	if($j('#requeteur').length != 0)
		$j('#requeteur').load('/zone/requeteur');
		
		/*
	$j("#formLogin").validate({
        rules: {
            identifiant: {
                required: true,
                minlength: 6
//				,
//                maxlength: 26
            },
            motdepass: {
                required: true,
                minlength: 6,
                maxlength: 32
            }
        },
        messages: {
            identifiant: {
                required: msg_required,
                minlength: jQuery.validator.format(str, "6", "26")
//				,
//                maxlength: jQuery.validator.format(str, "3", "26")
            },
            motdepass: {
                required: msg_required,
                minlength: jQuery.validator.format(str, "6", "32"),
                maxlength: jQuery.validator.format(str, "6", "32")
            }
        },
        errorPlacement: function(error, element)
         {
            // Set positioning based on the elements position in the form
            var elem = $j(element),
               corners = ['left center', 'right center'],
               flipIt = elem.parents('span.right').length > 0;
 
            // Check we have a valid error message
            if(!error.is(':empty')) {
               // Apply the tooltip only if it isn't valid
               elem.filter(':not(.valid)').qtip({
                  overwrite: false,
                  content: error,
                  position: {
                     my: corners[ flipIt ? 0 : 1 ],
                     at: corners[ flipIt ? 1 : 0 ],
                     viewport: $j(window)
                  },
                  show: {
                     event: false,
                     ready: true
                  },
                  hide: false,
                  style: {
                     classes: 'ui-tooltip-shadow ui-tooltip-rounded ui-tooltip-error'
                  }
               })
 
               // If we have a tooltip on this element already, just update its content
               .qtip('option', 'content.text', error);
            }
 
            // If the error is empty, remove the qTip
            else { elem.qtip('destroy'); }
         },
         success: $j.noop
    });	
	*/
	//animation des popup alert
	var msie6 = $j.browser == 'msie' && $j.browser.version < 7;
	  if (!msie6) {
	    $j(window).scroll(function (event) {
	     $j.each($j('.ui-dialog:has("#alert")'),function(){
	        var eloffset = $j(this).offset();
	        var windowpos = $j(window).scrollTop();
	        if(windowpos<eloffset.top) {
	            var finaldestination = 0;
	        } else {
	            var finaldestination = windowpos;
	        }
	        $j(this).stop().animate({'top':finaldestination},200);
	    });
	    });
	  }  
});
var oAlert =alert;
function alert(txt, title) {  
    try {  
        jAlert(txt, title);  
    } catch (e) {  
        oAlert(txt);  
    }  
}  
//confirm()  
var oConfirm = confirm;  
function confirm(txt, title, func) {  
    try {  
        jConfirm(txt, title, func);  
    } catch (e) {  
        if (oConfirm (txt, title)) func();  
    }  
}  
function jAlert(txt,title){
	if($j('#alert').length ==0){
		$j('#contenu').append('<div id="alert"></div>');
	}
		$j('#alert').html(txt);
		$j('#alert').dialog({
            title: title,
            bgiframe: true,
            modal: true,
            //height: 650,
            //width: 650,
            closeOnEscape: false,
            draggable: false,
            resizable: false,
            buttons: {
                '  ok  ': function(){
                    $j(this).dialog('close');
                }
            },
            close: function(){
                $j('#alert').html('');
                $j(this).dialog('destroy');
                $j('#alert').remove();
            }
        });
}
function jConfirm(txt, title, callback){
	if($j('#alert').length ==0){
		$j('#contenu').append('<div id="alert"></div>');
	}
	$j('#alert').html(txt);
	$j('#alert').dialog({
        title: title,
        bgiframe: true,
        modal: true,
        //height: 650,
        //width: 650,
        closeOnEscape: false,
        draggable: false,
        resizable: false,
        buttons: {
            '  ok  ': function(){
                $j(this).dialog('close');
                if(callback) callback(true);
            },
            'annuler': function(){
                $j(this).dialog('close');
            }
        },
        close: function(){
            $j('#alert').html('');
            $j(this).dialog('destroy');
            $j('#alert').remove();
        }
    });
}
function noaccent(chaine){
    temp = chaine.replace(/[àâä]/gi, "a");
    temp = temp.replace(/[éèêë]/gi, "e");
    temp = temp.replace(/[îï]/gi, "i");
    temp = temp.replace(/[ôö]/gi, "o");
    temp = temp.replace(/[ùûü]/gi, "u");
    temp = temp.replace(/[\s]/gi, "-");
    return temp; 
}
/*
function ajaxLoader (el, options) {
	// Becomes this.options
	var defaults = {
		bgColor 		: '#fff',
		duration		: 800,
		opacity			: 0.7,
		classOveride 	: false
	}
	this.options 	= jQuery.extend(defaults, options);
	this.container 	= $j(el);
	
	this.init = function() {
		var container = this.container;
		// Delete any other loaders
		this.remove(); 
		// Create the overlay 
		var overlay = $j('<div></div>').css({
				'background-color': this.options.bgColor,
				'opacity':this.options.opacity,
				'width':container.width(),
				'height':container.height(),
				//'position':'absolute',
				'top':'0px',
				'left':'0px',
				'z-index':99999
		}).addClass('ajax_overlay');
		// add an overiding class name to set new loader style 
		if (this.options.classOveride) {
			overlay.addClass(this.options.classOveride);
		}
		// insert overlay and loader into DOM 
		container.append(
			overlay.append(
				$j('<div></div>').addClass('ajax_loader')
			).fadeIn(this.options.duration)
		);
    };
	
	this.remove = function(){
		$j(el+" .ajax_overlay").remove();
	}

    this.init();
}
*/
function autoVille(mode, dom,valeur){
	 
    var query = dom.value;
    var id = dom.id;
    var nom = '#' + id;
	if(!valeur) valeur=0;
	var chemin = "/communes/autocompletioncommunesrech/" + query;
    $j(nom).attr('autocomplete', 'off');
    if (mode == 'on') {
		$j(nom).flushCache();
        $j(nom).autocomplete(chemin, {
            inputClass: 'ville',
			extraParams:{pays:valeur},
            selectedFirst: true,
            scrollHeight: 193,
            scroll: true,
			max:10,
			delay:0,
			cacheLength : 1,
            formatItem: function(data, i, n, value){
				time=0;
                return value.split(":")[1]+ " - " +value.split(":")[2];
            },
            formatResult: function(data, value, max){
				// faire test si identifiant = 0 avec pop-up
				if (value.split(":")[0] != 0) {
					if (time == 0) {
						premier = value;
						time = 1;
					}
					var retour = value.split(":")[1];
					return retour;
				}
				else {
					alert("Merci de vérifier votre saisie.");
					$j(nom).val('');
					$j('#' + id).focus();
					return false;
				}
            }
        });
		$j(nom).result(function(event, data, formatted){
			remplir(formatted,id,nom);
        });
		$j(nom).blur(function() {
			if (premier != "") {
				remplir(premier,id,nom);
				premier = "";
			}
		});
		
    }
    else 
        if (mode == 'off') {
            $j(nom).flushCache();
            $j(nom).unautocomplete();
            $j(nom).unbind('.autocomplete');
            $j(nom).removeClass('ville');
        }
}

function remplir(formatted, id,nom){
	var identifiant = formatted.split(':')[0];
	if (identifiant != 0) {
		var complete = formatted.split(":")[1].substr(0,formatted.split(":")[1].length);
		var paren = complete.indexOf(' (');
		if (paren != -1) {
			var ville = complete.substr(0, paren);
			var paren2 = complete.indexOf(')');
			var tabcp = complete.split('(');
			var cp = tabcp[1].split(')')[0];
		}
		else {
			var paren2 = complete.indexOf(' - ');
			if (paren2 != -1) {
				var ville = complete.substr(0,paren2);
				var cp = "";
			}else{
				var ville = complete;
				var cp = "";
			}
		}
		if (id == "RVille_Depart") {
			$j("#CVille_Depart").val(formatted.split(":")[0]);
			$j('#' + id).val(complete);
		}
		if (id == "RVille_Arrivee") {
			$j("#CVille_Arrivee").val(formatted.split(":")[0]);
			$j('#' + id).val(complete);
		}
		if (id == "PVille_Depart") {
			$j("#CPVille_Depart").val(formatted.split(":")[0]);
			$j('#' + id).val(complete);
		}
		if (id == "PVille_Arrivee") {
			$j("#CPVille_Arrivee").val(formatted.split(":")[0]);
			$j('#' + id).val(complete);
		}
		if (id == "Ville_Depart") {
			//$j('#ListePays_Ville_Depart option[value="' + LIPays[formatted.split(":")[2]] + '"]').attr('selected','selected');
			$j(nom).val(ville);
			$j('#CP_Depart').val(cp);
		//$j("#villeD").val(formatted.split(":")[0]);
		}
		if (id == "Ville_Arrivee") {
			//$j('#ListePays_Ville_Arrivee option[value="' + LIPays[formatted.split(":")[2]] + '"]').attr('selected','selected');
			$j(nom).val(ville);
			$j('#CP_Arrivee').val(cp);
		// $j("#villeA").val(formatted.split(":")[0]);
		}
		if (id == "Ville_Depart_Aire") {
			//$j('#ListePays_Ville_Depart option[value="' + LIPays[formatted.split(":")[2]] + '"]').attr('selected','selected');
			$j(nom).val(ville);
			$j('#CP_Depart_Aire').val(cp);
		}
		if (id == "Ville_Arrivee_Aire") {
			//$j('#ListePays_Ville_Arrivee option[value="' + LIPays[formatted.split(":")[2]] + '"]').attr('selected','selected');
			$j(nom).val(ville);
			$j('#CP_Arrivee_Aire').val(cp);
		}
		if (id == "Ville_Etape") {
			//$j('#ListePays_Ville_Etape option[value="' + LIPays[formatted.split(":")[2]] + '"]').attr('selected','selected');
			$j(nom).val(ville);
			$j('#CP_Etape').val(cp);
		}
		if (id == "Ville_Point") {
			//$j('#ListePays_Ville_Point option[value="' + LIPays[formatted.split(":")[2]] + '"]').attr('selected','selected');
			$j(nom).val(ville);
			$j('#CP_Point').val(cp);
		}
		if (id == "RVille") {
			$j(nom).val(ville);
			$j('#RCP').val(cp);
			$j('#hVille').val(formatted.split(':')[0]);
		}
		if (id == "Ville") {
			//$j('#ListePays_Inscription option[value="' + LIPays[formatted.split(" - ")[2]] + '"]').attr('selected','selected');
			$j(nom).val(ville);
			$j('#CP').val(cp);
		}
			time = 0;
			premier = "";
	 	$j(nom).flushCache();
	}else{
		alert("Merci de vérifier votre saisie.");
		$j(nom).val('');
		$j('#'+id).focus();
	}
}

function noaccent(chaine) {
  temp = chaine.replace(/[���]/gi,"a");
  temp = temp.replace(/[����]/gi,"e");
  temp = temp.replace(/[��]/gi,"i");
  temp = temp.replace(/[��]/gi,"o");
  temp = temp.replace(/[���]/gi,"u");
  return temp;
}
function autoAdresseRequeteur(mode, dom,typeAdresse){
	var query = dom.value;
    var id = dom.id;
    var nom = '#' + id;
	if (mode == 'on') {
		$j(nom).attr('autocomplete', 'off');
		$j(nom).geo_autocomplete(new google.maps.Geocoder, {
			mapkey: 'ABQIAAAAEcUpeH_-08lx9hb7NX7MxRSsb9KSOEw0JqhE9lg5ZzrkRCplyBQ--QX2WntEovD01XGNgjhov2Us2g',
			minChars: 3,
			cacheLength: 1,
			width: 300,
			scroll: true,
			delay: 300,
			max:100,
			inputClass: 'ChmpAdresse',
			parse: function(_results, _status, _query){
				var _parsed = [];
					$j.each(_results, function(_key, _result){
						_parsed.push({
							data: _result,
							value: _result.formatted_address,
							result: _result.formatted_address
						});
					});
				return _parsed;
			},
			formatItem: function(_data, _i, _n, _value){
				var value = formatAdresse(_data);
				return value;
			}
		}).result(function(_event, _data){
			$j('#results').append(_data);
		});
		$j(nom).result(function(event, data, formatted){
			remplirChampAdresseRequeteur(data,nom,typeAdresse,event,formatted);
        });
        $j(nom).blur(function(){
        	if(!$j("#formRequeteur").validate().element( nom))
				$j(nom).removeClass('valid').addClass('error');
			else
				$j(nom).removeClass('error').addClass('valid');
				
		});
	}else{
		if(mode == 'off'){
			 $j(nom).flushCache();
            $j(nom).unautocomplete();
            $j(nom).unbind('.autocomplete');
            $j(nom).removeClass('ChmpAdresse');
		}
	}
}
function autoAdresseCommunaute(mode, dom,typeAdresse){
	var query = dom.value;
    var id = dom.id;
    var nom = '#' + id;
	if (mode == 'on') {
		$j(nom).attr('autocomplete', 'off');
		$j(nom).geo_autocomplete(new google.maps.Geocoder, {
			mapkey: 'ABQIAAAAEcUpeH_-08lx9hb7NX7MxRSsb9KSOEw0JqhE9lg5ZzrkRCplyBQ--QX2WntEovD01XGNgjhov2Us2g',
			minChars: 3,
			cacheLength: 1,
			width: 300,
			scroll: true,
			delay: 300,
			max:100,
			inputClass: 'ChmpAdresse',
			parse: function(_results, _status, _query){
				var _parsed = [];
					$j.each(_results, function(_key, _result){
						_parsed.push({
							data: _result,
							value: _result.formatted_address,
							result: _result.formatted_address
						});
					});
				return _parsed;
			},
			formatItem: function(_data, _i, _n, _value){
				var value = formatAdresse(_data);
				return value;
			}
		}).result(function(_event, _data){
			$j('#results').append(_data);
		});
		$j(nom).result(function(event, data, formatted){
			remplirChampAdresseCommunautes(data,nom,typeAdresse,event,formatted);
        });
	}else{
		if(mode == 'off'){
			 $j(nom).flushCache();
            $j(nom).unautocomplete();
            $j(nom).unbind('.autocomplete');
            $j(nom).removeClass('ChmpAdresse');
		}
	}
}
function autoAdresseCPVIlle(mode, dom,pays,type){
//	var pays = pays;
	if(pays == "GDLuxembourg") pays = "Luxembourg";
//	var ville = $j('#Ville_'+type).val();
	var query = dom.value;
    var id = dom.id;
    var nom = '#' + id;
//	var cp = $j('#CP_'+type).val();
 //	var chemin = "/communes/autocompletioncommunesrech/" + query;
	if (mode == 'on') {
		$j(nom).attr('autocomplete', 'off');
		$j(nom).geo_autocomplete(new google.maps.Geocoder, {
			mapkey: 'ABQIAAAAEcUpeH_-08lx9hb7NX7MxRSsb9KSOEw0JqhE9lg5ZzrkRCplyBQ--QX2WntEovD01XGNgjhov2Us2g',
			selectedFirst: true,
			minChars: 3,
			cacheLength: 1,
			width: 300,
			scroll: true,
//			scrollHeight: 600,
			delay: 300,
			max:100,
			extraParams:{
				pays: pays
			},
			inputClass: 'ChmpAdresse',
			parse: function(_results, _status, _query){
				time = 0;
				var _parsed = [];
					$j.each(_results, function(_key, _result){
						if (time == 0) {
							premierAuto =  _result;
							time = 1;
						}
						_parsed.push({
							data: _result,
							value: _result.formatted_address,
							result: _result.formatted_address
						});
						
					});
				return _parsed;
			},
			formatItem: function(_data, _i, _n, _value){
				var value = formatAdresse(_data);
				if(value != false)
					return value;
			}
		}).result(function(_event, _data){
			$j('#results').append(_data);
		});
		$j(nom).result(function(event, data, formatted){
			remplirChampAdresse(data,type);
        });
		$j(nom).blur(function() {
			if (premierAuto) {
				remplirChampAdresse(premierAuto,type);
				premierAuto = undefined;
			}
		});
	}else{
		if(mode == 'off'){
			 $j(nom).flushCache();
            $j(nom).unautocomplete();
            $j(nom).unbind('.autocomplete');
            $j(nom).removeClass('ChmpAdresse');
		}
	}
}
function remplirChampAdresse(data,type){
	var adresse = "";
	$j('#Lat_'+type).val(data.geometry.location.lat());
	$j('#Lon_'+type).val(data.geometry.location.lng());
	$j.each(data.address_components, function(i, _item){
		if (_item.types[0] == 'country') {
			$j('#Pays_'+type).val(_item.long_name);
		}
		
		if (_item.types[0] == 'locality') {
			$j('#Ville_'+type).val(_item.long_name);
		}
		
		if (_item.types[0] == "postal_code") {
			$j('#CP_'+type).val(_item.long_name);
		}
		/*
		if (_item.types[0] == "administrative_area_level_2") {
		}
		*/
		if (_item.types[0] == "street_number") {
			adresse = _item.long_name + " ";
		}
		if (_item.types[0] == "route") {
			adresse += _item.long_name;
		}
	});
	$j('#Adresse_'+type).val(adresse);
	$j('#ChmpAdresse'+type).val(data.formatted_address);
	time = 0;
}
function formatAdresse(_data){
	var ville = cp =adresse = pays = departement = '';
	var retour = "";
	$j.each(_data.address_components, function(i, _item){
		if (_item.types[0] == 'locality') {
			ville = _item.long_name;
		}
		if (_item.types[0] == "postal_code") {
			cp = _item.long_name;
		}
		if (_item.types[0] == "street_number") {
			adresse = _item.long_name + " ";
		}
		if (_item.types[0] == "route") {
			adresse += _item.long_name;
		}
		if (_item.types[0] == "country") {
			pays = _item.long_name;
		}
		if (_item.types[0] == "administrative_area_level_2") {
			departement = _item.short_name;
		}
	});
	if(adresse != '')
		retour = adresse + ', ';
	if(cp != '')
		retour += cp +', ';
	if(ville != '')
		retour += ville +', ';
	if(departement != '')
		retour += departement + ', ';
	if(pays != '')
		retour += pays;
	if(ville != '')
		return retour;
	else
		return false;
}
function remplirChampAdresseCommunautes(data,nom,type,event,formatted){
	var adresse = ''; 
	$j('#HRequeteur_Lat_'+type).val(data.geometry.location.lat());
	$j('#HRequeteur_Lon_'+type).val(data.geometry.location.lng());
	$j.each(data.address_components, function(i, _item){
		if (_item.types[0] == 'locality') {
			$j('#Requeteur_Ville_'+type).val(_item.long_name);
		}
		if (_item.types[0] == "postal_code") {
			$j('#Requeteur_CP_'+type).val(_item.long_name);
		}
		if (_item.types[0] == "street_number") {
			adresse = _item.long_name + " ";
		}
		if (_item.types[0] == "route") {
			adresse += _item.long_name;
		}
		if (_item.types[0] == "country") {
			$j('#Requeteur_Pays_'+type).val( _item.long_name);
		}
	});
	$j('#Requeteur_Adresse_'+type).val(adresse);
	$j('#Requeteur_ChampAdresse'+type).val(data.formatted_address);
}

function remplirChampAdresseRequeteur(data,nom,type,event,formatted){
	var adresse = ''; 
	$j('#HRequeteur_Lat_'+type).val(data.geometry.location.lat());
	$j('#HRequeteur_Lon_'+type).val(data.geometry.location.lng());
	$j.each(data.address_components, function(i, _item){
		if (_item.types[0] == 'locality') {
			$j('#Requeteur_Ville_'+type).val(_item.long_name);
		}
		if (_item.types[0] == "postal_code") {
			$j('#Requeteur_CP_'+type).val(_item.long_name);
		}
		if (_item.types[0] == "street_number") {
			adresse = _item.long_name + " ";
		}
		if (_item.types[0] == "route") {
			adresse += _item.long_name;
		}
		if (_item.types[0] == "country") {
			$j('#Requeteur_Pays_'+type).val( _item.long_name);
		}
	});
	$j('#Requeteur_Adresse_'+type).val(adresse);
	$j('#Requeteur_Champ_Adresse'+type).val(data.formatted_address);
	$j('#Requeteur_Champ_Adresse'+type).removeClass("error").addClass('valid').blur();
}

function gotoDetailTrajet(item,href){
	gotoUrl('trajet',href);
	/*
	$j('#referer_old').val($j('#referer').val());
	$j('#referer').val(href);
	//$j('#ui-tabs-1').html('');
	$j('#tabsAccueil').tabs("select",0);
	$j('#ui-tabs-1').load(href,function(){
		$j('#ui-tabs-1').height('auto');
		$j('#tabsAccueil').height('auto');
		$j('#ui-tabs-1').height($j('#contenu').height());
		$j('#ui-tabs-1').css('padding-bottom','10px');
	});
	*/
}
function gotoProfil(href){
	/*
	var tabs = new Array();
	tabs['/cugn/profil'] 		= 0;
	tabs['/cugn/coordonnees'] 	= 1;
	tabs['/cugn/vehicule'] 		= 2;
	tabs['/cugn/preferences'] 	= 3;
	tabs['/cugn/adressepersos'] = 4;
	tabs['/cugn/communautes'] 	= 5;
	$j('#tabsAccueil').tabs("select",1);
	$j('#ui-tabs-2').load('/cugn/monprofil/ajax/1',function(){
		setTimeout(function(){$j('#tabsProfil').tabs("select",tabs[href]);},1000);
	});
	*/
	gotoUrl('profil',href);
}
function gotoPublication(href){
	gotoUrl('publication',href);
	/*
	$j('#wanted').val(href);
	if(null !=GetCookie('wanted')) DeleteCookie('wanted');
	 SetCookie('wanted', href, exp);
	location.href = '/cugn/accueil';
	*/
}
function gotoPublicationAvancee(href){
	location.href = "/cugn/accueil#"+href;
}
function retourPagePrec(){
	gotoUrl('trajet',$j('#referer_old').val());
	/*
	if($j('#referer_old').val() !='' && $j('#referer_old').val() != $j('#referer').val())
		gotoDetailTrajet('',$j('#referer_old').val());
	else
		location.href='/cugn/accueil';
		*/
}
function gotoCommunautes(href){
	gotoUrl('communaute',href);
}
function gotoServicesPlus(href){
	gotoUrl('servicesplus',href);
	/*
		var href = '/servicesplus/'+page;
		console.log(href);
		$j('#wanted').val(href);
		DeleteCookie('wanted');
		 SetCookie('wanted', href, exp);
		 console.log(GetCookie('wanted'));
		location.href = '/servicesplus/index';
		*/
}
function gotoDetailEvt(href){
	gotoUrl('evenement',href);
}
function gotoUrl(mode,href){
	
	if(mode == 'profil'){
		var tabsProfil = new Array();
		tabsProfil['/cugn/monprofil'] 			= 0;
		tabsProfil['/cugn/coordonnees'] 	= 1;
		tabsProfil['/cugn/vehicule'] 		= 2;
		tabsProfil['/cugn/preferences'] 	= 3;
		tabsProfil['/cugn/adressesperso'] 	= 4;
		tabsProfil['/servicesplus/mesaccesmobile'] 	= 5;
		$j('#tabsAccueil').tabs("select",1);
		$j('#ui-tabs-2').load('/cugn/monprofil/ajax/1',function(){
			setTimeout(function(){$j('#tabsProfil').tabs("select",tabsProfil[href]);},1000);
		});
	}
	if(mode == 'publication'){
		/*$j('#wanted').val(href);
		if(null !=GetCookie('wanted')) DeleteCookie('wanted');
	 	SetCookie('wanted', href, exp);*/
	 	if($j('#Publication').length !=0){
			$j('#Publication').remove();
		}
			$j('#wanted').val(href);
			chargement(href);
			//location.href = '/cugn/accueil#'+href;
	}
	if(mode == 'communaute'){
		var tabsCommunaute = new Array();
		tabsCommunaute['/communaute/my']			= 0;
		tabsCommunaute['/communaute/contacts'] 	  	= 1;
		tabsCommunaute['/communaute/groupes']     	= 2;
		tabsCommunaute['/evenements/index']     	= 3;
		tabsCommunaute[''] 	= 4;
		$j('#tabsAccueil').tabs("select",2);
		$j('#ui-tabs-3').load('/communaute/index/ajax/1',function(){
			setTimeout(function(){$j('#tabsCommunaute').tabs("select",tabsCommunaute[href]);},1000);
		});
	}
	if(mode == 'servicesplus'){
		var tabsServices = new Array();
		tabsServices['/servicesplus/recapitulatif']	 = 0;
		tabsServices['/communaute/evaluations'] = 1;
		tabsServices['/servicesplus/vacances'] = 2;
		$j('#ui-tabs-1').html("");
		//$j('#ui-tabs-1').css('height', "50px").css('display', 'block');
		//$j('#tabsAccueil').after('<div id="Services"><div id="formulaire">Chargement en cours...</div></div>')
		$j('#ui-tabs-1').load('/servicesplus/index/ajax/1',function(){
			setTimeout(function(){$j('#tabsServices').tabs("select",tabsServices[href]);},1000);
		});
	}
	if(mode == 'trajet'){
		var regAccueil = /accueil/;
		if(regAccueil.test(href)){
			location.href = href;
		}
		if(null !=GetCookie('wanted')) DeleteCookie('wanted');
	 	SetCookie('wanted', href, exp);
		var referer = $j('#referer').val();
		var referer_old = $j('#referer_old').val();
		$j('#referer').val(href);
		$j('#referer_old').val(referer);
 		$j('#referer_old2').val(referer_old); 
		
		$j('#tabsAccueil').tabs("select",0);
		if($j('#referer').val()  != ''){
			$j('#ui-tabs-1').load($j('#referer').val(),function(){
				$j('#ui-tabs-1').height('auto');
				$j('#tabsAccueil').height('auto');
				$j('#ui-tabs-1').height($j('#contenu').height());
				$j('#ui-tabs-1').css('padding-bottom','10px');
			});
			if($j('#referer_old2').val() == $j('#referer').val()){
				$j('#referer_old').val('');
			}
		}else{
			$j('#referer_old2').val('');
			$j('#ui-tabs-1').load('/cugn/calendrier/ajax/1',function(){
				$j('#ui-tabs-1').height('auto');
				$j('#tabsAccueil').height('auto');
				$j('#ui-tabs-1').height($j('#contenu').height());
				$j('#ui-tabs-1').css('padding-bottom','10px');
			});
		}
		DeleteCookie('wanted');
	}
	if(mode == 'evenement'){
		$j('#wanted').val(href);
		$j('#ui-tabs-3').load(href,function(){
			$j('#ui-tabs-3').height('auto');
			$j('#tabsAccueil').height('auto');
			$j('#ui-tabs-3').height($j('#contenu').height());
			$j('#ui-tabs-3').css('padding-bottom','10px');
			$j('#tabsAccueil').tabs("select",2);
		});
	}
}
function chargement(href){
	if ($j('#wanted').val() != "" || href != '') {
		var regPublier = /publier/;
		var regListe = /liste/;
		var regDetail = /detailtrajet/;
		var regDetailEvt = /detailevenement/;
		if (regListe.test($j('#wanted').val())) {
			$j('#tabsAccueil').tabs("select",0);
			$j('#ui-tabs-1').html('');
			$j('#tabsAccueil li.ui-tabs-selected').removeClass('ui.tabs-selected');
			$j('#ui-tabs-1').load($j('#wanted').val(), function(){
				$j('#ui-tabs-1').css('height', "auto").css('display', 'block');
				if ($j('#Publication').length != 0) {
					$j('#Publication').remove();
				}
			});
			DeleteCookie('wanted');
			$j('#wanted').val('');
		}
		else 
			if (regPublier.test($j('#wanted').val())) {
				$j('#tabsAccueil').tabs("select",0);
				$j('#ui-tabs-1').html('');
				$j('#tabsAccueil li.ui-tabs-selected').removeClass('ui.tabs-selected');
				$j('#ui-tabs-1').css('height',"50px").css('display','block');
				$j('#ui-tabs-1').html('<h1>Publier mon covoiturage</h1>');
				$j('#tabsAccueil').after('<div id="Publication">Chargement en cours...</div>');
				$j('#Publication').load($j('#wanted').val(),function(){
					DeleteCookie('wanted');
					$j('#wanted').val('');
				});
				
				/*
				$j('#ui-tabs-1').html('');
				$j('#tabsAccueil li.ui-tabs-selected').removeClass('ui.tabs-selected');
				$j('#ui-tabs-1').css('height', "50px").css('display', 'block');
				$j('#ui-tabs-1').html('<h1>Publier un nouveau trajet</h1>');
				$j('#tabsAccueil').after('<div id="Publication">Chargement en cours...</div>')
				$j('#Publication').load($j('#wanted').val());
				DeleteCookie('wanted');
				$j('#wanted').val('');
				*/
			}
			else 
				if (regDetail.test($j('#wanted').val())) {
					$j('#tabsAccueil').tabs("select",0);
					if ($j('#wanted').val() != '') {
						gotoDetailTrajet('', $j('#wanted').val());
						DeleteCookie('wanted');
					}
				}
				else {
					if (regDetailEvt.test($j('#wanted').val())) {
						$j('#tabsAccueil').tabs("select",2);
						if ($j('#wanted').val() != '') {
							$j('#ui-tabs-3').html('');
							$j('#tabsAccueil li.ui-tabs-selected').removeClass('ui.tabs-selected');
							$j('#ui-tabs-3').load($j('#wanted').val(),function(){
								$j('#ui-tabs-3').height('auto');
								$j('#tabsAccueil').height('auto');
								$j('#ui-tabs-3').height($j('#contenu').height());
								$j('#ui-tabs-3').css('padding-bottom','10px');
								$j('#wanted').val('');
							});
						}
					}else{
						$j('#wanted').val('');
						var tabsProfil = new Array();
						tabsProfil['/cugn/monprofil'] 			= 0;
						tabsProfil['/cugn/coordonnees'] 	= 1;
						tabsProfil['/cugn/vehicule'] 		= 2;
						tabsProfil['/cugn/preferences'] 	= 3;
						tabsProfil['/cugn/adressesperso'] 	= 4;
						tabsProfil['/servicesplus/mesaccesmobile'] 	= 5;
						var tabsCommunaute = new Array();
						tabsCommunaute['/communaute/my']			= 0;
						tabsCommunaute['/communaute/contacts'] 	  	= 1;
						tabsCommunaute['/communaute/groupes']     	= 2;
						tabsCommunaute['/evenements/index']     	= 3;
						var tabsServices = new Array();
						tabsServices['/servicesplus/recapitulatif']	 = 0;
						tabsServices['/communaute/evaluations'] = 1;
						tabsServices['/servicesplus/vacances'] = 2;
						if(tabsProfil[href] != undefined){
							gotoProfil(href);
						}
						if(tabsCommunaute[href] != undefined){
							gotoCommunautes(href);
						}
						if(tabsServices[href] != undefined){
							gotoServicesPlus(href);
						}
					}
				}
	}else{
		t = self.setInterval("getFluxActus()", 30000);
	}
}

function validationLogin(){
    if ($j('#formLogin').valid()) {
        $j('#okLogin').hide();
        $j("#contentLoading").show();
		$j('#formLogin').append('<input type="hidden" id="ChmpCacheLogin" name="ChmpCacheLogin" value="1" />');
		$j('#formLogin').append('<input type="hidden" id="referer" name="referer" value="" />');
		$j('#formLogin #referer').val(location.href);
		$j('#motdepass').val(hex_md5($j('#motdepass').val()));
		$j.post('/inscrit/identification',$j('#formLogin').serialize(),function(data){
			if (data.success) {
				if (data.url != "covistan") {
					$j('#moncompte').fadeOut().remove();
					$j('#banniere_haut').append("<div id='moncompte_active'></div>");
					$j('#moncompte_active').load('/inscrit/logue').fadeIn();
					$j('#menu').load('/zone/menuhaut');
					location.href = unescape(data.lien);
				}else{
					location.href= '/cugn/accueil';
				}
			}else{
				alert(data.msg.text,"Oups, un petit probl&egrave;me !!");
				if(data.code == 3){
					if ($j('#motdepass').length != 0) {
						$j('#motdepass').val('');
						$j('#motdepass').focus();
					}
					if ($j('#Mdp').length != 0) {
						$j('#Mdp').val('');
						$j('#Mdp').focus();
					}
				}
			}
		},'json');
    }
}
function validationLogout(){
	$j.post('/inscrit/logout',function(data){
		var RegOk = /OK/gi;
		if (RegOk.test(data)) {
			$j('#moncompte_active').fadeOut().remove();
			$j('#banniere_haut').append("<div id='moncompte'></div>");
			$j('#moncompte').load('/inscrit/login').fadeIn();
			$j('#menu').load('/zone/menuhaut');
			
//			var RegArticle = /article/gi;
//			var RegOffre = /offre\/detail/gi;
//			var RegDemande = /demande\/detail/gi;
//			if(!RegArticle.test(location.href) || !RegOffre.test(location.href) || !RegDemande(location.href) || location.ref!='/'){
				location.href = '/';
//			}
		}
	});
}
function inscription(){
	$j('#liens_rapides').append($j("<div id='popup'></div>"));
	$j('#popup').load("/inscrit/inscription");
	$j('#popup').dialog({
        title: 'Inscription',
        bgiframe: true,
        modal: true,
//        height: 300,
        width: 450,
        closeOnEscape: false,
        draggable: false,
        resizable: false,
		buttons:{
			"OK" : function(){
				validationInscription();
			}
		},
        close: function(){
            $j('#popup').html('');
            $j(this).dialog('destroy');
        }
    });
	// $j('#popup').dialog('moveToTop');
}

function popupBienvenue(){
	$j('#liens_rapides').append($j("<div id='popup'><p>Inscrivez-vous et recevez votre smartphone.</p><img src='/images/Covivo_iphone.png' alt='Covisoft application de covoiturage' width='152' height='200' style='margin-top:5px;margin-left:105px; margin-right:105px;' /></div>"));
	$j('#popup').dialog({
        title: "Inscrivez-vous !!",
        bgiframe: true,
        modal: true,
//        height: 300,
        width: 450,
        closeOnEscape: false,
        draggable: false,
        resizable: false,
		buttons:{
			"OK" : function(){
				$j('#popup').html('');
				$j('#popup').remove();	
				$j(this).dialog('close');
			}
		},
        close: function(){
            $j('#popup').html('');
			$j('#popup').remove();			
            $j(this).dialog('destroy');
        }
    });
}

function popup(url,titre,urlredirect){
	$j('#liens_rapides').append($j("<div id='popup'></div>"));
	$j('#popup').load(url);
	$j('#popup').dialog({
        title: titre,
        bgiframe: true,
        modal: true,
//        height: 300,
        width: 450,
        closeOnEscape: false,
        draggable: false,
        resizable: false,
		buttons:{
			"OK" : function(){
				$j(this).dialog('close');
				if(urlredirect != "")
					location = urlredirect;
			}
		},
        close: function(){
            $j('#popup').html('');
			$j('#popup').remove();
            $j(this).dialog('destroy');
        }
    });
}

function majExp(){
	$j().ready(function(){
		var agent = navigator.userAgent;
    var regIE7 = /MSIE 7.0/;
	    var regIE6 = /MSIE 6.0/;
	    var regIE8 = /MSIE 8.0/;
	    var regChrome = /Chrome/;
		var regSafari = /AppleWebKit/;
	    if (!(regIE7.test(agent) || regIE6.test(agent)))
			$j('#droite').css('height',$j('#conteneur').height());
		$j('#droite').css('background','url(/images/nouvellecharte/image_fond_gauche_interne.png) left bottom no-repeat');
	});
}

function majCG54(){
	$j().ready(function(){
		var agent = navigator.userAgent;
	    var regIE7 = /MSIE 7.0/;
	    var regIE6 = /MSIE 6.0/;
	    var regIE8 = /MSIE 8.0/;
	    var regChrome = /Chrome/;
		var regSafari = /AppleWebKit/;
	    if (!(regIE7.test(agent) || regIE6.test(agent)))
			$j('#droite').css('height',$j('#conteneur').height());
		$j('#droite').css('background','url(/images/partenaires/cg54/image_fond_gauche_interne.png) left bottom no-repeat');
	});
}

function majMgel(){
	$j().ready(function(){
		var agent = navigator.userAgent;
	    var regIE7 = /MSIE 7.0/;
	    var regIE6 = /MSIE 6.0/;
	    var regIE8 = /MSIE 8.0/;
	    var regChrome = /Chrome/;
		var regSafari = /AppleWebKit/;
	    if (!(regIE7.test(agent) || regIE6.test(agent)))
			$j('#droite').css('height',$j('#contenu').height());
		$j('#droite').css('background','url(/images/partenaires/mgel/image_fond_gauche_interne.png) left bottom no-repeat');
	});
}
function majLonguyon(){
	$j().ready(function(){
		var agent = navigator.userAgent;
	    var regIE7 = /MSIE 7.0/;
	    var regIE6 = /MSIE 6.0/;
	    var regIE8 = /MSIE 8.0/;
	    var regChrome = /Chrome/;
		var regSafari = /AppleWebKit/;
	   	if (!(regIE7.test(agent) || regIE6.test(agent)))
			$j('#droite').css('height',$j('#contenu').height());
		$j('#droite').css('background','url(/images/partenaires/longuyon/fond_gauche.png) left bottom no-repeat');
	});
}
function majWtc(){
	$j().ready(function(){
		var agent = navigator.userAgent;
	    var regIE7 = /MSIE 7.0/;
	    var regIE6 = /MSIE 6.0/;
	    var regIE8 = /MSIE 8.0/;
	    var regChrome = /Chrome/;
		var regSafari = /AppleWebKit/;
	    if (!(regIE7.test(agent) || regIE6.test(agent)))
			$j('#droite').css('height',$j('#contenu').height());
		$j('#droite').css('background','url(/images/partenaires/mgel/fond_gauche.png) left bottom no-repeat');
	});
}


function refond(taille){
    //	$j('#contenu').css('height',taille);
    var RegDyn = /dynamique/gi;
    var RegMgel = /mgel/gi;
    var RegCG54 = /cg54/gi;
    var RegLonguyon = /longuyon/gi;
    var RegWtc = /wtc/gi;
    if (RegDyn.test(location.href)) {
        majExp();
    }
    else 
        if (RegMgel.test(location.href)) {
            majMgel();
        }
        else 
            if (RegCG54.test(location.href)) {
                majCG54();
            }else
	            if (RegLonguyon.test(location.href)) {
	                majLonguyon();
	            }else{
		            if (RegWtc.test(location.href)) {
						majWtc();
					}
//					else {
//						majExp();
//					}
				}
}
function miniInscription(){
    $j('#contenu').append($j("<div id='popup'></div>"));
    $j('#popup').load('/inscrit/miniidentification');
    $j('#popup').dialog({
        title: "Identifiez-vous",
        bgiframe: true,
        modal: true,
        width: 720,
        closeOnEscape: false,
        draggable: false,
        resizable: false,
        close: function(){
            $j('#popup').html('');
            $j('#popup').remove();
            $j(this).dialog('destroy');
        }
    });
}

function Miniinscription(){
	var regMgel = /mgel/gi;
	if (regMgel.test(location.href)) {
		$j('#contenu').append('<div id="popup"></div>');
		$j('#popup').html('<div>Etes-vous &eacute;tudiant?</div>');
		$j('#popup').dialog({
			title: "Identifiez-vous",
	        bgiframe: true,
	        modal: true,
	        width: 200,
			minHeight:25,
	        closeOnEscape: false,
	        draggable: false,
	        resizable: false,
	        close: function(){
	            $j('#popup').html('');
	            $j('#popup').remove();
	            $j(this).dialog('destroy');
	         }
	    });
	    $j("#popup").dialog("option", "buttons", {
	        "OUI": function(){
				inscrit();
	        },
			"NON": function(){
				location.href="http://www.covivo.eu";
			}
	    });
	}else{
		inscrit();
	}
}
function inscrit(){
	$j('#popup').load('/inscrit/miniinscription');
	$j('#popup').css('z-index',99);
    $j('#popup').dialog("option", "width", 450);
//    $j('#popup').dialog("option", "height", 700);
    $j("#popup").dialog("option", "buttons", {
        "Ok": function(){
			if ($j('#formMiniInscription').valid()) {
				var data = $j('#formMiniInscription').serializeArray();
				$j.post('/inscrit/newmini', data, function(data){
					alert(data);
					$j('#popup').dialog('destroy');
					$j('#popup').remove();
				});
			}else{
			    $j('#popup #conteneur').css('display','block');	
			}
        }
    });
	$j('#popup').dialog('option','title','Inscrivez-vous');
}

function MiniPublication(id){
}

function Minivalidation(){
    if ($j('#formIdentificationEvt').valid()) {
        var data = $j('#formIdentificationEvt').serializeArray();
        $j.post('/inscrit/loginevt', data, function(data){
            alert(data);
            $j('#popup').dialog('close');
            location.reload();
        });
    }
}

function generationproposition(origine, idorigine, recherche){
    $j.post('/propgeneree/generation', {
        origine: origine,
        idorigine: idorigine,
        recherche: recherche
    }, function(data){
        if (origine == "demande") 
            var params = "offre";
        else 
            var params = "demande";
        if (data != "0") 
            location.href = '/propgeneree/detail/params/' + data + "/params/" + params;
    });
}
