//var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
var ltie7 = ($.browser.msie && $.browser.version < 7); 
var ltie9 = ($.browser.msie && $.browser.version < 9);

//$.ifixpng('/extension/excellence/design/excellence/images/pixel.gif');

$(function(){
	/* Submit automatique pour les User ayant aucune fiche entreprise redirection vers la fiche compagnie */

	/* Vous étes pour l'espace Presse */

	$(".pmMessagesNew").submit(function(){
		
		if($(".subject").val() == "")
		{
			$("#warning").html("<p>Votre message ne contient pas d'objet.</p>");
			
			return false;
		}
		
		
		
	});
	$("#ezcoa-412_you_are_0").attr("checked","checked");

	/* Vous étes pour l'espace CA */
	$("#ezcoa-385_you_are_ca_0").attr("checked","checked");

	$(".company_file form input[type='submit']:first").click();

	$(".media_file form input[type='submit']:first").click();

	$(".BestRecent").click(function(){
		var Url = $(this).parent().find('a').attr('href');
		window.location = Url;
	});
	$(".BestComment").click(function(){
		var Url = $(this).parent().find('a').attr('href');
		window.location = Url;
	});
	$(".BestRating").click(function(){
		var Url = $(this).parent().find('a').attr('href');
		window.location = Url;
	});

	if($("#sondage").size() > 0)
	{
		var sondageID = "";
		sondageID = $("#listSondage").attr('rel');
		if(sondageID)
			$("#listSondage").ez('sondages::sondages',{sondage:sondageID});
		else
		{
			$("#listSondage").ez('sondages::sondages');
		}
	}
	var value = $("#progressbar").attr('rel');
	$("#progressbar").progressbar({
			value: value
	});

	$(".progressbar").each(function(){
		var value = $(this).attr('rel');
		$(this).progressbar({
				value: value
		});
	});


	$("#layout .ui-widget-header,.ui-progressbar-value,ui-corner-left").effect('slide',{},600);


	$(".ajax_loading")
		.bind("ajaxSend", function(){
			$(this).html("<div class='ajaxLoader'><img src='/extension/excellence/design/excellence/images/loader.gif' /><br />Chargement...</div>");
		});

	if($("#f_secteur").size() > 0) 			DirectoryController.init();
	if($("#f_secteur_techno").size() > 0) 	DirectoryController.init();
	checkboxController.init();
	headerRechInputText.init();
	ajaxController.init();
	annuaire.init();
	pageRecherche.init();
	commentaires.init();
	CheckUserContactList.init();

	/* Gestion  de la deconnexion SSO : suppression du cookie Ruc */
	$('#header_loggue .deconnexion a').click(function(){
		logout = new Image();
		logout.src="http://www.mon.oseo.fr/logout.php";
		logout.src="http://monoseo.novactive.fr/logout.php";
		logout.src="http://monoseo.novactive.com/logout.php";
		$.cookie('MonSSOseo','invalid',{path: '/', domain: '.oseo.fr'});
		$.cookie('MonSSOseo','invalid',{path: '/', domain: '.novactive.fr'});
		$.cookie('MonSSOseo','invalid',{path: '/', domain: '.novactive.com'});
	});

	$("p.alerter > a.alertMess").attr('href','#').click(function(){
		var e = $(this);
		var parentE = e.parent();
		var isCommentaire = false;
		if (e.parents('.commentaireActions').size()) isCommentaire = true;
		e.parent().ez('alertewebmaster::alertewebmaster', {nodeid:e.attr('rel')}, '', moveReponse);

		function moveReponse(data){
			//alert(isCommentaire);
			//alert(parentE);
			if (isCommentaire) parentE.appendTo(parentE.parents('.commentaireActions').siblings('.encart_bloc'));
		}

		return false;
	});
	
	
	$("span.subscription").each(function(){
		$(this).ez('abonnements::is_subscribed', {nodeid:$(this).attr('rel'),end:$(this).attr('end')}, '', '');
	});
	
	
	// Formattage de certains champs numÃ©riques (Attention a supprimer les espaces ensuite lors du traitement!!)
	$(".numberFormat").each(function() {
		formatNumberField($(this));
	}).blur(function() {
		formatNumberField($(this));
	});

	if (ltie7) {
		logoPlaceHolder.init();
		//$('img[src$=.png]').ifixpng();
		$('img[usemap]').css('border','none');
		$('input[type="radio"]').css('border','none');
		$('input[type="checkbox"]').css('border','none');
		$('input[type="file"]').css('border','none');
		$('input[type="image"]').css('border','none');
		$('.menuItem:first-child, #layout #chiffresClesListe li:first-child').css('border-top','none');
		$('#footer li:first-child').css('border-left','none');
		$('.commentaires .liste_bloc li:first-child').css('border-top','none');
		$('.actualite:first-child').css('border-top','none');
	}
	
	$('#code_selectionnee').click(function(){
		    this.select();
		});

});

	function envoyerAbonnement ( nodeID )
	{
		//$("#confirmation").show();
		//$("#abonnement_" + nodeID).hide();
		//$("#confirmation").load('/layout/set/null/notifications_excellence/addtonotification/(ContentNodeID)/' + nodeID);
		$("#abonnement_" + nodeID).load('/layout/set/null/notifications_excellence/addtonotification/(ContentNodeID)/' + nodeID);
		return false;	
	}




