/**
 *  Fonctions pour les pages du guide d'entreprises webtotal
 * BP 200909
  */

function submitRecherche() {
    document.getElementById('gobutton').click();
    return false;
}

function searchEntreprises() {
    var valq = document.forms['formInscriptionEntreprise'].q;
    if (valq.value.length >= 3) {
	    document.getElementById("selectionTitre").style.visibility = "hidden";
	    document.getElementById("organizationSelelection").style.visibility = "hidden";
	    document.getElementById("inscriptionOptionsAfterSearch").style.visibility = "hidden";
	    document.getElementById("orgInfo").style.visibility = "hidden";
	    doc = new XML();
	    doc.setAttribute("searchQuery", document.formInscriptionEntreprise.q.value);
	    doc.addListener(onSearchedEntreprises);
	    doc.sendAndLoad("/wt/actions-guide-searchOrg.do");
    }
    else {
        alert("La recherche doit \u00EAtre d\u0027un minimum de 3 caract\u00E8res");
    }
}

function onSearchedEntreprises(response) {
    var xmldoc = response.responseXML;
    var liste = document.getElementById("organizationSelelection");
    var GBLorgs = getItems(xmldoc, "Organizations").items();
    var GBLorgsL = GBLorgs.length;
    if (GBLorgsL != 0) {
        document.getElementById("selectionTitre").style.visibility = "visible";
        document.getElementById("organizationSelelection").style.visibility = "visible";
        document.getElementById("inscriptionOptionsAfterSearch").style.visibility = "visible";
    }
    var orgs = getItems(GBLorgs[0], "Organization").items();
    //var orgs = xmldoc.evaluate('//Organization', xmldoc, null, XPathResult.ANY_TYPE, null) ;
    var orgsL = orgs.length;
    removeAllOptions(liste);
    for(var i1=0; i1<orgsL; i1++){
        var org = orgs[i1];
        addOption(liste, org.getAttribute("name"), org.getAttribute("id"), false);
    }
}

function loadOrgForm(orgId) {
    doc = new XML();
    doc.addListener(onLoadSignupOrg);
    doc.setAttribute("organizationId", orgId);
    doc.sendAndLoad("/wt/actions-guide-getOrgInfo.do");
}

function onLoadSignupOrg(response) {
    var doc = response.responseXML.documentElement;
    document.getElementById('org1').innerHTML = doc.getAttribute("name");
    document.getElementById('org2').innerHTML = doc.getAttribute("address");
    document.getElementById('org3').innerHTML = doc.getAttribute("address2");
    document.getElementById('org4').innerHTML = doc.getAttribute("city");
    document.getElementById('org5').innerHTML = doc.getAttribute("province");
    document.getElementById('org6').innerHTML = doc.getAttribute("country");
    document.getElementById('org7').innerHTML = doc.getAttribute("postalCode");
    document.getElementById('org8').innerHTML = decodeEmail(doc.getAttribute("email"));
    document.getElementById('org9').innerHTML = doc.getAttribute("web");
    /*document.getElementById('org10').innerHTML = doc.getAttribute("phone");
    document.getElementById('org11').innerHTML = doc.getAttribute("fax");*/

}

function clearOrgInfoField() {
    for (var i = 1; i<=9; i++) {
        var fieldName = "org"+i;
        document.getElementById(fieldName).innerHTML = "";
    }
    document.getElementById('contName').innerHTML = "";
}

function decodeEmail(v, n){
    var c = v.split(";");
    var r = "";
    var k = c.length & 1;

    for(var i=c.length-2;i>=0;i--){
        r += String.fromCharCode(c[i] >> (((i + k) & 1) + 1));
    }

    if(!n){
        n = r;
    }

    return "<a href='mailto:"+r+"'>"+n+"</a>";
}

function lookForMainContact() {
    var orgId = document.getElementById('organizationSelelection').options[document.getElementById('organizationSelelection').selectedIndex].value;
    doc = new XML();
    //doc._method = "POST";
    doc.addListener(onLookedForContact);
    doc.setAttribute("organizationId", orgId);
    doc.sendAndLoad("/wt/actions-guide-getOrgContact.do");
}

