/*///////////////////////////////////////////////////////////////////////////////////////////////////////
///// Code mixing by Molokoloco for Agence Clark... [BETA TESTING FOR EVER] ........... (o_O)  /////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

Functions :
	
	db(myvar)
	die()
	exec(func)
	isSet(myVar)
	isId(myElmt)
	isWhat(myVar)						:  return ( number | string | object | boolean | function )
	checkUrl(strUrl)
	checkMail(strMail)
	checkDate(strDate)
	cleanString(string)
	formVerif(frm_name,arr_control,arr_param,errorMessage) : controle des formulaires
	
	
Have to check prototype !

	// EX. ONLOAD EVENT 
	var page_loaded = function(evt) { if (evt) Event.stop(evt); ... }
	Event.observe(window, 'load', page_loaded);	
	...
*/

// ------------------------- REQUIRE :) ---------------------------------- //
if (typeof Element == 'undefined') throw("tools.js requires prototype.js library");

// ------------------------- DEBUG VAR ---------------------------------- //
var db = function(myvar) {
    var varValue = 'DB (' + typeof myvar + ') :\n';
    if (typeof myvar == 'string' || typeof myvar == 'number') varValue = myvar;
    //else if (typeof myvar == 'object') return vd(myvar);
    else {
        for (var att in myvar) {
            if (typeof myvar[att] != 'function') // (bad prototype noise)
                varValue += '\t'+att + ' <'+typeof myvar[att]+'> ' + myvar[att]+'\n';
        }
    }
	if (typeof myvar == 'array') varValue += "\n"+myvar.inspect();
    if (navigator.userAgent.indexOf('Firefox') >= 0 && console.log) console.log(varValue); // DEV
    else nativeAlert(varValue);
};

// ------------------------- STOP SCRIPT ---------------------------------- //
var die = function(mess) {
    throw(( mess ? mess : "JS says that you killing him softly : Oh my god moonWalker is down..."));
};


// ------------------------- Execute function ---------------------------------- //
var exec = function(func) {
	if (typeof(func) == 'string') func = eval(func);
	else if (typeof(func) != 'function') return false;
	try { func(); return true; }
	catch(e) { func; return true; }
	return false;
}

// ------------------------- IS SET ? ---------------------------------- //
var isSet = function(myVar) {
	if (typeof(myVar) == 'undefined' || myVar === '' || myVar === null) return false;
	else return true;
};

// ------------------------- ID ELEMENT EXIST ? ---------------------------------- //
var isId = function(element) {
	if (!isSet(element)) return false;
	try { 
		if ($(element)) return true;
		else return false;
	}
   	catch(e) { return false; }
};

// ------------------------- Type of ---------------------------------- //
var isWhat = function(myVar) {
	if (!isSet(myVar)) return '';
	else return typeof myVar; // number | string | object | boolean | function
};

// ------------------------- VALIDATE URL ------------------------------ //
var checkUrl = function(strUrl) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    return regexp.test(strUrl);
};

// ------------------------- VALIDATE URL ------------------------------ //
var checkMail = function(strMail) {
    var regexp = /^[A-Za-z0-9._-]+@[A-Za-z0-9.\-]{2,}[.][A-Za-z]{2,4}$/;
    return regexp.test(strMail);
};

// ------------------------- VALIDATE DATE : 15/02/78 ------------------------------ //
var checkDate = function(strDate) {
    if (!isSet(strDate) || !strDate.match('/')) return false;
    var date_array = strDate.split('/');
    var day = String(date_array[0]);
    var month = String(date_array[1]);
    var year = String(date_array[2]);
    if (day.length < 2 || month.length < 2 || year.length < 2) return false;
    if (parseInt(year) > 78) year = '19'+year;
    else year = '20'+year;
    month = parseInt(month - 1);
    var source_date = new Date(year,month,day);
    if (year != source_date.getFullYear() || month != source_date.getMonth() || day != source_date.getDate()) return false;
    else  return true;
};

