
//Raccourci pour des messages d'alerte
function alert(message,title,width,height,className,nomBouton) {
  if (!className) 
    jQuery('#' + 'TB_window').removeClass('success_message');
	var title = title || "Compte";
	var width = width || 300;
	var height = height || 120;
	var url = '#' + 'TB_inline?height=' + height + '&width=' + width + '&inlineId=messageAlert';
  var nomBouton = nomBouton || 'fermer';
	if (!(jQuery('#' + 'TB_window').length))
		jQuery('#messageAlert').html("<div class='error_message " + nomBouton + "'>"
			+ message
			+ '<div id=\'cadre_close\' style=\'position:absolute;bottom:2px;right:2px;text-align:left\'>'       //  le bottom et right est d&eacute;fini de fa&eacute;on a ce qu'on ait au moins 16px -- sinon on a des scrollbar sous FF car le submit semble double
			+ '<a href=\'#\' onclick=\'tb_remove();return false;\' id=\'close_popup\'></a>'
			+ '</div>'
			+ "</div>");
	
	tb_show(title,url,'false');

	if (className!='') {
    jQuery('#' + 'TB_window').addClass(className);
  }

  jQuery('#fakeInput').focus(); //  pour que les formulaires erron&eacute;s ne gardent pas le focus (touche "Enter" -> envoi) 

	return false;
}

function videoDemo(urlVideo, title, message, width, height) {
jQuery('#' + 'TB_window').removeClass('success_message');
 var title = title || "D&eacute;mo";
 if ($.browser.mozilla) {
   var width2 = width ;
   var height2 = height ;
 }
 else {
   var width2 = (parseInt(width) + 80);
   var height2 = (parseInt(height) + 20);
 }
 var url = '#' + 'TB_inline?height=' + height + '&width=' + width + '&video=1&inlineId=messageAlert';
 jQuery('#messageAlert').html("<iframe frameborder='0' hspace='0' src='"+urlVideo+"' id='TB_iframeContent' name='iFrameName' onload='tb_showIframe()' style='width:"+width2+"px;height:"+height2+"px;' > </iframe>");
tb_show(title,url,'false',message);
jQuery('#TB_ajaxContent').height(height-83);
}

function successMessage(message,title,width,height) {
  title = title || 'Information';
  alert(message,title,width,height,'success_message');
  return false;
}

function confirm(msg,callback, title, width, height) {
  var title = title || MSG_DEFAULT_CONFIRM;
  var width = width || 300;
  var height = height || 120;
  var url = '#' + 'TB_inline?height=' + height + '&width=' + width + '&inlineId=messageAlert';
  var texte = "<div class='error_message'>";
	texte	= texte + msg;
	texte = texte + '<div style=\'position:absolute;bottom:2px;right:2px;text-align:left\'>';
	texte = texte + '<div class="notconfirm" style="float:right"><a class=\'right\' href="#" onclick="tb_remove();return false" id="notconfirm"></a></div>';
	texte = texte + '<div class="confirmed"  style="margin-right:10px; float:right"><a class=\'right\' href="#" id="confirmed"></a></div>';
	texte = texte + '</div>';
	texte = texte + "</div>";
	jQuery('#messageAlert').html(texte);
	tb_show(title,url,'false');
  jQuery('#confirmed')
      .click(function(){
        if (typeof callback == 'string') 
          window.location.href = callback;
        else {
          tb_remove();
          callback();
        }
      });
  if ($.browser.msie) window.scroll(0,0);
  jQuery('#fakeInput').focus();
 	return false;
}

// V&eacute;rification d'un mail
function isEmailValid(str) {
  	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
  	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
    return (!reg1.test(str) && reg2.test(str)); 
}