function onLookedForContact(response) {
    var xmldoc = response.responseXML.documentElement;
    var conts = getItems(xmldoc, "Person").items();
    var contsL = conts.length;
    var hasMainContact = "false";
    for(var i1=0; i1<contsL; i1++){
        var contact = conts[i1];
        document.getElementById('alertBox').style.display="block";
        hasMainContact = "true";
       	document.getElementById('contName').innerHTML = contact.getAttribute('firstName')+" "+contact.getAttribute('lastName')+" "+decodeEmail(contact.getAttribute('email'));
    }
    if (hasMainContact == "false") {
        document.getElementById('alertTitle').innerHTML = "Il n'y a pr&eacute;sentement aucun administrateur de cette inscription";
        document.getElementById('alertMessage').innerHTML = "Pour prendre possession de ce compte, <a href=\"javascript:submitOrganizationForm('true')\">cliquez ici</a>";
        document.getElementById('alertBox').style.display="block";
        //document.getElementById('formInscriptionEntreprise').submit();
    } else {
        document.getElementById('alertTitle').innerHTML = "Il y a d&eacute;j&agrave; un contact principal qui est administrateur de cette inscription";
        document.getElementById('alertMessage').innerHTML = "Si vous d&eacute;sirez remplacer ce contact principal, <a href=\"javascript:callReplaceMainContactForm()\">cliquez ici</a>";
        document.getElementById('alertBox').style.display="block";
    }
}

function callReplaceMainContactForm() {
    var selectionBox = document.getElementById('organizationSelelection');
    var orgId = selectionBox.options[selectionBox.selectedIndex].value;
    window.location = "/470/chasse-peche-411.html?page=subscribeOrgReplace&organizationId="+orgId;
}

function submitOrganizationForm(isfound) {
    if (isfound == 'false') {
        document.getElementById('formInscriptionEntreprise').action="/470/chasse-peche-411.html?page=subscribeOrgNew";
        document.getElementById('formInscriptionEntreprise').onSubmit="";
        document.getElementById('formInscriptionEntreprise').submit();
    } else if(isfound == 'true') {
        var selectionBox = document.getElementById('organizationSelelection');
        var orgId = selectionBox.options[selectionBox.selectedIndex].value;
        document.getElementById('formInscriptionEntreprise').action="/470/chasse-peche-411.html?page=subscribeOrgChange&organizationId="+orgId;
        document.getElementById('formInscriptionEntreprise').submit();
    }
}

function fillOrgForm(orgId) {
    doc = new XML();
    doc.addListener(onFillSignupOrg);
    doc.setAttribute("organizationId", orgId);
//	doc.setAttribute("uniqId", Math.round(Math.random()*10000));
    doc.sendAndLoad("/wt/actions-guide-getOrgInfo.do");
}

function onFillSignupOrg(response) {
    var doc = response.responseXML.documentElement;
    document.getElementById('orgName_text').value = doc.getAttribute("name");
    document.getElementById('orgAddress_text').value = doc.getAttribute("address");
    document.getElementById('orgAddress2_text').value = doc.getAttribute("address2");
    document.getElementById('orgCity_text').value = doc.getAttribute("city");
    document.getElementById('orgProvince_hidden').value = doc.getAttribute("province");
    var provinceSelect = document.getElementById('selectProvincesOrg');
    var provinceId = doc.getAttribute("provinceId");
	for(var id = 0; id<provinceSelect.options.length; id++) {
		if(provinceSelect.options[id].value == provinceId) {
			provinceSelect.selectedIndex = id;
			break;
		}
	}
    document.getElementById('orgCountry_hidden').value = doc.getAttribute("country");
    var countrySelect = document.getElementById('selectCountriesOrg');
    var countryId = doc.getAttribute("countryId");
	for(var id2 = 0; id2<countrySelect.options.length; id2++) {
		if(countrySelect.options[id2].value == countryId) {
			countrySelect.selectedIndex = id2;
			break;
		}
	}
    document.getElementById('orgPostalCode_text').value = doc.getAttribute("postalCode");
    document.getElementById('orgEmail_text').value = doc.getAttribute("email");
    document.getElementById('orgWeb_text').value = doc.getAttribute("web");
    document.getElementById('orgPhone_text').value = doc.getAttribute("phone");
    document.getElementById('orgFax_text').value = doc.getAttribute("fax");
    //document.getElementById('orgCellPhone_text').value = doc.getAttribute("cellPhone");
    var sectionSelect = document.getElementById('selectSectionOrg');
    var sectionId = doc.getAttribute("sectionId");
	for(var id3 = 0; id3<sectionSelect.options.length; id3++) {
		if(sectionSelect.options[id3].value == sectionId) {
			sectionSelect.selectedIndex = id3;
			break;
		}
	}
}
/*
function fillOrgForm(orgId) {
    var doc = response.responseXML.documentElement;
    document.getElementById('orgName_text').value = doc.getAttribute("name");
    document.getElementById('orgAddress_text').value = doc.getAttribute("address");
    document.getElementById('orgAddress2_text').value = doc.getAttribute("address2");
    document.getElementById('orgCity_text').value = doc.getAttribute("city");
    document.getElementById('orgProvince_hidden').value = doc.getAttribute("province");
    document.getElementById('orgCountry_hidden').value = doc.getAttribute("country");
    document.getElementById('orgPostalCode_text').value = doc.getAttribute("postalCode");
    document.getElementById('orgEmail_text').value = doc.getAttribute("email");
    document.getElementById('orgWeb_text').value = doc.getAttribute("web");
    document.getElementById('orgPhone_text').value = doc.getAttribute("phone");
    document.getElementById('orgFax_text').value = doc.getAttribute("fax");
    document.getElementById('orgCellPhone_text').value = doc.getAttribute("cellPhone");
}
*/