var CheckUserContactList = function () {

	var TempObject;

	function _init(){


		$('.actuCat').each(function(e){
			var ContactUserID = ""
			var Content = "";
			ContactUserID = $(this).attr('rel');

			if(ContactUserID) {
				jQuery.ez('ezcontact::iscontactlist',{ContactUserID:ContactUserID}, wrapper($(this)));
			}
			else
			{
				jQuery.ez('ezcontact::iscontactlist',{ContactUserID:ContactUserID}, wrapper($(this)));
			}
		});

		$('.commentaireActions').each(function(e){
			var ContactUserID = ""
			var Content = "";
			ContactUserID = $(this).attr('rel');

			if(ContactUserID) {
				jQuery.ez('ezcontact::iscontactlist',{ContactUserID:ContactUserID,TypeElmt:'comment'},wrapperComment($(this)));
			}
			else
			{
				jQuery.ez('ezcontact::iscontactlist',{ContactUserID:ContactUserID},wrapperComment($(this)));
			}
		});

	}

	function wrapper(currentElem) {
		return function (data, status) {
			currentElem.append(data.content);
		}
	}

	function wrapperComment(currentElem) {
		return function (data, status) {
			currentElem.prepend(data.content);
		}
	}


	return {init:_init};
}();

var DirectoryController = function () {
	function _init(){

		/****	Selecteur annuaire	 ****/
		//$("#f_secteur").ez("sectoractivity::sector_tradi");
		
		$("#f_secteur").change(function(){

			var PathName = location.pathname;
			var  reg = new  RegExp('[(]sector_tradi[)]/([0-9]+)', "g");
			
			if(PathName.substring((PathName.length)-1) != '/')
				var PathName = location.pathname+"/";
			
			if (PathName.indexOf('sector_tradi') == -1)
				PathName = PathName+"(sector_tradi)/"+$(this).find("[:selectbox]:selected").val();
			else
				PathName = PathName.replace(reg,'(sector_tradi)/'+$(this).find("[:selectbox]:selected").val());
			
			
			if($(this).find("[:selectbox]:selected").val() == 0)
			{
				var  reg = new  RegExp('([(]sector_tradi[)]/[0-9]+)', "g");
				
				PathName = PathName.replace(reg,'');
				
			}
			window.location.replace("http://"+location.host+PathName);

		});
		
		$("#f_secteur_techno").change(function(){

			var PathName = location.pathname;
			var  reg = new  RegExp('[(]sector_techno[)]/([0-9]+)', "g");
			
			if(PathName.substring((PathName.length)-1) != '/')
				var PathName = location.pathname+"/";
			
			if (PathName.indexOf('sector_techno') == -1)
				PathName = PathName+"(sector_techno)/"+$(this).find("[:selectbox]:selected").val();
			else
				PathName = PathName.replace(reg,'(sector_techno)/'+$(this).find("[:selectbox]:selected").val());
			
			
			if($(this).find("[:selectbox]:selected").val() == 0)
			{
				var  reg = new  RegExp('([(]sector_techno[)]/[0-9]+)', "g");
				
				PathName = PathName.replace(reg,'');
				
			}
			window.location.replace("http://"+location.host+PathName);

		});
		
		$("#region_name").change(function(){

			var PathName = location.pathname;
			var  reg = new  RegExp('[(]region[)]/([0-9]+)', "g");

			if ($(this).find("[:selectbox]:selected").val() == '0')
				window.location.replace("http://"+location.host+PathName);
			
			if(PathName.substring((PathName.length)-1) != '/')
				var PathName = location.pathname+"/";
			
			if (PathName.indexOf('region') == -1)
				PathName = PathName+"(region)/"+$(this).find("[:selectbox]:selected").val();
			else
				PathName = PathName.replace(reg,'(region)/'+$(this).find("[:selectbox]:selected").val());
			
			if($(this).find("[:selectbox]:selected").val() == 0)
			{
				var  reg = new  RegExp('([(]region[)]/[0-9]+)', "g");
				
				PathName = PathName.replace(reg,'');
				
			}
			//return false;
			
			window.location.replace("http://"+location.host+PathName);
			
		});
	}
	return {init:_init};
}();

