function reloadCaptcha() {
	if ( jQuery('#capaimg').length  )
	{
		var currentSRC = jQuery('#capaimg').attr( 'src' );
		var concat = "?";
		if ( currentSRC.indexOf("?") >= 0 )
			concat = "&";
		jQuery('#capaimg').attr( 'src', jQuery('#capaimg').attr( 'src' )+concat+'r=' + Math.random() );
	}
}

function autoHeight(expandContainer) {
    try {
        if (expandContainer) {
            window.onresize = function() {
                autoHeight(expandContainer);
            }
        }
        var window_height = jQuery(window).height();
        var wrap_container_height = jQuery("#content").outerHeight() + parseInt(jQuery("#wrap-container").css("margin-top"));
        var wrap_footer_height = jQuery("#wrap-footer").outerHeight() || 0;
        var wrap_footer_bottom = parseInt(jQuery("#wrap-footer").css("margin-bottom"));
        var wrap_page_ref_height = jQuery("#wrap-page-ref").outerHeight() || 0;

        if (expandContainer) {
            if ((window_height - wrap_container_height - wrap_footer_bottom) > wrap_footer_height + wrap_page_ref_height) {
                push_height = (window_height - wrap_container_height - wrap_footer_bottom - wrap_page_ref_height);
            } else {
                push_height = (wrap_footer_height + wrap_page_ref_height);
            }
        } else {
            push_height = (wrap_footer_height);
        }
        document.getElementById('push').style.height = push_height + "px";
        document.getElementById('wrap-container').style.marginBottom = (0 - wrap_footer_height) + "px";
    }
    catch (e) {}
};

function validateFields( prefix, method, location, message  )
{
	startLoading();
    paramPrefix = "param_";
	nPSkip = paramPrefix.length;
	nSkip = prefix.length + 1;
	inputs = [];
	arrParams = [];

	if ( typeof message == "undefined" )
		message = false;

	jQuery("[id^='"+prefix+"_']").each(function(){
			var name = this.id.substr( nSkip );
			if ( name.substr( 0, nPSkip ) == paramPrefix )
				arrParams.push({ name:name.substr( nPSkip ), value:jQuery(this).val() });
			else
				inputs.push( jQuery.param({ name:name, value: jQuery(this).val() }) );
	});

	data = { method: method, 'inputs[]': inputs };
	for( i=0; i<arrParams.length; i++ )
		eval( "data." + arrParams[i].name + "=\"" + arrParams[i].value + "\";" );

	callAjax( data, function( result ) {
		if ( result["valid"] )
		{
				if ( message )
				{
					window.top.jAlert( "<p>" + message + "</p>", txtThankYou, function(){
						if ( typeof location != "undefined" && location != "" )
							document.location = location;
					} );
				}
				else
				if ( typeof location != "undefined" )
				{
					document.location = location;
				}

		}
		else
		{
			reloadCaptcha();
			var errMsg = "";
			
			for ( var i=0; i < result['err'].length; i++ )
			{
				if ( result["err"][i] )
				{
					errMsg += result["err"][i] + "<br />";
				}
			}
			 window.top.jError( errMsg, txtError );
		}
		endLoading();
	});
}