// Fonction g&eacute;n&eacute;rique qui v&eacute;rifie la validit&eacute; d'un formulaire
function check_submit(formId){
	formId = formId || this;
	var correct=true;
	var message='';
	var height = 0;

  jQuery("input, textarea").each(function() {
    jQuery(this).val($.trim(jQuery(this).val()));
  });
  jQuery("input").removeClass('empty_error');
	jQuery("select").removeClass('empty_error');
	jQuery("textarea").removeClass('empty_error');
	
	if (jQuery(".obligatoire[@value='']",formId).length) {
		jQuery(".obligatoire[@value='']",formId).each(function() {
			if (!jQuery(this).attr('disabled')) {
				correct = false;
			    jQuery(this).addClass('empty_error');
			}
		})
		if (correct==false) {
		    message += "<li>" + MSG_CHAMPS_OBLIGATOIRES + "</li>\n";
			height += 15;
		} 
  }

	/* un champ est obligatoire si un autre a une certaine valeur */
  if (jQuery("input.conditionne", formId).length) {
		var condition = jQuery(".conditionne", formId).attr('rel').split(":");
		if ((jQuery(".conditionne", formId).val() == condition[0]) && !jQuery("#" + condition[1]).val()) {
      if (correct) {
		  message += "<li>" + MSG_CHAMPS_OBLIGATOIRES + "</li>\n";
		  height += 15;
	    }
      jQuery("#" + condition[1]).addClass('empty_error');
      correct=false;
    }
  }

  if (jQuery("input.email", formId).length) {
  	var str = jQuery("input.email", formId).val();
  	if (!isEmailValid(str)) {
  		message += "<li>" + MSG_BAD_EMAIL + "</li>\n";
		height += 15;
  		correct=false;
      jQuery(formId).find("input.email").addClass('empty_error');
  	} 
  }
  
  if (jQuery("input.password", formId)) {
    var verif = jQuery("input.password", formId).attr('rel');
    if (jQuery("input.password", formId).val() != jQuery("#" + verif).val()) {
      message += "<li>" + MSG_DIFFERENT_PASSWD + "</li>\n";
	  height += 2*15;
      jQuery(formId).find("input.password").addClass('empty_error');
      jQuery("#" + verif).addClass('empty_error');
      correct=false;
    }
  }

  // Conseiller a un ami
  if (jQuery('#msg').val() == "Saisissez votre texte ici.") {
    jQuery("#msg").addClass('empty_error');
  }
  
  if (jQuery("#emailsAmis").length){
  	// check all email adresses
  	// replace all \n by ;
  	var str = new String(jQuery("#emailsAmis").val());
  	str = str.replace(/\n/g, ";");
  	var emails = str.split(";");
  
  	var i;
  	var tempList = new Array();
    var errorEmails=false;
    
  	for (i = 0; i < emails.length; i++)
  	{
  		var check = $.trim(emails[i]);
  
  		if(check != "")
  		{	
  			if(!isEmailValid(check))
  			{
  				errorEmails=true;
  			} else {
  				tempList.push(check);
  			}
  		}
  	}
  	if (errorEmails) {
		message += '<li>' + MSG_SOME_BAD_EMAIL + '</li>';
		height += 15;
		jQuery("#emailsAmis").addClass('empty_error');      
    }
    if(tempList.length > NB_MAX_EMAILS)
  	{
  		message += '<li>' + MSG_LIMIT_EMAILS + '</li>';
		height += 15;
		jQuery("#emailsAmis").addClass('empty_error');	
  	}
    if (!message) jQuery("#emailsAmis").val(tempList.join(";"));
  }    


	if (message) {
    height += 15; // Pour la ligne de texte &eacute; ins&eacute;rer 
		height += 90; // Hauteur par d&eacute;faut sans ligne de texte
		alert(MSG_START_ALERT + '<ul>' + message + '</ul>' + MSG_END_ALERT
        ,"Saisie",300,height);
	return false;
	}
  
  return true;
}

jQuery().ready(function() {
  jQuery('input:image.btn_submit').hover(function(){
  var temp = new Array();
  var src = jQuery(this).attr('src');
	var test_debord = src.indexOf('_hover.');  // Ca arrive parfoit
	if (test_debord != -1) {
		jQuery(this).attr('orig',test_debord[0]+'.'+test_debord[1]);
	} else {
  	jQuery(this).attr('orig',src);
  	temp = src.split('.');
  	jQuery(this).attr('src',temp[0]+'_hover.'+temp[1]);
    }
  },function(){
  	jQuery(this).attr('src',jQuery(this).attr('orig'));
    }
  );
  
  jQuery('form[class!=dynamic]').bind('submit',function(){return check_submit(this);});
});