var checkboxController = function () {
	function _init(){
		// ":not([safari])" is desirable but not necessary selector
		$('input:checkbox:not([safari])').not("#secteurActi input:checkbox").not(".engagement_perso input:checkbox").not(".userGestionGroupes input:checkbox").checkbox({empty:'/extension/excellence/design/excellence/images/empty.png'});
		$('.userGestionGroupes input:checkbox').checkbox({empty:'/extension/excellence/design/excellence/images/pm/retirerGroupe.png'});
		$('input[safari]:checkbox').checkbox({cls:'jquery-safari-checkbox', empty:'/extension/excellence/design/excellence/images/empty.png'});
		$('input:radio').checkbox({cls:'jquery-radio', empty:'/extension/excellence/design/excellence/images/empty.png'});
		//$('input:radio,input:checkbox').checkbox({empty:'/extension/excellence/design/excellence/images/empty.png'});
	}
	return {init:_init};
}();

var ajaxController = function () {
	function _init(){
		var div=$('#decouvrezMembresB .ajax_loading');
		if (div.size()>0) div.ez('membres::inscrit', '', '', function(){ gestionCarouselMembres.init();});

		var div=$('#actualiteB .ajax_loading');
		if (div.size()>0)
				div.ez('excenotif::home');

		var div=$("#actualitesLoadNotif");
		var aPost ={ajxr:"ajxr",'node_id':div.attr('rel'),class_filter_array:['actualite','company_file']};
		if (div.size()>0) div.ez('excenotif::context',aPost);

		/****	Selecteur annuaire	 ****/
		if($("#sector_tradi_annuaire").size() >0)
			$("#sector_tradi_annuaire").ez("sectoractivity::sector_tradi");
	}
	return {init:_init};
}();

var headerRechInputText = function(){
	var input, submit, label, labelText;
	function _init(){
		input = $("#homeRechercheTexte");
		submit = $("#homeRechercheSubmit");
		label = input.siblings('label');
		labelText = label.text();

		submit.click(function(){
			if (input.val() == labelText) {
				input.val('').focus();
				return false;
			}
		});

		input.each(function(){
			var elmt=$(this);
			inserLabelIntoInput(elmt.siblings('label'),elmt);
		});
	}
	return {init:_init};
}();