function validateOrgForm(pageType) {
//	alert(pageType);
    Field.BACKGROUND_COLOR = "#FFF";
    tb = new TabbedPane();
    personAdd = new TabbedPaneSection("personAdd");
    if(pageType == "newOrg") {
	    personAdd.addField("person4","person_error4","required");
	    personAdd.addField("person5","person_error5","required");
	    personAdd.addField("password_text","password2_error","password_compare|password2_text");
	    personAdd.addField("password2_text","password2_error","password_compare|password_text");
	    personAdd.addField("email_text","email_error","emailexists");
	    personAdd.addField("orgName_text","orgName_error","required");
	    personAdd.addField("orgAddress_text","orgAddress_error","required");
	    personAdd.addField("orgCity_text","orgCity_error","required");
	    personAdd.addField("orgPhone_text","orgPhone_error","required");
	    personAdd.addField("orgPostalCode_text","orgPostalCode_error","required");
	    personAdd.addField("orgEmail_text","orgEmail_error","email");
    } else if(pageType == "changeOrg") {
	    personAdd.addField("person4","person_error4","required");
	    personAdd.addField("person5","person_error5","required");
	    personAdd.addField("password_text","password2_error","password_compare|password2_text");
	    personAdd.addField("password2_text","password2_error","password_compare|password_text");
	    personAdd.addField("email_text","email_error","emailexists");
	    personAdd.addField("orgName_text","orgName_error","required");
	    personAdd.addField("orgAddress_text","orgAddress_error","required");
	    personAdd.addField("orgCity_text","orgCity_error","required");
	    personAdd.addField("orgPhone_text","orgPhone_error","required");
	    personAdd.addField("orgPostalCode_text","orgPostalCode_error","required");
	    personAdd.addField("orgEmail_text","orgEmail_error","email");
    } else if(pageType == "replace") {
	    personAdd.addField("person4","person_error4","required");
	    personAdd.addField("person5","person_error5","required");
	    personAdd.addField("password_text","password2_error","password_compare|password2_text");
	    personAdd.addField("password2_text","password2_error","password_compare|password_text");
	    personAdd.addField("email_text","email_error","emailexists");
    }
    tb.addSection(personAdd);

	if (tb.handleSubmit() == false) {
        return false;
    } else {
        return true;
    }
}


/**
 *  Fonctions de validation des formulaires
 */

/**
 *@param field L'ID du champ du formulaire
 *@param error L'ID de l'élément pour afficher les messages d'erreur
 *@param validations Un Array contenant les validations pour ce champ
 *@param name Le nom du champ a envoyer au serveur
 *@param type Le type de champ (Field.STRING ou Field.NUMERIC)
 */
Field = function(field, error, validations, name, type) {
    
    this._field = field;
    this._error = error;
    this._validations = validations;
    this._isAutoSaved = !isNaN(type);
    this._name = name;
    this._type = type;

    
    if(document.getElementById(this._field) != null) {
        this._fieldEl = document.getElementById(this._field);
        this._fieldEl.onchange = Delegate.create(this, this.isValid);
    }
    else
        this._fieldEl = this._field;
    
 
    this._fieldValue = "";
    if(typeof this._fieldEl != 'string' && this._fieldEl.value)
        this._fieldValue = this._fieldEl.value;
    

    this._errorEl = document.getElementById(this._error);

    
    
    for(var i in validations){       
        validations[i].__field = this._fieldEl;       
        if(validations[i].init){
            validations[i].init(this._fieldEl);
        }
    }
}

Field.BACKGROUND_COLOR = "#FFF";
Field.ERROR_COLOR = "#FFFFCC";


/**
 *
 */
