$(document).ready(function(){
	function changeColor() {
        var that = $(this);
        var message_index = that.val();
        if (this.selectedIndex == 0) {
            if (that.hasClass('cpt_noir')) that.removeClass('cpt_noir');
            that.addClass('cpt_gris');
        }
        else {
            if (that.hasClass('cpt_gris')) that.removeClass('cpt_gris');
            that.addClass('cpt_noir');
        }
    }
    $("select").change(changeColor).change();
    
    if (typeof activity == 'undefined') {
    	var activity = '';
    }
    var rgx = /\/act([0-9]{2,4})-/;
    if (rgx.test(document.location)){
        activity = (document.location+'').match(rgx)[1];
    }

	var con_textArea = 'Please provide a description of your request, including any important details of the work required';
    
    $(":textarea[class=TEXTAREA]")
	.focus(function(){
		if(this.value==con_textArea) this.value='';
	})
	.blur(function(){
		if(this.value=='') this.value=con_textArea;
	})
	.val(con_textArea)
	;
	
	$(':text[name^=critere]').each(function(){
		var that = $(this);
		
		var parentShowHide = function (visible){
			//console.log(that,visible,that.parent());
			if (visible){
				that.parent().show('normal');
			}else{
				that.parent().hide();
			}
		}
		var testIfToDisplay=function(text){
			var rtn;
			if (/^If yes/.test(text)){
				rtn = true;
			}else if (/^Other/.test(text)){
				rtn = true;
			}else if (/^Yes/.test(text)){
				rtn = true;
			}else{
				rtn = false;
			}
			return rtn;
		}
		
		var rgx1 = new RegExp('critere\\\[(.*)\\\]\\\[saisie\\\]');		
		
		if (match = that[0].name.match(rgx1)){
			//bloc select
			var slc = $('select[name=critere\\\['+match[1]+'\\\]\\\[valeur\\\]]');
			if (slc.length){
				slc.change(function(){					
					var maCombo = $(this)[0];
					var DisplayOrNot; 
					//console.log(that,maCombo);
					if (testIfToDisplay(maCombo.options[maCombo.selectedIndex].text)){
						DisplayOrNot = true;
					//}else{
						//DisplayOrNot = maCombo.selectedIndex==maCombo.options.length-1;
					}
					parentShowHide(DisplayOrNot);
				});
				that.parent().hide();
			}

			//bloc checkbox
			var checks = $(':checkbox[name^=critere['+match[1]+'][valeur]]');
			if (checks.length){
				/*var libelle = $('#label_'+(/radio_id_(.*)__/.exec(this.className))[1])[0].innerHTML;
				DisplayOrNot = false;
				if (testIfToDisplay(libelle)){
					DisplayOrNot = true;
				}*/
				$(checks[checks.length-1]).click(function(){					
					parentShowHide($(this).is(':checked'));
				});
				that.parent().hide();
			}
			
			//bloc radio
			var radios = $('input[type="radio"][name^=critere['+match[1]+'][valeur]]');
			if (radios.length){
				$(radios).click(function(){
					var libelle = $('#label_'+(/radio_id_(.*)__/.exec(this.className))[1])[0].innerHTML;
					DisplayOrNot = false;   
					if (testIfToDisplay(libelle)){
						DisplayOrNot = true;
						//}else{ DisplayOrNot = $(this).val()==radios.length-1;
					}
					 //= testIfToDisplay(maCombo.options[maCombo.selectedIndex].text)
					parentShowHide(DisplayOrNot);					
				});
				that.parent().hide();
			}
		}
    });  
    
});
function verif_me()
{
    if (typeof activity == 'undefined') {
    	var activity = '';
    }
    var rgx = /\/act([0-9]{2,4})-/;
    if (rgx.test(document.location)){
        activity = (document.location+'').match(rgx)[1];
    }

	var con_textArea = 'Please provide a description of your request, including any important details of the work required';

    //alert(this.nom);
    //console.log(this);
    if (!document.form1.elements[this.nom]) return true;
    switch(this.type)
    {
        case "radio":
        	
            for(i=0;i<document.form1.elements[this.nom].length;i++)
            {
                if(document.form1.elements[this.nom][i].checked == true) return true;
            }
            return false;
        break;
        case "checkbox":
            test = eval(this.nom);
            //alert(document.form1.elements[this.nom]);
            for(i=0;i<test.length;i++)
            {
                if(document.form1.elements[test[i]].checked == true) return true;
            }
            return false;
        break;
        case "select":
            if(document.form1.elements[this.nom].selectedIndex) return true;
            else return false;
        break;
        case "text":
            if(document.form1.elements[this.nom].value == "") return false;
            else return true;
        break;
        case "textarea":
            //clean textarea
		    //var con_textArea = 'To ensure accurate estimates, please give all the important details.';
		    if(document.form1.elements[this.nom].value == con_textArea) {
		       document.form1.elements[this.nom].value = "";
		    }
		    else {
                if(document.form1.elements[this.nom].value == "" & document.form1.elements[this.nom].value.length < 1000) return false;
		    }
            return true;
        break;
    }
}