function inserLabelIntoInput (label,input) {
	if (!input.val() && label.text()) {
		setDefaultValue(label,input);
		input.blur(function(){
			if (input.val()=='') setDefaultValue(label,input);
		});
	}
	function setDefaultValue(label, input) {
		var labelText = label.text();
		input.val(labelText).addClass('defaultValue').one('click',function(){
			var elmt = $(this);
			if (elmt.val() == labelText) elmt.val('').removeClass('defaultValue');
			else if (elmt.val() == '') elmt.val(labelText).addClass( 'defaultValue');
		});
	}
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var annuaire = function() {

	function _init() {
		$('.item_annuaire').adjustSize();
	}

	return {init:_init};
}();

var logoPlaceHolder = function() {
	var C, L, hC, hL, mT, $$; // c : conteneur; L : logo, hC : hauteur Conteneur, hL : hauteur Logo, mT :margin-top
	function _init() {
		C = $('.logoC');
		C.each(function(){
			$$ = $(this);
			hC = $$.height();
			L = $$.find('img');
			hL = L.height();
			mT = Math.floor((hC-hL)/2);
			L.css('margin-top',mT+'px');
		});
	}
	return {init:_init};
}();

var pageRecherche = function(){

	var menuRecherche, contenuRecherche, mRH, cRH;
	function _init(){
		contenuRecherche = $('.contenuB');
		menuRecherche = $('#menuRechercheB');
		mRH = parseInt(menuRecherche.height())+40;
		cRH = parseInt(contenuRecherche.height());
		if (mRH > 300) {
			if (ltie7) contenuRecherche.css({height: (mRH+180)+'px'})
			else contenuRecherche.css({minHeight: (mRH+180)+'px'})
		}
	}

	return {init:_init};
}();

var commentaires = function(){
	var ajouter, deplier, liste, formulaire;
	function _init(){
		ajouter = $('.ajouter_commentaire');
		formulaire = $('#formComment');

		//deplier = $('.commentaires > h3');
		//liste = $('.liste_bloc');

		ajouter.click(function(){
			ajouter.hide();
			$('.subscription > .ajouter_commentaire').hide();
			formulaire.slideDown();
			return false;
		});
		//deplier.wrapInner('<a href="#" title="Afficher les commentaires" />').click(function(){liste.slideToggle(); return false;});

		if (window.location.hash.replace('#','') == 'formComment') ajouter.eq('0').click();

	}
	return {init:_init}
}();

// Nouvelle fonction jquery de retaillage de blocks
$.fn.adjustSize=function(options) {
	var settings = {
		periode: 2,
		mode: 'height',
		minHeight: 0,
		minWidth: 0
	};
	var ltie7 = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent);
	if (options) {
		jQuery.extend(settings, options);
	}
	var totalSize = $(this).size();
	var nbPeriodes = Math.ceil(totalSize/settings.periode);
	var index = 0;
	if (settings.mode == 'height' || settings.mode == 'both') {
		var maxTotalHeightArray = new Array();
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			if (!maxTotalHeightArray[blockId]) maxTotalHeightArray[blockId]=0;
			var blockTotalHeight = $(this).height();
			if (blockTotalHeight > maxTotalHeightArray[blockId]) {
				if (settings.minHeight && settings.minHeight > blockTotalHeight) blockTotalHeight = settings.minHeight;
				maxTotalHeightArray[blockId] = blockTotalHeight;
			}
			index++;
		});
		var index = 0;
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			var blockComputedHeight = maxTotalHeightArray[blockId]+1;
			if (ltie7) $(this).height(blockComputedHeight+'px');
			else $(this).css('minHeight',blockComputedHeight+'px');
			index++;
		});
	}
	if (settings.mode == 'width' || settings.mode == 'both') {
		var maxTotalWidthArray = new Array();
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			if (!maxTotalWidthArray[blockId]) maxTotalWidthArray[blockId]=0;
			var blockTotalWidth = $(this).width() ? $(this).width() : $(this).attr('offsetWidth') ;
			if (blockTotalWidth > maxTotalWidthArray[blockId]) {
				if (settings.minWidth && settings.minWidth > blockTotalHeight) blockTotalWidth = settings.minWidth;
				maxTotalWidthArray[blockId] = blockTotalWidth;
			}
			index++;
		});
		var index = 0;
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			var blockComputedWidth = maxTotalWidthArray[blockId];
			if (ltie7) $(this).width(blockComputedWidth+'px');
			else $(this).css('minWidth',blockComputedWidth+'px');
			index++;
		});
	}

	return this;
};

function formatNumberField(input) {
	if (input.val() != "") {
		var newVal = number_format(myStr_replace(',','.',myStr_replace(' ','', input.val())), 0, ',', ' ');
		if (newVal != "NaN")
			input.val(newVal);
	}
}

function number_format(a, b, c, d) {
	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a + '';
	f = e.split('.');
	if (!f[0]) {
		f[0] = '0';
	}
	if (!f[1]) {
		f[1] = '';
	}
	if (f[1].length < b) {
		g = f[1];
		for (i=f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j+=3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '' : c;
	return f[0] + c + f[1];
}

function myStr_replace(recherche,rep,text) {
	while (text.search(recherche)!=-1)
		text = text.replace(recherche,rep);
	return text;
}

