// =========== Automated footer height script =========== //
/*function autoHeight() {
    var divh = document.getElementById('footer').offsetHeight;
    var refDiv = (divh +"px");
    document.getElementById('wrap-footer').style.height = refDiv;
    document.getElementById('push').style.height = refDiv;
    document.getElementById('fwrap1').style.height = refDiv;
    document.getElementById('fwrap2').style.height = refDiv;
    document.getElementById('fwrap3').style.height = refDiv;
    document.getElementById('wrap-container').style.marginBottom = (0-divh)+"px";

    var minDivh = document.getElementById('container').offsetHeight;
    document.getElementById('mh1').style.height = minDivh+"px";
    document.getElementById('mh2').style.height = minDivh+"px";
    document.getElementById('mh3').style.height = minDivh+"px";

};
window.onload = function() {autoHeight()};*/
// ====================================================== //

var xmlHttp; 

function makeHttpRequest(scriptpath,urlmethod) {
		if(!initAjax()) {
				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);

				} else {
							//parent.document.getElementById("divContact").innerHTML = "<strong>Envoi du message</strong>";
				}

		}
    xmlHttp.send(null);
}

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 toggle(obj, element, class1, class2){
    if (element.style.display == "none") {
        element.style.display = "block";
    } else {
        element.style.display = "none";
    }
    if (obj.className == class1){
        obj.className = class2;
    } else {
        obj.className = class1;
    }
}
// ====================================================== //