Field.getValidations = function(str){
    
    var validations = [];
    var params = str.split(",");    
    
    for(var i=0; i<params.length; i++){
        var temp = params[i];
        if("required" == temp){
            validations.push(Validation.REQUIRED);
        }
        else if("int" == temp){
            validations.push(Validation.INTEGER);
        }
        else if("float" == temp){
            validations.push(Validation.FLOAT);
        }
        else if("image" == temp){
            validations.push(Validation.IMAGE());
        }
        else if("email" == temp) {
            validations.push(Validation.EMAIL());
        }
        else if("link" == temp) {
            validations.push(Validation.LINK());
        }
        else if("emailexists" == temp) {
            validations.push(Validation.EMAILEXISTS());
        }        
        else if(temp.indexOf("date_after") > -1) {
            validations.push(Validation.DATE_AFTER(temp.split("|")[1]));
        }
        else if(temp.indexOf("password_compare") > -1) {
            validations.push(Validation.PASSWORD_COMPARE(temp.split("|")[1]));
        }
        else if(temp.indexOf("noteq") > -1){
            validations.push(Validation.NOT_EQUALS(temp.split("|")[1]));
        }
        else if("tinymce" == temp) {
            validations.push(Validation.TINYMCE);
        }
        else if(temp.indexOf("strlen") > -1){
            var t = temp.split("|");
            validations.push(Validation.STRING_LENGTH(parseInt(t[1]), parseInt(t[2])));
        }
        else if(temp.indexOf("range") > -1){
            var t = temp.split("|");
            validations.push(Validation.NUMERIC_LENGTH(parseInt(t[1]), parseInt(t[2])));
        }
        else if(temp.indexOf("update") > -1){
            var t = temp.split("|");
            validations.push(Validation.UPDATE(t[1], t[2]));
        }
        else if(temp.indexOf("formula") > -1){
            var t = temp.split("|");
            validations.push(Validation.FORMULA(t[1], t[2]));
        }
    }
    
    return validations;
}

/**
 *
 */
Field.getDigitOnly = function(field) {
    var value = field.value; 
    var length = value.length;
    var result = "";
    for(var i=0; i<length; i++) {
        var ch = value.charAt(i);        
        if(!isNaN(ch) && (ch != " " || ch == ".")) {
            result += value.charAt(i);
        }
    }
    
    return parseFloat(result); 
}



/**
 *
 */
Field.prototype.isValid = function() {      
    
    for(var i=0; i<this._validations.length; i++) {     
        if(!this._validations[i].isValid(this._fieldEl,this._fieldValue)) {
            this._errorEl.style.display = "block";
            this._errorEl.innerHTML = this._validations[i].getMessage();

            if(typeof this._fieldEl != 'string')
                this._fieldEl.style.backgroundColor = Field.ERROR_COLOR;
            return false;            
        }else {
            if(this._validations[i].isCancellable()){
                return true;
            }
        }
    }
    
    this._errorEl.innerHTML = "&nbsp;";
    if(typeof this._fieldEl != 'string')
        this._fieldEl.style.backgroundColor = Field.BACKGROUND_COLOR;
    this._errorEl.style.display = "none";           
    this._fieldValue = this._fieldEl.value;
    
    return true;
}

Field.STRING = 1;
Field.NUMERIC = 2;


Validation = {};

/**
 *
 */
Validation.REQUIRED = {
    isValid : function(field, oldValue){
        if(field.value == null || field.value == "") {
             return false;
        }
        
        return true;
    },
    getMessage : function(){ 
        return "Ce champ est requis"; 
    },
    isCancellable : function(){ 
        return false; 
    },
    toString : function(){ 
        return "REQUIRED";
    }
};



Validation.IMAGE = function() {
    return {
        isValid : function(field, oldValue){        
            return field.value.toLowerCase().match(/^.*(jpg|jpeg|gif)$/);            
        },
        getMessage : function(){ 
            return "Le fichier doit &ecirc;tre de type JPG, JPEG ou GIF."; 
        },
        isCancellable : function(){ 
            return false; 
        },
        toString : function(){ 
            return "UPDATE" 
        },
        init : function(field){  
            
        }
    };
}


Validation.UPDATE = function(name, fieldName) {
    return {
        isValid : function(field, oldValue){ 
            FormUpdate.notifyContext(name, fieldName, field.value);
            return true; 
        },
        getMessage : function(){ 
            return ""; 
        },
        isCancellable : function(){ 
            return false; 
        },
        toString : function(){ 
            return "UPDATE" 
        },
        init : function(field){          
            FormUpdate.notifyContext(name, fieldName, field.value);
            
            field.onkeyup = function(){
                FormUpdate.notifyContext(name, fieldName, field.value);
            }
        }
    };
}

Validation.FORMULA = function(name, formula) {
    
    var val = {
        isValid : function(field, oldValue){ 
            return true; 
        },
        getMessage : function(){ 
            return ""; 
        },
        isCancellable : function(){ 
            return false; 
        },
        toString : function(){ 
            return "FORMULA"; 
        },
        update : function(evt){        
            var temp = FormUpdate.compute(evt.context, formula);
            if(temp == null || isNaN(temp)){
                val.__field.value = "";
            }else{
                val.__field.value = temp;
            }
        }
    };
    
    FormUpdate.getContext(name).events.addEventListener("update", val.update);
    
    return val;
}