function setStyles()
{

    jQuery('input[type="checkbox"]').addClass('input-checkbox');

    jQuery('input[type="radio"]').addClass('input-radio');

	jQuery('input[type="button"], input[type="reset"], input[type="submit"]').each(function() {

        jQuery(this).addClass("input-button")

                    .mouseover(function() {
                        jQuery(this).addClass('hover');
                    })

                    .mouseout(function() {
                        jQuery(this).removeClass('hover');
                    })
                    .click(function(){
                        jQuery(this).blur();
                    });
    });

    jQuery('input[type="text"], input[type="password"], textarea').each(function() {

        var default_value = ( jQuery(this).attr("alt") ) ? jQuery(this).attr("alt") : jQuery(this).val();

        jQuery(this).addClass('input-text')

                    .focus(function() {
                        jQuery(this).addClass('focus');
                        if ( (jQuery(this).val().toLowerCase() == default_value.toLowerCase()) && jQuery(this).hasClass('placeholder') ) {
                            jQuery(this).val('');
                        }
                    })

                    .blur(function() {
                        jQuery(this).removeClass('focus');
                        if ((jQuery(this).val() == '') && jQuery(this).hasClass('placeholder')) {
                            jQuery(this).val(default_value);
                        }
                    });
    });

    jQuery('.button1')
        .mouseover(function() {
            jQuery(this).addClass('button1-hover');
        })
        .mouseout(function() {
            jQuery(this).removeClass('button1-hover');
        });
        
    jQuery('.input1')
        .focus(function() {
            jQuery(this).addClass('input1-hover');
        })
        .blur(function() {
            jQuery(this).removeClass('input1-hover');
        });
}

/* Ajax
------------------------------------------------------------------------------*/
var xmlHttp;
var WindowPopUp;

function initAjax() {
    try {
		xmlHttp=new XMLHttpRequest();
	}
    catch (e) {
	    try {
		    xmlHttp=new ActiveXObject('Msxml2.XMLHTTP');
	    }
	    catch (e) {
		    try {
			    xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch (e) {
		        return false;
			}
	    }
	}
    return true;
}

function makeHttpRequest(scriptpath,urlmethod) {
    if (!initAjax()) {
	    jAlert.alert('Votre navigateur ne supporte pas AJAX!');
		return false;
	}
    strString = "";
    xmlHttp.open(urlmethod,scriptpath,true);
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                strString = xmlHttp.responseText.toString();
            } else {
                strString = "Page: " + scriptpath + " - " + xmlHttp.status + ": " + xmlHttp.statusText.toString();
            }
        }
        processResult(strString, xmlHttp.readyState);
    }
    xmlHttp.send(null);
}

/* Basics
------------------------------------------------------------------------------*/
function checkEmail(txtEmail)
{
	strMail = txtEmail.replace(/ /g,"");
		regex =
/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
	if (regex.test(strMail)) {
			return true;
	}	else {
			return false;
	}
}

function isFloat(objText) {
	var floatPoint = false;
		if (objText.charAt(0) == "." || objText.charAt(0) == ",")
		return false;
		for (i=0; i < objText.length; i++) {
			if (!isDigit(objText.charAt(i))) {
			if (!floatPoint && (objText.charAt(i) == "." || objText.charAt(i) == ","))
			floatPoint = true;
			else
			return false;
			}
		}
		return true;
}

function checkFirstLetter(strString) {
		letter = strString.charAt(0);
		switch (letter) {
				case "e":
				case "a":
				case "i":
				case "o":
				case "u":
				case "é":
					return true;
				break;
				default:
					return false;
				break;
		}
}

