// JavaScript Document
function VerifImg(classN, classNDuplic){	
	if(classNDuplic==undefined){classNDuplic=classN;}
	this.classNoSuppr='no_suppr';
	this.tabElemNoSuppr = new Array();
	this.tabElem = new Array();
	this.count=0;
	this.limit=8;
	this.element;
	
	if(this.init(classN, classNDuplic)==true){
		this.classN=classN;
		
		this.parentDuplic;
		this.tabExtension = new Array('jpg', 'jpeg', 'jpe'); /// liste des extensions autorisées
		this.okImgUrl= 'medias/valider.gif';
		this.notOkImgUrl = 'medias/croix_rouge.gif';
		this.notOkMsg = "ATTENTION ! Ce fichier n'est pas un fichier jpeg.";		
		
		this.imgClass='class__img__ok__not__ok';
		this.msgClass='class__msg__not__ok';
		
		this.tabImg = new Array();
		this.tabMsg = new Array();
		this.tabOk = new Array();
		
		this.posElemCourant;
		this.submitButton;
		
		this.initEvent();
	}
}

VerifImg.prototype.eregi = function(chaine, find) {
	var norm = new RegExp( find );
	return norm.exec( chaine )!=null;
}

VerifImg.prototype.init = function (classN, classNDuplic){
	var tab = new Array();
	tab=getElementsByClassName(classNDuplic);
	var nb_tab=tab.length;
	var j=0;
	if(nb_tab>0){
		for(var i=0; i<nb_tab; i++){
			if(this.eregi(tab[i].className,this.classNoSuppr)==false){
				if(j!=0){
					tab[i].parentNode.removeChild(tab[i]);
				}
				else{
					this.templateDuplic=tab[i].cloneNode(true);
					this.parentDuplic=tab[i].parentNode;	
					
					if(classN==classNDuplic){this.element=tab[i];}
					else{
						var tab2 = new Array();	
						tab2=tab[i].getElementsByTagName("input");
						var nb_tab2=tab2.length;
						for(var ii=0; ii<nb_tab2; ii++){
							if(this.eregi(tab2[ii].className,classN)==true){
								this.element=tab2[ii];
								break;
							}
						}
					}
				}
				j++;
			}
			else{
				if(classN==classNDuplic){
					this.tabElemNoSuppr.push(tab[i]);
					this.tabElem.push(tab[i]);
				}
				else{
					var tab2 = new Array();	
					tab2=tab[i].getElementsByTagName("input");
					var nb_tab2=tab2.length;
					for(var ii=0; ii<nb_tab2; ii++){
						if(this.eregi(tab2[ii].className,classN)==true){
							this.tabElemNoSuppr.push(tab2[ii]);
							this.tabElem.push(tab2[ii]);
							break;
						}
					}
				}
				
			}
		}
		
		this.count=this.tabElemNoSuppr.length;
		
		if(this.count==this.limit){this.element=tab[0];}
		this.submitButton=this.findSubmit(this.findForm());
		return true;
	}
	else{return false;}
}

VerifImg.prototype.initEvent = function (){
	var localThis=this;
	var tab = new Array();
	tab=getElementsByClassName(this.classN);
	var nb_tab=tab.length;
	var element;
	for(var i=0; i<nb_tab; i++){
		element=tab[i];
		element.onchange=function(){
			localThis.verif();
		}
		
		element.onfocus=function(){
			localThis.element=this;
			var tempKey = localThis.get_key_in_array(localThis.element, localThis.tabElem);
			if(tempKey==null){
				localThis.posElemCourant = localThis.tabElem.length;
				localThis.tabElem.push(localThis.element);
			}
			else{
				localThis.posElemCourant = parseInt(tempKey);
			}
		}
		
		element.onclick=element.onfocus;
	}
}

VerifImg.prototype.verif = function (){
var tab = new Array();
tab = this.explode('.', this.element.value);

var extension = tab[tab.length-1].toLowerCase();
this.removeImg();
if(this.notOkMsg!=""){this.removeMsg();}

	if(this.in_array(extension,this.tabExtension)==true){
		this.insertImg(true);
		this.tabOk[this.posElemCourant]=true;
		
		// && this.in_array(this.element, this.tabElemNoSuppr)==false
		if(this.count<(this.limit-1) && (this.posElemCourant==this.count)){
			//this.element.style.fontSize='50px';
			var newElem=this.newElement();		
			this.element=newElem;
			this.count++;
			this.initEvent();
		}
	} 
	else{		
		this.insertImg(false);
		if(this.notOkMsg!=""){this.insertMsg();}
		this.tabOk[this.posElemCourant]=false;
	}	
	
	this.AbleDisableSubmit(this.verifAll());
}