/**
 * SearchHighlight plugin for jQuery
 * 
 * Thanks to Scott Yang <http://scott.yang.id.au/>
 * for the original idea and some code
 *    
 * @author Renato Formato <renatoformato@virgilio.it> 
 *  
 * @version 0.33
 *
 *  Options
 *  - exact (string, default:"exact") 
 *    "exact" : find and highlight the exact words.
 *    "whole" : find partial matches but highlight whole words
 *    "partial": find and highlight partial matches
 *     
 *  - style_name (string, default:'hilite')
 *    The class given to the span wrapping the matched words.
 *     
 *  - style_name_suffix (boolean, default:true)
 *    If true a different number is added to style_name for every different matched word.
 *     
 *  - debug_referrer (string, default:null)
 *    Set a referrer for debugging purpose.
 *     
 *  - engines (array of regex, default:null)
 *    Add a new search engine regex to highlight searches coming from new search engines.
 *    The first element is the regex to match the domain.
 *    The second element is the regex to match the query string. 
 *    Ex: [/^http:\/\/my\.site\.net/i,/search=([^&]+)/i]        
 *            
 *  - highlight (string, default:null)
 *    A jQuery selector or object to set the elements enabled for highlight.
 *    If null or no elements are found, all the document is enabled for highlight.
 *        
 *  - nohighlight (string, default:null)  
 *    A jQuery selector or object to set the elements not enabled for highlight.
 *    This option has priority on highlight. 
 *    
 *  - keys (string, default:null)
 *    Disable the analisys of the referrer and search for the words given as argument    
 *    
 */