/**
 *
 */
Validation.NO_WHITESPACE = {
    
    isValid : function(field, oldValue){
        var str = field.value;
        if(!str) { 
            return false;
        }else{
            str = str.replace(/^\s*|\s*$/g, "");            
            if(str.length > 0){
                field.value = str;
                return true;
            }
            return false;
        }
    },
    getMessage : function() {
        return "Ce champ ne peut &ecirc;tre que des espaces blancs.";
    },
    isCancellable : function() {
        return false; 
    },
    toString : function() { 
        return "NO_WHITESPACE"; 
    }
    
}

/**
 *
 */
Validation.INTEGER = {
    isValid : function(field, oldValue){     
        var value = field.value;
        var length = value.length;
        for(var i=0; i<length; i++) {
            if(isNaN(value.charAt(i))) {                
                field.value = oldValue;
                return false;
            }
        }
        return true; 
    },
    getMessage : function(){ 
        return "Ce champ doit &ecirc;tre un nombre entier.";
    },
    isCancellable : function(){ 
        return false; 
    },
    toString : function(){ 
        return "INTEGER" 
    }
}


/**
 *
 */
Validation.INTEGER_OR_ZERO = {
    
    isValid : function(field, oldValue){     
        var value = field.value;
        var length = value.length;
        for(var i=0; i<length; i++) {
            if(isNaN(value.charAt(i))) {                
                field.value = oldValue;
                field.value = 0;
            }
        }
        return true; 
    },
    isCancellable : function(){ 
        return false; 
    },
    toString : function(){ 
        return "INTEGER" 
    }
    
}

/**
 *
 */
Validation.FLOAT = {
    isValid : function(field, oldValue) { 
        var valid = true;
        var dotUsed = false;
        var value = field.value;
        var length = value.length;
        
        for(var i=0; i<length; i++) {
            var ch = value.charAt(i);
            if(ch == ".") {
                if(dotUsed) {
                    field.value = oldValue;
                    return false;
                }else{
                    dotUsed = true;
                }
            }
            else if(isNaN(ch)) {
                field.value = oldValue;
                return false;
            }
        }
        return true; 
    },
    getMessage : function(){ 
        return "Ce champ doit &ecirc;tre un nombre r&eacute;el."; 
    },
    isCancellable : function(){ 
        return false; 
    },
    toString : function(){ 
        return "FLOAT" 
    }
}


/**
 *
 */
Validation.NOT_EQUALS = function(value) {
    return {
        isValid : function(field, oldValue){ 
            return field.value != value; 
        },
        getMessage : function(){ 
            return "Ce champ est requis"; 
        },
        isCancellable : function(){ 
            return false; 
        },
        toString : function(){ 
            return "NOT_EQUALS('"+value+"')" 
        }
    };
}

/**
 *
 */
Validation.STRING_LENGTH = function(min, max) {
    return {
        
        isValid : function(field, oldValue) {
            try{
                if(!isNaN(min) && field.value.length < min) {
                    this._errorType = "min";
                    return false;
                }
                if(!isNaN(max) && field.value.length > max) {
                    this._errorType = "max";
                    return false;
                }
            }catch(e){
                alert("error : " + e + " in " + this.toString());
            }
            return true;
        },
        
        isCancellable : function(){ return false; },
        
        getMessage : function() {
            if(this._errorType == "min"){
                return "Ce champ doit avoir un minimum de " + min + 
                " charact&egrave;res."; 
            }
            if(this._errorType == "max"){
                return "Ce champ doit avoir un maximum de " + max + 
                " charact&egrave;res."; 
            }
            return "&nbsp;";
        },
        
        toString : function(){ return "STRING_LENGTH("+min+","+max+")" }
    };
}

/**
 *
 */
Validation.NUMERIC_LENGTH = function(min, max) {
    return {
        
        isValid : function(field, oldValue) {
            //var value = parseInt(Field.getDigitOnly(field));
            var value = parseFloat(field.value);
            

            if(isNaN(min) == false) {
                if(value < min) {
                    this._errorType = "min";
                    return false;
                }
            }
            
    
            if(isNaN(max) == false) {
                if(value > max) {
                    this._errorType = "max";
                    return false;
                }
            }
         
            return true;
        },
        
        getMessage : function() {
            if(this._errorType == "min"){
                return "La valeur de ce champ doit &ecirc;tre sup&eacute;rieur &agrave; " + min + "."; 
            }
            if(this._errorType == "max"){
                return "La valeur de ce champ doit &ecirc;tre inf&eacute;rieur &agrave; " + max + "."; 
            }
            return "&nbsp;";
        },
        
        isCancellable : function(){ 
            return false; 
        },
        
        toString : function(){ 
            return "NUMERIC_LENGTH("+min+","+max+")";
        }
    };
}

