//Gestion des formualaires
var TravelForm = function(name,positionId){
    this.name = name;
    this.comboBox = [];
    this.autoComplete = [];
    this.datePickers = [];
    this.errorUrl = [];
	this.positionId = positionId;
}
TravelForm.prototype.getDiv = function(){
    if (this.div == null) {
        this.div = document.getElementById("form-div-" + this.name);
    }
    return this.div;
}
TravelForm.prototype.getForm = function(){
    if (this.form == null) {
        this.form = document.getElementById("form-" + this.name);
    }
    return this.form;
}
TravelForm.prototype.getTab = function(){
    if (this.tab == null) {
        this.tab = document.getElementById("tab-" + this.name);
    }
    return this.tab;
}

TravelForm.prototype.getSelectedPartner = function(){
    var pInput = this.getForm()[this.name + '-partner'];
    if (pInput != null && pInput.value != null) {
        return pInput.value;
    }
    else 
        if (pInput.length != null) {
            for (var i = 0; i < pInput.length; i++) {
                if (pInput[i].checked) {
                    return pInput[i].value;
                }
            }
            
        }
        else 
            return "undefined";
    
}

TravelForm.prototype.deselectAllPartners = function(){
    var pInput = this.getForm()[this.name + '-partner'];
    if (pInput != null && pInput.length != null) {
        for (var i = 0; i < pInput.length; i++) {
            pInput[i].checked = false;
        }
        
    }
    
}

TravelForm.prototype.findList = function(listName){
    for (var i = 0; i < this.comboBox.length; i++) {
        if (this.comboBox[i].name == listName) {
            return this.comboBox[i];
        }
    }
    for (var i = 0; i < this.autoComplete.length; i++) {
        if (this.autoComplete[i].name == listName ) {
        	return this.autoComplete[i];
        }
    }
	return null;
}

TravelForm.prototype.notify = function(propertyChangeInput){
    console.log("Modifiction d'un element de '" + propertyChangeInput.form.name + "' : " + propertyChangeInput.name + "=" + propertyChangeInput.value);
    var tf = propertyChangeInput.form.travelForm;
    for (var i = 0; i < this.comboBox.length; i++) {
        if (this.comboBox[i].dependencies.contains(propertyChangeInput.name)) {
            console.log("Dependency found : " + this.comboBox[i].name + " depends of " + propertyChangeInput.name);
            this.comboBox[i].update(propertyChangeInput);
        }
    }
    for (var i = 0; i < this.autoComplete.length; i++) {
        if (this.autoComplete[i].dependencies.contains(propertyChangeInput.name)) {
            console.log("Dependency found : " + this.autoComplete[i].name + " depends of " + propertyChangeInput.name);
            this.autoComplete[i].update(propertyChangeInput);
        }
    }
	var updated = this.findList(propertyChangeInput.name);
	if(updated != null){
		console.log("A list has been modified, we'll try to auto resolve depencies if needed. List modified : ");
		console.log(updated);
		updated.autoResolveDependencies();
	}
}
TravelForm.prototype.init = function(){
    this.getForm().travelForm = this;
    for (var i = 0; i < this.comboBox.length; i++) {
        this.comboBox[i].getCombo().selectedIndex = 0;
    }
    for (var i = 0; i < this.autoComplete.length; i++) {
        this.autoComplete[i].getField().value = "";
    }
    for (var i = 0; i < this.datePickers.length; i++) {
        this.datePickers[i].field.value = "";
    }
    this.deselectAllPartners();
}
TravelForm.prototype.checkForm = function(){
    if (this.getSelectedPartner() == "undefined" || this.getSelectedPartner() == undefined) {
        blinkDiv("partner-warn-"+this.name,1);
        return false;
    }
    else {
        return true;
    }
    
}
TravelForm.prototype.submit = function(){
    //TODO verifier que les chmaps sont complété correctement et que le partenaire est bien selectionné
    //Contruction d'une map contenant les valeurs des champs a envoyer, ainsi que le partenaire choisi
    try {
        //on verifie qu'un partenaire est bien selectionn�
        console.log("Submiting " + this.name);
		var errBox = document.getElementById('warn-message-'+this.name);
		if(errBox) errBox.style.display = "none";
        
        if (!this.checkForm()) {
            console.log(" --> No partner selected : break");
            return false;
        }
        var formMap = {};
		console.log(" --> Form : "+this.getForm());
        var elts = this.getForm().elements;
		if(elts ==null) elts = this.getForm().getElements();
		console.log(" --> Scanning elements "+elts);
        for (var i = 0; i < elts.length; i++) {
			console.log("  --> adding "+elts[i]+" "+elts[i].name);
            formMap[elts[i].name] = getFieldValue(elts[i]);
            console.log("   --> formMap[" + elts[i].name + "] =" + getFieldValue(elts[i]));
        }
        console.log("Sending form '" + this.name + "' with data : ");
        console.log(formMap);
		LoadIndicator.add();
		SearchListService.prepareSubmit(this.name, this.getSelectedPartner(), formMap,this.positionId, this.getSubmitCallback());
		return false;
    } 
    catch (ex) {
        console.error("Error when sending form : break !");
        console.error("Error "+ex.number+" : "+ex.description);
        return false;
    }
}

TravelForm.prototype.getSubmitCallback = function(){
	var _this = this;
	return function(map){
		console.log("Reciving form data to submit : ");
		console.log(map);
		LoadIndicator.remove();
		if (map['errorUrl'] == null && map['errorMessage'] == null) {
		
			// Tracking
			try {
				callTracking(map.trackingUrl+context+trackingUrl);
			} 
			catch (e) {
				console.error(e);
			}
			
				
				var uForm = document.getElementById('usefull-form');
				uForm.action = map.formAction;
				if (map.formType == "GET")
					uForm.method = 'get';
				else
					uForm.method = 'post';
				uForm.innerHTML = "";
				for (key in map) {
					if (key != "formAction" && key != "formType" && key != "trackingUrl") {
						uForm.innerHTML += '<input type="hidden" name="' + key + '" value="' + map[key] + '" />\n';
					}
				}
				console.log("Sending form : ");
				console.log(uForm);
				
		
				uForm.submit();
		
		}
		else 
			if (map['errorMessage'] == null) {
				window.open(map['errorUrl'], "_blank");
			}
			else {
				var errBox = document.getElementById('warn-message-' + _this.name);
				if (errBox) {
					errBox.innerHTML = map['errorMessage'];
					blinkDiv('warn-message-' + _this.name)
				}
				else 
					alert(map['errorMessage']);
				return false;
			}
	}
}

TravelForm.prototype.selectPartner = function(selected){
    if (selected) {
    	document.getElementById("partner-warn-"+this.name).style.display = "none";
        if (this.getSelectedPartner() != "none") {
            for (var i = 0; i < this.comboBox.length; i++) {
                this.comboBox[i].update();
            }
            for (var i = 0; i < this.autoComplete.length; i++) {
                this.autoComplete[i].refreshParams();
            }
        }
    }
}