function critere_a_verif(id,nom,type,libelle)
{
    this.id = id;
    this.nom = nom;//peut etre un tableau notament pour les checkboxs
    this.type = type;
    this.libelle = libelle;
    this.verif_me = verif_me;
    this.message_critere = message_critere;
}

function message_critere()
{
	switch(this.type)
	{
		case "radio":
			return "Select a choice for '"+ this.libelle +"'";
		break;
		case "checkbox":
			return "Select a choice for '"+ this.libelle +"'";
		break;
		case "select":
			return "Select a choice for '"+ this.libelle +"'";
		break;
		case "text":
			return "Fill in the field '"+ this.libelle + "'";
		break;
		case "textarea":
			return "Fill in the field '"+ this.libelle + "'";
		break;
	}
	return 

}


function checkPostCode (toCheck) {
  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5

  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^([a-z][a-z]?[0-9]{1,2})(\\s*)([0-9][a-z][a-z])$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^([a-z][0-9][a-z])(\\s*)([0-9][a-z][a-z])$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^([a-z][a-z]?[0-9][a-z])(\\s*)([0-9][a-z][a-z])$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  if (valid) {return postCode;} else return false;
}

function verif()
{
	message="Please :\n";
	if(document.form1.cp.value == "")  
	  message +="- Fill in the work place postcode \n";
	else
	{
			StrNewStr=""; 
        	for(i=0;i<=document.form1.cp.value.length;i++){ 
           		StrChar=document.form1.cp.value.substring(i,i+1); 
           		if(StrChar!=" " ){ 
              		 StrNewStr=StrNewStr+StrChar; 
           		} 
		 	} 
			//if(StrNewStr.search(/^[0-9][0-9][0-9][0-9][0-9]$/)==0)
			if(checkPostCode(StrNewStr) != false)
				document.form1.cp.value=StrNewStr;
			else
			 	message +="- Postcode error: the poscode you filled in does not exists, please enter a valid postcode.\n";
			
			
		}
	for(t=0; t<tab_element.length ;t++)
	{
		if(!tab_element[t].verif_me()) message +="- "+ tab_element[t].message_critere() +"\n";
	}

	//if(document.forms[nomform].libelle.value == "") message +="- Spécifier un libelle pour le critère\n";
	//if(document.forms[nomform].question.value == "") message +="- Spécifier une question à afficher\n";
	//if(document.forms[nomform].elements["tab_valeur[]"].length < 1 | document.forms[nomform].elements["tab_valeur[]"].options[0].value =="bidon") message +="- Spécifier des Valeurs au critère\n";
	//if(document.zeform.type.selectedIndex) message +="- Choisir un Type de champ\n";
	if(message!="Please :\n")
	{
		alert(message);
		return false;
	}
	else return true;
}

