// ÃŠtre compatible avec MSIE...
if ('undefined' == typeof Node)
    Node = { ELEMENT_NODE: 1, TEXT_NODE: 3 };

MSG_BLANK = ' est obligatoire.';
MSG_NOT_A_DATE = ' n\'est pas une date.';
MSG_NOT_A_DOUBLE = ' n\'est pas un nombre.';
MSG_NOT_AN_INTEGER = ' n\'est pas un nombre entier.';
MSG_TOO_LOW = ' est trop petit(e).';
MSG_TOO_HIGH = ' est trop grand(e).';

REGEX_AUTO_FIELD = /^[^_]+(_Req)?(_(Int|Dbl|Date)(_[0-9.]+){0,2})?$/;
REGEX_BLANK = /^\s*$/;
REGEX_DAY = /^(0?[1-9]|[1-2][0-9]|3[01])$/;
REGEX_MONTH = /^(0?[1-9]|1[0-2])$/;
// Les multiples groupes vont nous dÃ©couper l'ID tout seuls...
REGEX_TYPED_FIELD = /_(Int|Dbl|Date)(_([0-9.]+))?(_([0-9.]+))?$/;
REGEX_YEAR = /^[0-9]{2,4}$/;


function checkForm(e) {
    // CompatibilitÃ© MSIE / les autres...
    
    e = e || window.event;
    var form = e.target || e.srcElement;
    var errors = '';
    var faulty = null;
    //alert('test'+form.elements.length);
    for (var index = 0; index < form.elements.length; ++index) {
        
        var field = form.elements.item(index);
        // VÃ©rification de syntaxe
        if (!field.id.match(REGEX_AUTO_FIELD))
            continue;
        var value = $F(field);
        // Champ requis ?
        $spec = true;
        
        if(field.id == 'edtSociete_Req' && $('statutprive').checked) $spec = false;
        if (field.id.match(/_Req/) && (value == null || value.match(REGEX_BLANK)) && $spec) {
        	
            errors += getFieldName(field) + MSG_BLANK + '\n';
            faulty = faulty || field;
            continue;
        }
	// Champ typÃ© ?
	var match = field.id.match(REGEX_TYPED_FIELD);
	if (match) {
	    var type = match[1];
	    var min = match[3];
	    var max = match[5];
	    var error = checkTypedField(value, type, min, max);
	    if (error) {
		errors += getFieldName(field) + error + '\n';
		faulty = faulty || field;
	    }
	}
    }
    if (!faulty)
        return;
    stopEvent(e);
    alert(errors);
    faulty.focus();
} // checkForm

function checkTypedField(value, type, min, max) {
    // Valeurs par dÃ©faut pour les bornes
    min = min || Number.NEGATIVE_INFINITY;
    max = max || Number.POSITIVE_INFINITY;
    var val;
    if ('Int' == type) {
        try {
            val = parseInt(value, 10);
	    if (String(val) != value)
	    	throw val;
        } catch (e) {
            return MSG_NOT_AN_INTEGER;
        }
    }
    if ('Dbl' == type) {
        try {
            val = parseFloat(value);
	    if (String(val) != value)
	    	throw val;
        } catch (e) {
            return MSG_NOT_A_DOUBLE;
        }
    }
    if ('Int' == type || 'Dbl' == type) {
        if (val < min)
            return MSG_TOO_LOW;
        if (val > max)
            return MSG_TOO_HIGH;
    }
    if ('Date' == type) {
        var comps = value.split('/');
        if (3 != comps.length || !comps[0].match(REGEX_DAY) ||
            !comps[1].match(REGEX_MONTH) ||
            !comps[2].match(REGEX_YEAR))
            return MSG_NOT_A_DATE;
    }
    return null;
} // checkTypedField

function getFieldName(field) {
    var label = getLabelFor(field);
    if (!label)
        return field.name;
    var text = '';
    var node = label.firstChild;
    // Parcours en profondeur, dÃ©rÃ©cursifiÃ©, du fragment sous le libellÃ©
    while (true) {
        if (Node.ELEMENT_NODE == node.nodeType && node.hasChildNodes())
            node = node.firstChild;
        else if (Node.TEXT_NODE == node.nodeType)
            text += node.nodeValue;
        if (node.nextSibling)
            node = node.nextSibling;
        else {
            node = node.parentNode;
            if (node == label)
                break;
            node = node.nextSibling;
        }
    }
    return text;
} // getFieldName



function getLabelFor(field) {
    var labels = document.getElementsByTagName('label');
    for (var index = 0; index < labels.length; ++index) {
        var label = labels.item(index);
        if (label.htmlFor == field.id)
            return label;
    }
    return null;
} // getLabelFor

function stopEvent(e) {
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    } else {
        e.cancelBubble = true;
        e.returnValue = false;
    }
} // stopEvent
function showsociete() {
    $('societe').show();
}
function hidesociete() {
    $('societe').hide();
}

function test() {
	$tmp_fdp=parseFloat($('us_fp').innerHTML.replace(",","."));
	if($('edtPays_Req').value!='France' && $('edtPays_Req').value!='Belgique')
	{
		$('us_fp').innerHTML='10,00';
	}
	else
	{
		sous_total=parseFloat($('us_st').innerHTML.replace(",","."))
		if(sous_total <= 50) 
		$('us_fp').innerHTML = '6,00';
		
		if(sous_total > 50 && sous_total <= 100)
		$('us_fp').innerHTML = '3,00';
		
		if(sous_total > 100)
		$('us_fp').innerHTML='0,00';
	}
	st=$('us_st').innerHTML.replace(",",".");
	fp=$('us_fp').innerHTML.replace(",",".");
	to=parseFloat(st)+parseFloat(fp);
	to=to.toFixed(2);
	to=to.replace(".",",");
	$('us_to').innerHTML=to;
	
	tmp_fdp_fin=parseFloat($('us_fp').innerHTML.replace(",","."));
	if($tmp_fdp!=tmp_fdp_fin)
	alert('Vos frais de port sont désormais de '+ $('us_fp').innerHTML +' €');
}



Event.observe(window, 'load', function(){ $('excuses').hide() });
Event.observe(window, 'load', function(){ Event.observe($('contactForm'), 'submit', checkForm); });
Event.observe(window, 'load', function(){ Event.observe($('edtPays_Req'), 'change', test); });
Event.observe(window, 'load', function(){ Event.observe($('statutpro'), 'focus', showsociete); });
Event.observe(window, 'load', function(){ Event.observe($('statutprive'), 'focus', hidesociete); });
function addRequired(label) {
    eltfor = $(label.htmlFor);
    if(eltfor && eltfor.id.match(/Req/)) {
        label.className += ' required';
    }
}
function decorateNodeForAccessKey(label) {
    var ak = label.accessKey.toUpperCase();
    var labelvalueupper = label.firstChild.nodeValue.toUpperCase();
    var pos = labelvalueupper.indexOf(ak);
    var labelvalue = label.firstChild.nodeValue;
    Element.replace(label.firstChild, labelvalue.sub(eval('/'+ak+'/i'), '<span class="accessKey">'+labelvalue.charAt(pos)+'</span>', 1))
}
function decorateLabels() {
    var labels = $$('form label');
    labels.each(addRequired);
    //labels.each(decorateNodeForAccessKey);
} // decorateLabels

Event.observe(window, 'load', decorateLabels);