/**
 * Validation pour la saisie double de mot de passe (inscription ou changement
 * de mot de passe)
 * 
 * @param (String) Id du champs du 2e champs de mot de passe
 */
Validation.PASSWORD_COMPARE = function(fieldCompare) {
    var enoughChar = true;
    var passSame = true;
    return {
        isValid : function(field,oldValue) {
            var input1 = field;
            var input2 = document.getElementById(fieldCompare);
            
            //Dans le cas où l'usager n'a pas saisie un des deux champs 
            //la différence n'est pas tenue en compte
            
            enoughChar = (input1.value.length > 3);
            
            passSame = (input1.value == "" || input2.value == "" || 
            input1.value == input2.value);
            
            return enoughChar && passSame;
        },
        
        getMessage : function() {
            fieldCompare.value = fieldCompare.value;
            if (!enoughChar) {
                return "Le mot de passe doit &ecirc;tre au moins 4 charact&egrave;res.";
            } else {
                return "Les deux mots de passe diff&egrave;rent.";
            }
        },
        
        isCancellable : function() { 
            return false; 
        },
        
        toString : function() {
            return "PASSWORD_COMPARE()";
        }
    };
}

/**
 * Validation basique de courriel
 */
Validation.EMAIL = function() {
    return {
        isValid : function(field,oldValue) {
            var emailParts = field.value.split("@");
            
            if(emailParts.length < 2) //Ne contient pas de @
                return false;
            
            if(!(emailParts[1].indexOf(".") != -1)) //N'a pas de domaine
                return false;
            
            return true;
        },
        
        getMessage : function() {
            return "Le courriel n'est pas valide.";
        },
        
        isCancellable : function() { 
            return false; 
        },
        
        toString : function() {
            return "EMAIL()";
        }
    };
}


/**
 * Validation d'un lien
 */
Validation.LINK = function() {
    return {
        isValid : function(field,oldValue) {
            //console.info(field.value.indexOf("http://"));
            return (field.value.indexOf("http://") == 0 || field.value == "");
        },
        
        getMessage : function() {
            return "Votre lien doit d&eacute;buter par \"http://\".";
        },
        
        isCancellable : function() { 
            return false; 
        },
        
        toString : function() {
            return "LINK()";
        }
    };
}

/**
 * Validation du contenu de tinymce
 */
Validation.TINYMCE = {
    isValid : function(field,oldValue) {
        var value;
        if(typeof field == 'object')
            value = tinyMCE.getContent(field.id);
        else
            value = tinyMCE.getContent(field)
            
        if(value == null || value.length == 0)
            return false;
        
        return true;
    },
        
    getMessage : function() {
        return "Ce champ est requis";
    },
        
    isCancellable : function() { 
        return false; 
    },
        
    toString : function() {
        return "TINYMCE";
    }
};


/**
 * Vérification qu'une date vienne après une autre
 */
Validation.DATE_AFTER = function(secondDate) {
    return {
        isValid : function(field,oldValue) {
            var valueAfter = field.value;
            var valueBefore = document.getElementById(secondDate).value;
            //console.info("valueAfter: "+valueAfter);
            //console.info("valueDefore: "+valueBefore);
            
            res = dateCompare(valueAfter,valueBefore);
            //console.info("res: "+res);
            return (res > 0);
            /*
            var partsAfter = valueAfter.split("/");
            var partsBefore = valueBefore.split("/");
             
            alert(partsAfter);
            if(!(partsAfter.length < 5 || partsBefore.length < 5))
            {
                alert(1);
             
                var dateAfter = new Date();
                dateAfter = Date.UTC(partsAfter[0],partsAfter[1],partsAfter[2],partsAfter[3],partsAfter[4],0,0);
             
                var dateBefore = new Date();
                dateBefore = Date.UTC(partsBefore[0],partsBefore[1],partsBefore[2],partsBefore[3],partsBefore[4],0,0);
             
                console.info("Date: "+dateAfter.toLocaleString());
                console.info("Date: "+dateBefore.toLocaleString());
            }*/
            //return true;  
        },
        
        getMessage : function() {
            return "La date doit &ecirc;tre plus r&eacute;cente que la date pr&eacute;c&eacute;dente.";
        },
        
        isCancellable : function() { 
            return false; 
        },
        
        toString : function() {
            return "DATE_AFTER()";
        }
    };
}



/**
 * Méthodes de comparaison de date (String)
 */