function showImage(strFile, nWidth, nHeight)
{
	if((typeof WindowPopUp != "undefined") && (WindowPopUp != null))
		WindowPopUp.close();

    WindowPopUp = window.open("admin/popup.php?file="+strFile, "image", "left="+parseInt((screen.width-nWidth)/2)+", top="+parseInt((screen.height-nHeight)/2)+", width="+nWidth+", height="+nHeight);
    if(WindowPopUp != null)
		WindowPopUp.focus();
}

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 setHeadCart( array )
{
	if ( typeof( array.count ) != "undefined" )
		jQuery("#headCountItems").html( ( !parseInt(array.count) ) ? "0" : array.count + " article(s)" );
	if ( typeof( array.total ) != "undefined" )
		jQuery("#headTotal").html( array.total + "&nbsp;&euro;" );
}

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 doOnBlur(obj, nSel, text) {
	  switch (nSel) {
	      case 1:
	          if (obj.value.replace(/ /g,'') == '')
	              obj.value = text;
	          break;
	  }
	}

	function doOnFocus(obj,nSel, text) {
	  switch (nSel) {
	      case 1:
	          if (obj.value == text)
	              obj.value = "";
	          break;
	  }
	}

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 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 = "";
	nrErr = 0;
	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;
    	    nrErr++;
    	    arrRejected[arrRejected.length] = obj;
        }
      }
  }

   if((objForm.elements["capa"] != null && (document.getElementById("capa").value.replace(/ /g,"") == ""))){
	   txtErr += "Vous devez remplir le <b>Code de s&eacute;curit&eacute;</b> !<br />" ;
	   nrErr++;
       arrRejected[arrRejected.length] = objForm.elements["capa"];
	}
	if(txtErr != "") {
		//openDialog("Erreur", txtErr, 0, 0, 500, nrErr * 28 );
        jError(txtErr,"Erreurs");
	 	//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(jQuery("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 <b>" + strIdent + "</b> dans le formulaire !<br />";
					break;
					case 1:
							if(checkFirstLetter(strIdent)) {
								strErrorMsg = "L'<b>"+strIdent+"</b>";
							} else {
								strErrorMsg = "Le <b>" + strIdent+"</b>";
							}
								strErrorMsg += " que vous avez introduit n'est pas valide !<br />";
					break;
					case 2:
								strErrorMsg = "Les mots de passe introduits ne correspondent pas.<br />";
					break;
					case 3:
								strErrorMsg = "Le formulaire est invalide.<br />";
					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 PopUp(strFile, nWidth, nHeight)
{
    if((typeof WindowPopUp != "undefined") && (WindowPopUp != null))
        WindowPopUp.close();

    WindowPopUp = window.open("popup.php?file="+strFile, "popup", "left="+((screen.width-nWidth)/2)+", top="+((screen.height-nHeight)/2)+", width="+nWidth+", height="+nHeight);
    if(WindowPopUp != null)
        WindowPopUp.focus();
}
*/

function loadMessage()
{
	var height = jQuery(window).height();
	var width = jQuery(window).width();
	var scrollTop = jQuery(window).scrollTop();
	jQuery('.fadeMessage').css({'display' : 'inline',
							'top' : (scrollTop+(height/2)) + 'px',
							'left': (width/2) + 'px'
	}).fadeIn("slow").animate({ "opacity": 1 }, 1000).fadeOut(500);

}

function startLoading()
{
	var height = jQuery(window).height();
	var width = jQuery(window).width();
	var scrollTop = jQuery(window).scrollTop();
	jQuery("#loading").css({'display' : 'inline',
						    'top' : (scrollTop+(height/2)) + 'px',
						    'left': (width/2) + 'px'
	}).bgiframe();
}

function endLoading()
{
	jQuery("#loading").css('display','none');
}

function openDialog( title,  message, marginTop, marginBottom, width, height )
{
	if ( !marginTop )
		marginTop = 15;
	if ( !marginBottom )
		marginBottom = 15;	
	if ( !width )
		width = 500;
	if ( !height )
		height = 100;
	jQuery("#dialog").dialog( 'destroy' );

	jQuery("#dialog").dialog({autoOpen: false, bgiframe: true});

	jQuery("#dialog").html('<p style="margin-top:' + marginTop + 'px;margin-bottom:' + marginBottom + 'px;" align="center">' + message + '</p>');
	jQuery("#dialog").dialog('option', 'title', title);
	jQuery("#dialog").dialog('option', 'width', width);
	jQuery("#dialog").dialog('option', 'height', (height + marginBottom + marginTop + 70));
	jQuery("#dialog").dialog( 'open' );
	
}

function openConfirm( title,  message, func, okButtonText, marginTop, marginBottom, width, height )
{
	jQuery("#dialog").dialog( 'destroy' );
	var dialog_buttons = {}; 
	dialog_buttons[okButtonText] = function(){ eval(func); jQuery(this).dialog('close'); };
	dialog_buttons['Annuler'] = function(){ jQuery(this).dialog('close'); } ;
	
	jQuery("#dialog").dialog({ buttons: dialog_buttons, bgiframe: true });
	if ( !marginTop )
		marginTop = 15;
	if ( !marginBottom )
		marginBottom = 15;	
	if ( !width )
		width = 350;	
	if ( !height )
		height = 65;
	jQuery("#dialog").html('<p style="margin-top:' + marginTop + 'px;margin-bottom:' + marginBottom + 'px;" align="center">' + message + '</p>');
	jQuery("#dialog").dialog('option', 'title', title);
	jQuery("#dialog").dialog('option', 'width', width);
	jQuery("#dialog").dialog('option', 'height', (height + marginBottom + marginTop + 70));
	
}




function validateLogin()
{
	var login = jQuery("#login").val();
	var pass = jQuery("#pass").val();
	var remember = 0;
	if ( jQuery("#remember").attr("checked") == true )
		remember = 1;
	callAjax({method : 2, user : login, pass : pass, remember: remember}, function(result){
		if ( result['valid'] ) 
		{	
			document.location = "file_transfer.php";
		} 
		else if ( parseInt(result) == -1 )
		{
			openDialog( "<p style='color:#ffffff'>Erreur</p>", "<p>Le compte n'est pas actif!</p>", 0, 0, 300);
		
		} else 
		{	
			openDialog( "<p style='color:#ffffff'>Erreur</p>", "<p style='font-size: 15px; text-align: left'>Utilisateur ou mot de passe invalide!</p>", 0, 0, 300);
		}
		endLoading();
	}); 
}

function logout()
{
	callAjax({method : 4}, function(result){
		if ( result)
			document.location = "index.php";
		endLoading();
	});

}


function checkFields(){
	var errMsg = [];
	var name = "";
	var valid = false;	
	var out = true;
	var color = "";
	var name= "";
	jQuery("[id^=validation]").each(function(){
		valid = true;
		name = jQuery(this).prev().html();
		if ( this.id.search(/_needed/i) > 0 )
			name = name.substr(2);
		
		//mandatory validation
		if ( ( this.id.search(/_needed/i) > 0 ) && !(this.value) )
		{		
			valid = false;			
		}		
		//type validation
		if ( valid )
		{
			if ( ( this.id.search(/_integer/i) > 0 ) && !( isNumber( this.value ) ) )
				valid = false;
			else if ( ( this.id.search(/_email/i) > 0 ) && !( checkEmail( this.value ) ) ) 
				valid = false;
			else if ( ( this.id.search(/_float/i) > 0 ) && !( isFloat( this.value ) ) )
				valid = false;
		}
		//limit value
		if ( valid )
		{
			if ( ( this.id.search(/_maxval/i) > 0 ) )
			{
				if (parseFloat(this.value) > parseFloat( getBracketsValue( this.id, '_maxval' ) ) )
					valid = false;
			}
			if ( ( this.id.search(/_minval/i) > 0 ) )
			{
				if (parseFloat(this.value) < parseFloat( getBracketsValue( this.id, '_minval' ) ) )
					valid = false;
			}
		}
				
		if (!valid)
		{
			out = false;
			color = 'red';
			//jQuery(this).focus();
			//if (!jQuery.inArray( name, errMsg ) ) errMsg.push(name);			
		} 
		else
		{	
			color = 'black';
		}
		jQuery(this).prev().css("color",color);
	});
	return out;
}

function getBracketsValue( str, type )
{
	var arr = str.split(type+"(");
	var arr2 = arr[1].split(")");
	return arr2[0];
}



function callAjax(data, callback) {
	startLoading();	
	jQuery.post("./ajax.php", data, callback, "json");
}


String.prototype.tcreplace = stringReplace;

function stringReplace(findText, replaceText) {
  var originalString = new String(this);

  var pos = 0;
  var len = findText.length;
  pos = originalString.indexOf(findText);
  while (pos != -1) {
    preString = originalString.substring(0, pos);
    postString = originalString.substring(pos + len,originalString.length);
    originalString = preString + replaceText + postString;
    pos = originalString.indexOf(findText);
  }
  return originalString;
}