VerifImg.prototype.verifAll = function (){
	var nb = this.tabOk.length, i=0;
	while(this.tabOk[i]!=false && i<nb){
		i++;
	}
	
	if(i==nb){return true;}
	else{return false}	
}

VerifImg.prototype.AbleDisableSubmit = function (bool){
	var opa;
	if(bool==true){
		opa=1;
		this.submitButton.disabled=false;
		this.submitButton.style.opacity=opa;
		this.submitButton.style.MozOpacity =opa; /// pr vieux firefox
		this.submitButton.style.filter = "alpha(opacity=" + (opa*100) + ")"; /// pr IE
		this.submitButton.style.KhtmlOpacity =opa; /// pr Konqueror et safari
		this.submitButton.style.cursor='pointer';
	}
	else{
		opa=0.3;
		this.submitButton.disabled=true;
		this.submitButton.style.opacity=opa;
		this.submitButton.style.MozOpacity =opa; /// pr vieux firefox
		this.submitButton.style.filter = "alpha(opacity=" + (opa*100) + ")"; /// pr IE
		this.submitButton.style.KhtmlOpacity =opa; /// pr Konqueror et safari
		this.submitButton.style.cursor='not-allowed';
	}
}

VerifImg.prototype.newElement = function (){	
	var nouveauDuplic = this.templateDuplic.cloneNode(true);
	this.parentDuplic.appendChild(nouveauDuplic);
	var nouvelInput;
	
	var tab = new Array();	
	if(nouveauDuplic.value!=undefined){
		nouveauDuplic.value='';
		nouvelInput=nouveauDuplic;
	}
	else{
		tab=getElementsByClassName(this.classN, 'input', nouveauDuplic);
		if(tab.length>0){
			tab[0].value='';
			nouvelInput=tab[0];
			nouvelInput.name='img'+(this.count+2);
		}
	}
	
	return nouvelInput;
}

VerifImg.prototype.removeImg = function (){
	if(this.tabImg[this.posElemCourant]){
		this.tabImg[this.posElemCourant].parentNode.removeChild(this.tabImg[this.posElemCourant]);
		delete(this.tabImg[this.posElemCourant]); 
	}
	
}

VerifImg.prototype.removeMsg = function (){
	if(this.tabMsg[this.posElemCourant]){
		this.tabMsg[this.posElemCourant].parentNode.removeChild(this.tabMsg[this.posElemCourant]);
		delete(this.tabMsg[this.posElemCourant]);
	}	
}


VerifImg.prototype.insertImg = function (ok){
	if(ok==true){imgUrl= this.okImgUrl;}
	else{imgUrl = this.notOkImgUrl;}

	var nouvelleImg= document.createElement('img');
	nouvelleImg.src=imgUrl;
	nouvelleImg.className=this.imgClass;
	nouvelleImg.alt='';
	this.tabImg[this.posElemCourant]=nouvelleImg;
	this.element.parentNode.appendChild(nouvelleImg);
}

VerifImg.prototype.insertMsg = function (){
	var nouveauDiv= document.createElement('div');
	var texte=document.createTextNode(this.notOkMsg);
	nouveauDiv.appendChild(texte);
	nouveauDiv.className = this.msgClass;
	this.tabMsg[this.posElemCourant]=nouveauDiv;
	this.element.parentNode.appendChild(nouveauDiv);
}


VerifImg.prototype.explode = function(delimiter, string, limit) { 
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if(arguments.lengt <2 || typeof arguments[0]=='undefined' || typeof arguments[1]=='undefined'){return null;}
 
    if(delimiter === '' || delimiter === false || delimiter === null){return false;}
 
    if(typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object') {
        return emptyArray;
    }
 
    if (delimiter === true) {delimiter = '1';}
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

VerifImg.prototype.in_array = function (needle, haystack, strict) {
    var found = false, key, strict = !!strict;

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }

    return found;
}

VerifImg.prototype.get_key_in_array = function (needle, haystack, strict) {
    var found = null, key, strict = !!strict;

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = key;
            break;
        }
    }

    return found;
}


VerifImg.prototype.findForm = function () {
	var tempElem = this.element;
	while(tempElem.parentNode.nodeName.toLowerCase()!="form"){
		tempElem=tempElem.parentNode;
	}
	
    return tempElem.parentNode;
}

VerifImg.prototype.findSubmit = function (form) {
	var nb = form.getElementsByTagName("input").length;
	var tempElem, tempType;

	for(var i=0; i<nb; i++){
		tempElem=form.getElementsByTagName("input")[i];
		tempType=tempElem.type.toLowerCase();
		if(tempType=="submit" || tempType=="image"){break;}
	}
		
    return tempElem;
}


var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};