function dateCompare(dateString1,dateString2) {
    var partsAfter = dateString1.split("/");
    var partsBefore = dateString2.split("/");
    
    //alert(partsAfter);
    if(!(partsAfter.length < 5 || partsBefore.length < 5)) {
        //alert(1);
        
        var dateAfter = new Date();
        dateAfter = Date.UTC(partsAfter[0],partsAfter[1],partsAfter[2],partsAfter[3],partsAfter[4],0,0);
        
        var dateBefore = new Date();
        dateBefore = Date.UTC(partsBefore[0],partsBefore[1],partsBefore[2],partsBefore[3],partsBefore[4],0,0);
        
        //console.info("Date: "+dateAfter);
        //console.info("Date: "+dateBefore);
        
        if (dateAfter > dateBefore)
            return 1;
        else if (dateAfter < dateBefore)
            return -1;
        else
            return 0;
        
    }
    return 9; //Format invalide
    //console.info("Date invalide");
}

/**
 * Validation d'un email s'Il exite dans la bd ou non
 */

//var recu = false;

Validation.EMAILEXISTS = function() {
    var exists = false;
    var invalid = false;
    var emailInvalid = false;
    var email;
    return {
        isValid : function(field,oldValue) {
            email = field.value;
            
            if (email == "") {
                emailInvalid = true;
            } else {
            // TODO: controle email
/*
                try {                            
                    doc = new XML();
                    doc.addListener(function() {});
                    doc.setAttribute("email", field.value);
                    doc.setAttribute("uniqId", Math.round(Math.random()*10000));
                    doc.setAsyn(false);
                    response = doc.sendAndLoad("actions-existsUser.do");
                    
                    if(response.indexOf('true') != -1){
                        exists = true;
                        showExistsAlert(email);
                    } else if (response.indexOf('invalid') != -1) {
                        showInvalidAlert(email);
                        invalid = true;
                    } else if (response.indexOf('emailInvalid') != -1) {
                        emailInvalid = true;
                    }
                } catch(e) {
                    alert('err: '+e);
                }
*/
            }
            var resp = true;
            if (emailInvalid) { 
                resp = false; 
            } else if (exists) { 
                resp = false; 
            } else if (invalid) { 
                resp = false; 
            }
            return (resp);
        },
        
        getMessage : function() {
            if (emailInvalid) {
                emailInvalid = false;
                hideAlert();
                return "Ce courriel n'est pas valide.";
            } else if (exists) {
                exists = false;
                return "Ce courriel existe d&eacute;j&agrave;.";
            } else if (invalid) {
                invalid = false;
                return "Ce compte est déjà existant, mais inactif.";
                //return "Vous vous &ecirc;tes d&eacute;j&agrave; inscrit, nous vous avons envoy&eacute; un courriel explicatif pour activer votre compte.";
            }
        },
        
        isCancellable : function() { 
            hideAlert();
            return false; 
        },
        
        toString : function() {
            return "LINK()";
        }
    };
}

function hideAlert() {
    document.getElementById('alertBox').style.display = "none";
}

function showExistsAlert(email) {
    document.getElementById('alertMessage').innerHTML = "\u003Ca href\u003D\u0022page-lostpwd.do?email="+email+"\u0022\u003E Cliquez ici\u003C\u002Fa\u003E pour r\u00E9cup\u00E9rer votre mot de passe.";
    document.getElementById('alertBox').style.display = "block";
}

function showInvalidAlert(email) {
    document.getElementById('alertMessage').innerHTML = "Cependant\u002C le compte associé au courriel n\u0027a pas \u00E9t\u00E9 activ\u00E9\u002E\u003Cbr \u002F\u003E \u003Ca href\u003D\u0022javascript\u003AsendAction\u0028'"+email+"' \u0029\u003B\u0022\u003E Cliquez ici\u003C\u002Fa\u003E pour recevoir un courriel d\u0027activation \u00E0 cette adresse.";
    document.getElementById('alertBox').style.display = "block";
}

function initNewOrgForm() {
	alert('new');
//	            InitCommand.addCommand(function(){
//
                    Field.BACKGROUND_COLOR = "#FFF";

                    tb = new TabbedPane();
                    personAdd = new TabbedPaneSection("personAdd");
                    personAdd.addField("person4","person_error4","required");
                    personAdd.addField("person5","person_error5","required");
                    personAdd.addField("password_text","password2_error","password_compare|password2_text");
                    personAdd.addField("password2_text","password2_error","password_compare|password_text");
                    personAdd.addField("email_text","email_error","emailexists");
                    personAdd.addField("orgName_text","orgName_error","required");
                    personAdd.addField("orgAddress_text","orgAddress_error","required");
                    personAdd.addField("orgCity_text","orgCity_error","required");
                    personAdd.addField("orgPhone_text","orgPhone_error","required");
                    personAdd.addField("orgPostalCode_text","orgPostalCode_error","required");
                    personAdd.addField("orgEmail_text","orgEmail_error","email");
                    tb.addSection(personAdd);
//	            });
	
}