(function($){
  jQuery.fn.SearchHighlight = function(options) {
    var ref = options.debug_referrer || document.referrer;
    if(!ref && options.keys==undefined) return this;
    
    SearchHighlight.options = $.extend({exact:"exact",style_name:'hilite',style_name_suffix:true},options);
    
    if(options.engines) SearchHighlight.engines.unshift(options.engines);  
    var q = options.keys!=undefined?options.keys.toLowerCase().split(/[\s,\+\.]+/):SearchHighlight.decodeURL(ref,SearchHighlight.engines);
    if(q && q.join("")) {
      SearchHighlight.buildReplaceTools(q);
      return this.each(function(){
        var el = this;
        if(el==document) el = jQuery("body")[0];
        SearchHighlight.hiliteElement(el, q); 
      })
    } else return this;
  };    

  var SearchHighlight = {
    options: {},
    regex: [],
    engines: [
    [/^http:\/\/(www\.)?google\./i, /q=([^&]+)/i],                            // Google
    [/^http:\/\/(www\.)?search\.yahoo\./i, /p=([^&]+)/i],                     // Yahoo
    [/^http:\/\/(www\.)?search\.msn\./i, /q=([^&]+)/i],                       // MSN
    [/^http:\/\/(www\.)?search\.live\./i, /query=([^&]+)/i],                  // MSN Live
    [/^http:\/\/(www\.)?search\.aol\./i, /userQuery=([^&]+)/i],               // AOL
    [/^http:\/\/(www\.)?ask\.com/i, /q=([^&]+)/i],                            // Ask.com
    [/^http:\/\/(www\.)?altavista\./i, /q=([^&]+)/i],                         // AltaVista
    [/^http:\/\/(www\.)?feedster\./i, /q=([^&]+)/i],                          // Feedster
    [/^http:\/\/(www\.)?search\.lycos\./i, /q=([^&]+)/i],                     // Lycos
    [/^http:\/\/(www\.)?alltheweb\./i, /q=([^&]+)/i],                         // AllTheWeb
    [/^http:\/\/(www\.)?technorati\.com/i, /([^\?\/]+)(?:\?.*)$/i]           // Technorati
    ],
    subs: {},
    decodeURL: function(URL,reg) {
      URL = decodeURIComponent(URL);
      var query = null;
      $.each(reg,function(i,n){
        if(n[0].test(URL)) {
          var match = URL.match(n[1]);
          if(match) {
            query = match[1].toLowerCase();
            return false;
          }
        }
      });
      
      if (query) {
      query = query.replace(/(\'|")/, '\$1');
      query = query.split(/[\s,\+\.]+/);
      }
      
      return query;
    },
		regexAccent : [
      [/[\xC0-\xC5\u0100-\u0105]/ig,'a'],
      [/[\xC7\u0106-\u010D]/ig,'c'],
      [/[\xC8-\xCB]/ig,'e'],
      [/[\xCC-\xCF]/ig,'i'],
      [/\xD1/ig,'n'],
      [/[\xD2-\xD6\xD8]/ig,'o'],
      [/[\u015A-\u0161]/ig,'s'],
      [/[\u0162-\u0167]/ig,'t'],
      [/[\xD9-\xDC]/ig,'u'],
      [/\xFF/ig,'y'],
      [/[\x91\x92\u2018\u2019]/ig,'\'']
    ],
    matchAccent : /[\x91\x92\xC0-\xC5\xC7-\xCF\xD1-\xD6\xD8-\xDC\xFF\u0100-\u010D\u015A-\u0167\u2018\u2019]/ig,  
		replaceAccent: function(q) {
		  SearchHighlight.matchAccent.lastIndex = 0;
      if(SearchHighlight.matchAccent.test(q)) {
        for(var i=0,l=SearchHighlight.regexAccent.length;i<l;i++)
          q = q.replace(SearchHighlight.regexAccent[i][0],SearchHighlight.regexAccent[i][1]);
      }
      return q;
    },
    escapeRegEx : /((?:\\{2})*)([[\]{}*?|])/g, //the special chars . and + are already gone at this point because they are considered split chars
    buildReplaceTools : function(query) {
        var re = [], regex;
        $.each(query,function(i,n){
            if(n = SearchHighlight.replaceAccent(n).replace(SearchHighlight.escapeRegEx,"$1\\$2"))
              re.push(n);        
        });
        
        regex = re.join("|");
        switch(SearchHighlight.options.exact) {
          case "exact":
            regex = '\\b(?:'+regex+')\\b';
            break;
          case "whole":
            regex = '\\b\\w*('+regex+')\\w*\\b';
            break;
        }    
        SearchHighlight.regex = new RegExp(regex, "gi");
        
        $.each(re,function(i,n){
            SearchHighlight.subs[n] = SearchHighlight.options.style_name+
              (SearchHighlight.options.style_name_suffix?i+1:''); 
        });       
    },
    nosearch: /s(?:cript|tyle)|textarea/i,
    hiliteElement: function(el, query) {
        var opt = SearchHighlight.options, elHighlight, noHighlight;
        elHighlight = opt.highlight?jQuery(opt.highlight):jQuery("body"); 
        if(!elHighlight.length) elHighlight = jQuery("body"); 
        noHighlight = opt.nohighlight?jQuery(opt.nohighlight):jQuery([]);
                
        elHighlight.each(function(){
          SearchHighlight.hiliteTree(this,query,noHighlight);
        });
    },
    hiliteTree : function(el,query,noHighlight) {
        if(noHighlight.index(el)!=-1) return;
        var matchIndex = SearchHighlight.options.exact=="whole"?1:0;
        for(var startIndex=0,endIndex=el.childNodes.length;startIndex<endIndex;startIndex++) {
          var item = el.childNodes[startIndex];
          if ( item.nodeType != 8 ) {//comment node
  				  //text node
            if(item.nodeType==3) {
              var text = item.data, textNoAcc = SearchHighlight.replaceAccent(text);
              var newtext="",match,index=0;
              SearchHighlight.regex.lastIndex = 0;
              while(match = SearchHighlight.regex.exec(textNoAcc)) {
                newtext += text.substr(index,match.index-index)+'<span class="'+
                SearchHighlight.subs[match[matchIndex].toLowerCase()]+'">'+text.substr(match.index,match[0].length)+"</span>";
                index = match.index+match[0].length;
              }
              if(newtext) {
                //add the last part of the text
                newtext += text.substring(index);
                var repl = $.merge([],jQuery("<span>"+newtext+"</span>")[0].childNodes);
                endIndex += repl.length-1;
                startIndex += repl.length-1;
                jQuery(item).before(repl).remove();
              }                
            } else {
              if(item.nodeType==1 && item.nodeName.search(SearchHighlight.nosearch)==-1)
                  SearchHighlight.hiliteTree(item,query,noHighlight);
            }	
          }
        }    
    }
  };
})(jQuery)