// ------------------------- CLEAN WORD STRING ------------------------------ //
var cleanString = function(string) {
	if (!isSet(string)) return '';
	var myregexp = new RegExp(/((&ldquo;)|(&rdquo;)|(&acute;)|(&lsquo;)|(&rsquo;)|(&hellip;)|(\Œ)|(\»)|(\«)|(\œ)|(\€)|(\“)|(\”)|(\´)|(\‘)|(\’)|(\…)|(\„)|(\))/gi);
	string = string.replace(myregexp,' ');
	return string;
};

// ------------------------- VERIF Formulaire ---------------------------------- //

var formVerif = function(frm_name,arr_control,arr_param,errorMessage,errorConteneur) {
	// Masque de errorConteneur
	$(errorConteneur).setStyle({display:'none'});
	
    if (!document.forms[frm_name]) {
        alert('Vérifiez l\'ID du formulaire');
        die();
    }

	var myForm = document.forms[frm_name];
	
    var divErrorCss = 'divError'; // Class error applicable a la div affichant l'alerte
    var oneError = false;
    var focusinput = false;
    //var errorMessage = '';
	
	// Array parametres (extensibles!...)
    var mep = arr_param['mep'] == 'alerte' ? 'alerte' : 'message';
    var autoScroll = arr_param['autoScroll'] == true ? true : false;
    var action = arr_param['action'] ? arr_param['action'] : 'submit';
   
    // Class error applicable aux champs
    var inputCss = {
        input:       'input_error',
        textarea:    'area_error',
        select:      'select_error'
    }

	// Champs a vérifier
	if (isWhat(arr_control) != 'object') {
		alert('toDO // Scan champs par defaut... !!!');
		inputCollection = Form.serialize(myForm, true);
		db(inputCollection);
		die();
		// Serialize form data to a string suitable for Ajax requests (default behavior) or,
		// if optional getHash evaluates to true, an object hash where keys are form control names and values are data
	}
	
	// Clean word bad string
	if (typeof cleanString == 'undefined') db("form.js requires 999_regexp.js");
	else {
		$$('#'+frm_name+' input[type="text"]').each( function(e) { $(e).value = cleanString($F(e)); });
		$$('#'+frm_name+' textarea').each( function(e) { $(e).value = cleanString($F(e)); });
	}
	
    for (var property in arr_control) {
		var nom_champ = property;
		var type = arr_control[property]['type'];
		var minchar = ( arr_control[property]['minchar'] > 0 ? arr_control[property]['minchar'] : false );
		if (minchar) var mincharAlerte = 'Le champ <strong>'+nom_champ+'</strong> doit faire '+minchar+' charact&egrave;res minimum';
		var alerte = ( arr_control[property]['alerte'] ? arr_control[property]['alerte'].stripScripts() : 'Le champ <strong>'+nom_champ+'</strong> est obligatoire');
		var divErrorCssCustom = arr_control[property]['errorMessCss'] ? arr_control[property]['errorMessCss'] : divErrorCss;
		//var specifiqueInput = arr_control[property]['input'] ? arr_control[property]['input'] : '';
		
		var reg_expression;
		var matched = false;
		var alerte_sup = ''; // Alerte spécifique pour 2nd email
		//var toshort = false;
		
		if (!myForm[nom_champ] && !myForm[nom_champ+'[]']) {
			alert('Champ HTML absent : "'+nom_champ+'"');
			die();
		}
		var input_element = ( myForm[nom_champ] ? myForm[nom_champ] : myForm[nom_champ+'[]'] );
		
		var input_element_p = input_element;
		var input_element_d = input_element;
		if (input_element[0] && input_element[0].nodeName.toLowerCase() != 'option') { // Si input type radio|check > array
			input_element_p = input_element[0]; // Premier element
			input_element_d = input_element[(input_element.length-1)]; // Dernier element
		}
		
		var input_element_tag = input_element_p.nodeName.toLowerCase(); // 'textarea' | 'input' | ...
		var input_type_area = '';
		
		switch(input_element_tag) {
            case 'textarea': input_type_area = 'text'; // Astuce > fait passer textarea pour input "text"
            case 'input':
              var input_type = (input_type_area ? input_type_area : input_element_p.getAttribute('type'));
              input_type = input_type.toLowerCase();
              switch(input_type) {
                  case 'password':
						if (input_element.value == '') break;
						else if (minchar && input_element.value.length < minchar) {
							 alerte = mincharAlerte;
							 break;
						}
						else matched = true;
						
						// Mot de passe
						if (matched && myForm[nom_champ+'_2']) {
                            if (myForm[nom_champ+'_2'].value != myForm[nom_champ].value) alerte_sup = 'second_mdp_erreur';
                            else alerte_sup = 'second_mdp_ok';
                        }
						
                  case 'text':
                  case 'hidden':
						if (input_element.value == '') break;
						else if (minchar && input_element.value.length < minchar) {
							 alerte = mincharAlerte;
							 break;
						}
                        switch(type) {
                            case 'tel_fr' :      reg_expression = /^0([1-6]|8|9)([. -\/]?)\d{2}(\2\d{2}) {3}$/; break;
                            case 'tel' :         reg_expression = /^[0-9]{10}$/; break;
                            case 'chiffre' :     reg_expression = /^[0-9]{1,}$/; break;
                            case 'mel' :         reg_expression = /^[A-Za-z0-9._-]+@[A-Za-z0-9.\-]{2,}[.][A-Za-z]{2,4}$/; break;
                            case 'url' :         reg_expression = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; break;
                            case 'date' : break;
                            default : reg_expression = /^(.+)[\r\n]|$/; break; // Valide text non vide
                        }
                        if (type == 'date') { // Valide jj/mm/aa(aa)
                            if (checkDate(input_element.value)) matched = true;
                        }
                        else if (input_element.value.match(reg_expression)) matched = true;
                        else if (type == 'mel') alerte = alerte; //'L\'email ne semble pas correcte';
                        // Si type "mel" check if "mel_2" exist et si identique
                        if (matched && type == 'mel' && myForm[nom_champ+'_2']) {
                            if (myForm[nom_champ+'_2'].value != myForm[nom_champ].value) alerte_sup = 'second_email_erreur';
                            else alerte_sup = 'second_email_ok';
                        }
                        break;
                  case 'file':
                        if (input_element.value != '') {
                            var fichier = baseName(input_element.value);
                            if (type != '') {
                                exts = type.split('|');
                                for (i=0; i<exts.length; i++) if (fichier.match(exts[i])) matched = true;
                            }
                            else if (fichier) matched = true;
                        }
                        break;
                  case 'checkbox':
                  case 'radio':
                     input_element_tag = 'radio';
                     if (input_element.length) {
                         for (var j=0; j<input_element.length; j++) { if (input_element[j].checked) matched = true; }
                     }
                     else if (input_element.checked) matched = true;
                  	break;
              }
          break;
          case 'select':     
              if (input_element.options[input_element.selectedIndex].value != '') matched = true;
          break;
        }
        if (!matched) {
            oneError = true;
            if (mep == 'message') {
                if ($('div_error_'+nom_champ)) {
                    $('div_error_'+nom_champ).update(alerte);
                    $('div_error_'+nom_champ).addClassName('divError');
                    $('div_error_'+nom_champ).show();
                }
                else {
                    if ($(nom_champ+'_erreur')) $(nom_champ+'_erreur').show();
                    else new Insertion.After(input_element_d,'<div class="'+divErrorCssCustom+'" id="'+nom_champ+'_erreur">'+alerte+'</div>');
                }
            }
            else{
				//$(nom_champ).addClassName('erreur_champ');
				$(nom_champ).setStyle({border:'1px solid red'});
				errorMessage += alerte; //errorMessage += alerte+'<br>';
			}

            if (input_type != 'checkbox' && input_type != 'radio') {
                Element.removeClassName(input_element_p, inputCss[input_element_tag]);
                Element.addClassName(input_element_p, inputCss[input_element_tag]);
            }
            if (!focusinput) { // Focus la première erreur
                focusinput = true;
                input_element_p.focus();
            }
        }
        else {
            if (input_type != 'checkbox' && input_type != 'radio') Element.removeClassName(input_element_p, inputCss[input_element_tag])
            if ($('div_error_'+nom_champ)) $('div_error_'+nom_champ).hide();
            else if ($(nom_champ+'_erreur')) $(nom_champ+'_erreur').hide();
			$(nom_champ).setStyle({border:'1px solid #DCDCDC'});
        }
		
        if (alerte_sup != '') {
            switch(alerte_sup) {
                case 'second_email_erreur' :
                    oneError = true;
                    alerte = 'Les deux e-mails  ne sont pas identiques';
                    nom_champ = nom_champ+'_2'; // Envois alert input "mel" sur "mel_2"
                    if (mep == 'message') {
                        if ($(nom_champ+'_erreur')) $(nom_champ+'_erreur').show();
                        else new Insertion.After($(nom_champ),'<div class="'+divErrorCssCustom+'" id="'+nom_champ+'_erreur">'+alerte+'</div>');
                        Element.removeClassName($(nom_champ), inputCss[input_element_tag]);
                        Element.addClassName($(nom_champ), inputCss[input_element_tag]);
                    }
                    else errorMessage += alerte+'<br>';
                   
                   if (!focusinput) { // Focus la première erreur
                        focusinput = true;
                        $(nom_champ).focus();
                    }
                break;
                case 'second_email_ok' :
                    nom_champ = nom_champ+'_2'; // Envois alert input "mel" sur "mel_2"
                    if (mep == 'message') {
                        Element.removeClassName($(nom_champ), inputCss[input_element_tag])
                        if ($('div_error_'+nom_champ)) $('div_error_'+nom_champ).hide();
                        else if ($(nom_champ+'_erreur')) $(nom_champ+'_erreur').hide();
                    }
                break;
				
            }
        }
    }

    // SUBMIT
    if (!oneError && (errorMessage == '' || errorMessage =='Les champs suivants sont obligatoires et doivent être valides : <br />'|| errorMessage =='Identification incorrecte' || errorMessage =='<p id="errorMail_oublie" class="erreur_saisie">Adresse E-mail incorrecte<\/p>')) {
        if (action == 'submit') {
			if (Element.hasAttribute(myForm, 'onsubmit')) $(myForm).setAttribute('onsubmit', '');
			//myForm.submit();
			return true;
		}
		else if (action == 'getUrl') {			
			var responseElement = arr_param['responseElement'];
			var responseMessage = arr_param['responseMessage'];
			var updateElement = arr_param['updateElement'];
			// Submit the form by Ajax
			var callAction = Form.requestAction(document.forms[frm_name], {
				evalScripts: true,
				onSuccess: function(transport) {
					if (isId(updateElement)) $(updateElement).update(transport.responseText);
					else return alert('Problème avec votre element à updater dans formVerif');
				}
			});
		}
        else if (isSet(action) && !exec(action)) return alert('Problème avec votre action dans formVerif');
		else return alert('Ajoutez une action dans le JS');
		return true;
    }
    else {		
        if (autoScroll) new Effect.ScrollTo(myForm, {offset: -16});
        if (autoScroll && mep != 'message') {			
			//setTimeout("printInfo('"+strRep(errorMessage,'\'','\\\'')+"');",1000); // Wait scroll
		}
		if (autoScroll && mep != 'message'){
			//setTimeout(myLightWindow.activateWindow({href: './alertes.php?contenu='+errorMessage, title:'', width:'500px', height:'300px'}),1000); // Wait scroll
			$(errorConteneur).update(errorMessage);
			$(errorConteneur).setStyle({display:'block'});
		}
      	//  else if (mep != 'message') printInfo(strRep(errorMessage,'\'','\\\''));
		else if (mep != 'message'){
			//myLightWindow.activateWindow({href: './alertes.php?contenu='+errorMessage+'&type=erreur', title:'', width:'500px', height:'300px'});
			$(errorConteneur).update(errorMessage);
			$(errorConteneur).setStyle({display:'block'});
		}
		return false;
    }
};