function RenameURL( url )
{
	url = url.replace( / /g, "-" );
	url = url.replace( /\&#039/g, "-" );
	url = url.replace( /\&amp;/g, "et" );
	url = url.replace( /\&/g, "et" );
	url = url.replace( /\.,/g, "-" );
	url = url.replace( /[éêëè]/g, "e" );
	url = url.replace( /[ÈÉÊË]/g, "E" );
	url = url.replace( /[äãåâáà]/g, "a" );
	url = url.replace( /[óòöô]/g, "o" );
	url = url.replace( /[úùûü]/g, "u" );
	url = url.replace( /[~;\/':%\+\^\$\*€-]/g, "-" );
	url = url.replace( /[^a-z0-9A-Z+]/ig, "-" );
	while ( url != url.replace( /--/ig, "-" ) )
			url = url.replace( /--/ig, "-" );
			
	return url;
}
function isDigit (c) {
	return ((c >= "0") && (c <= "9"));
}

function doResetById(formId) {
	form = document.getElementById(formId);
	form.reset();
}

function isNumber(param) {
	strLocalString = param.replace(/ /g, "");
	for (t = 0; t < strLocalString.length; t++) {
		if (!isDigit(strLocalString.charAt(t))) {
			return false;
		}
	}
	return true;
}

function doFormSubmit(objForm, strFormTarget, strFormAction) {
/*
attributes will be read fron id value
your id should be of the form id="x/y/z", if not then the corresponding element won't be checked

where:
  x = "mandatory"(if the lement is mandatory ) or any other string if you do not want that element to be mandatory(try to use "notmandatory"..estetics)
  y = the element type  = email, checkbox, text, number, select, password
  z = an error message to be displayed if the validation process for that field has failed

copy/paste this code into a "button" tag to use for submitting a form:
 -=  onClick="doFormSubmit(this.form)"  =-
*/

	arrValidation = Array();
  	arrRejected = Array();
    var arrVisited = new Array();
	txtErr = "";
	strTmp = "";
	arrElements = objForm.elements;
	for(var i=0;i<arrElements.length;i++) {
	  obj = arrElements[i];
	  if(jQuery.inArray(obj.name, arrVisited) != -1) continue;

	  arrVisited.push(obj.name);

      arrObjOptions = obj.id.split("---");
      if ((arrObjOptions.length == 3)) {

        if (arrObjOptions[0] == "mandatory")
          strTmp = validateObjectByType(obj, arrObjOptions[1], arrObjOptions[2].replace(/_/g," "), false);
        else
          strTmp = validateObjectByType(obj, arrObjOptions[1], arrObjOptions[2].replace(/_/g," "), true);

    	if(strTmp != "") {
    	    txtErr += strTmp;
    	    arrRejected[arrRejected.length] = obj;
        }
      }
  }

   if((objForm.elements["capa"] != null && (document.getElementById("capa").value.replace(/ /g,"") == ""))){
				txtErr += "Vous devez remplir le code de s&eacute;curit&eacute;!\r\n";

             arrRejected[arrRejected.length] = objForm.elements["capa"];
	}
	if(txtErr != "") {

		parent.jAlert( txtErr,"Erreur");
//	 	arrRejected[0].focus();
	} else {
        if(strFormTarget.replace(/ /g,"") != "")
				objForm.setAttribute("target",strFormTarget.replace(/ /g,""));
		if(strFormAction.replace(/ /g,"") != "")
				objForm.setAttribute("action",strFormAction.replace(/ /g,""));
		objForm.submit();
	}


}

function validateObjectByType(obj, strType, strIdent, bTypeOnly) {
		bErr = false;
		errType = -1;
		strErrorMsg = "";

    		if(!bTypeOnly) {
    			objVal = obj.value;
    			if(objVal.replace(/ /g,"") == "") {
    					bErr = true;
    					errType = 0;
    			}
		    }

			if(strType == "email") {
					objVal = obj.value.replace(/ /g,"");
					if( !bTypeOnly || objVal != "") {
             if(objVal == "") {
              errType = 0;
             } else if(!checkEmail(objVal)) {
									errType = 1;
							}
					}
			} else if(strType == "text")  {
					objVal = obj.value;

					if(objVal.replace(/ /g,"") == "") {
					  if (!bTypeOnly)
							errType = 0;
					}
			} else if(strType == "checkbox" || strType == "radio") {
				   //	if(!obj.checked) {

                   if(!bTypeOnly) {
				   	if(typeof($("input[name='"+obj.name+"']:"+strType+":checked").val()) == 'undefined') {
							errType = 0;
					}
                   }
			} else if(strType == "select")  {
					objVal = obj.value;
					if(objVal.replace(/ /g,"") == "" || parseInt(objVal.replace(/ /g,"")) == 0) {
							errType = 1;
					}
			} else if(strType == "number") {
					objVal = obj.value;
          if(!bTypeOnly) {
             if(objVal == "") {
              errType = 0;
             } else 	if(!isNumber(objVal)) {
   						errType = 1;
   					}
					}

          if(bTypeOnly) {
   					if(!isNumber(objVal)) {
   						errType = 1;
   					}
          }
			} else if(strType == "password")  {
					objVal = obj.value;
					objID = obj.getAttribute("id") + "2";
					if(!document.getElementById(objID)) {
							errType = 3;
					} else if((objVal.replace(/ /g,"") == "") || (document.getElementById(objID).value.replace(/ /g,"") == "") ){
							errType = 0;
					} else if (document.getElementById(objID).value.replace(/ /g,"") != objVal.replace(/ /g,"")) {
							errType = 2;
					}
			}



		if(errType != -1) {
			switch(errType) {
					case 0:
							strErrorMsg = "Vous devez saisir votre " + strIdent + " dans le formulaire!\r\n";
					break;
					case 1:
							if(checkFirstLetter(strIdent)) {
								strErrorMsg = "L'"+strIdent;
							} else {
								strErrorMsg = "Le " + strIdent;
							}
								strErrorMsg += " que vous avez introduit n'est pas valide!\r\n";
					break;
					case 2:
								strErrorMsg = "Les mots de passe introduits ne correspondent pas\r\n";
					break;
					case 3:
								strErrorMsg = "Le formulaire est invalide\r\n";
					break;

			}
			return strErrorMsg;
		}  else {
			return "";
		}
}

function parseFloatCustom(strVal,nDecimals) {
		divider = Math.pow(10,nDecimals);
		subject = parseFloat(strVal.replace(/,/g,"."));
		if(!isNaN(subject)) {
			result = Math.round(subject * divider)/divider;
			return result;
		} else {
			return subject;
		}
}

function showPopup(file, h, w) {
    if((typeof WindowPopUp != "undefined") && (WindowPopUp != null))
        WindowPopUp.close();

    WindowPopUp = window.open(file,"popup","left="+parseInt((screen.width-w)/2)+", top="+parseInt((screen.height-h)/2)+", width="+w+", height="+h);

    if(WindowPopUp != null)
        WindowPopUp.focus();
}
function callAjax( data, callback, bShowLoading )
{
	if ( typeof bShowLoading == "undefined" )
		bShowLoading = true;
	jQuery.ajax({
                type: "POST",
                cache: false,
                timeout: 30000,
                url: "./ajax.php",
                data: data,
                processData: true,
                dataType: "json",
                beforeSend: function(){
					if ( bShowLoading ) startLoading();
                },
                success: callback,
                complete: function(request, status){
                    if ( bShowLoading ) endLoading();
                }
            });
}

function coverScreen(el)
{
    var pos = "fixed";
    var height = "100%";

    if ( jQuery.browser.msie && parseInt(jQuery.browser.version) <= 6 )
    {
        pos = "absolute";
        height = jQuery(document).height() + "px";
    }

    jQuery(el).css({
        position: pos,
        top: 0,
        left: 0,
        overflow: "hidden",
        zIndex: 10000,
        width: "100%",
        height: height
    });
}

function startLoading( containerID, strClass )
{
	if ( typeof containerID != "undefined" )
	{
    	if ( typeof strClass != "undefined" )
    	{
    		jQuery("#"+containerID).addClass(strClass);
    	}
        else
        {
    		jQuery("#"+containerID).addClass("loading-elem");
        }
	}
	else
	{
        if ( jQuery("#tmp_loading").size() == 0 )
        {
            jQuery("body").append("<div id='tmp_loading' class='loading-full'></div>");
            jQuery("#tmp_loading").css("opacity", 0.7);
        }
        coverScreen(jQuery("#tmp_loading"));
	}
}

function endLoading( containerID, strClass )
{
	if ( typeof containerID != "undefined" )
	{
    	if ( typeof strClass != "undefined" )
    	{
    		jQuery("#"+containerID).removeClass(strClass);
    	}
        else
        {
    		jQuery("#"+containerID).removeClass("loading-elem");
        }
	}
	else
	{
	    jQuery("#tmp_loading").remove();
	}
}