TabbedPane = function(sections) {	
    this._sections = [];
    this._sectionsMaps = {};
    this._currentSection = null;    
    if(sections && sections.length){
        for(var i=0; i<sections.length; i++){
            this.addSection(sections[i]);
        }
    }
}
var TB = TabbedPane.prototype;

TabbedPane.getInstance = function() {
    if(!this.__instance){
        this.__instance = new TabbedPane();
    }
    return this.__instance;
}

TB.submit = function(form){
    var invalidTab = this.getInvalidSection();       
    if(invalidTab != null){
        this.forceShowSection(invalidTab);
        invalidTab.showErrors();
    }else{
        this.preSubmit();
        form.submit();
    }
}

TB.handleSubmit = function(){
    var invalidTab = this.getInvalidSection();       
    if(invalidTab != null){
        this.forceShowSection(invalidTab);
        invalidTab.showErrors();
        return false;
    }else{
        this.preSubmit();
    }
    return true;
}

TB.addSection = function(section) {	
    var index = this._sections.length;	
    section.index = index;	
    this._sections[index] = section;
    this._sectionsMaps[section._id] = section;
}

TB.getSection = function(id) {	
    return this._sectionsMaps[id];
}


/**
 * override this method to add a behavior before submiting the form
 */
TB.preSubmit = function(){}


/**
 * Procède à la validation de toutes les sections,
 * Si une section n'est pas valide, elle sera retournée.
 * Si toute les section sont valide, on retourne null.
 */
TB.getInvalidSection = function() {
    for(var i=0; i<this._sections.length; i++){
        if(!this._sections[i].isValid()){
            return this._sections[i];
        }
    }   
    return null;
}



/**
 * Retourne la section précedente à celle envoyé en parametre
 */
TB.getPreviousSection = function() {
    for(var i=0; i<this._sections.length; i++){
        if(this._sections[i] === this._currentSection && i > 0){
            return this._sections[i-1];
        }
    }   
    return null;
}


/**
 *Affiche une section
 *@param tab Une référence à une instance de la classe "TabbedPaneSection"
 */
TB.forceShowSection = function(tab) {
    if(this._currentSection != null){
        this._currentSection.hide();
    }
    this._currentSection = tab;
    this._currentSection.show();
}


/**
 *Affiche une section (seulement si la section courante est valide)
 *@param id Le nom de la section
 */
TB.showSection = function(id) {    
    for(var i=0; i<this._sections.length; i++) {      
        if(this._sections[i]._id == id) {
            if(this._currentSection != null) {	                             
                if(this._currentSection.isValid()){	
                    this._currentSection.hide();
                }else{                    
                    this._currentSection.showErrors();
                    return;
                }
            }                        
            
            this._currentSection = this._sections[i];
            this._currentSection.show();
            this.onSelect(id);
            return;
        }
    }
}


/**
 *Retourne la section suivante. (null s'il n'y a pas de suivate) 
 */
TB.getNextSection = function() {
    for(var i=0; i<this._sections.length; i++){
        if(this._sections[i] === this._currentSection){
            return this._sections[i+1];
        }
    }
    return null;                       
}

TB.getCurrentSection = function() {    
    return this._currentSection;                       
}

TB.onSelect = function(){}

TabbedPaneSection = function(id) {
    this._id = id;
    this._element = document.getElementById("tab_" + id);
    this._visible = false;
    this._fields = [];
    this._btn = document.getElementById("btn_" + id);
}

var TBS = TabbedPaneSection.prototype;

TBS.addValidation = function(validation) {
    this._validations.push(validation);
}

TBS.addField = function(fieldName, error, validations, name, type) {
    if(typeof validations == "string"){
         validations = Field.getValidations(validations);
    }

    this._fields.push(new Field(fieldName, error, validations, name, type));
}

TBS.show = function() {
    // FIXME: should reworks again for multi-tabbed forms
    //this._element.style.display = "block";
    //this.onOpen();
}

TBS.hide = function() {
    // FIXME: should reworks again for multi-tabbed forms
    //this._element.style.display = "none";
    //this.onClose();
}

TBS.isOpen = function() {
    return (this._element.style.display == "block");
}

TBS.isValid = function() {
    var fields = this._fields;
    var length = fields.length;

    var ok = true;    
    for(var i=0; i<length; i++){
        if(!fields[i].isValid()){
            ok = false;
        }
    }    
    return ok;
}

TBS.showErrors = function(){
    alert("Certains champs ne sont pas valides. " + 
    "Assurez-vous que tous les champs sont valides avant de soumettre le formulaire.");
}

TBS.onOpen = function(){          
    
}

TBS.onClose = function(){ 
    
}
