if(!ch){
	var ch = {};
}
if(!ch.exmachina){
	ch.exmachina = {};
}
if(!ch.exmachina.bravofly){
	ch.exmachina.bravofly = {};
}
ch.exmachina.bravofly.GeographicGroup = function(/* object */ctorArgs){
	this.domNode = $(ctorArgs.domNode);
	this.containerNode = $(ctorArgs.containerNode);
	this.addNode = $(ctorArgs.addNode);
	this.minFields = ctorArgs.minFields || this.minFields;
	this.maxFields = ctorArgs.maxFields || this.maxFields;
	this.symbols.SEARCHING = ctorArgs.searching || this.symbols.SEARCHING;
	this.searchLanguage = ctorArgs.searchLanguage || this.searchLanguage;
	this.areaPrompt = ctorArgs.areaPrompt || "";	
	this.nationPrompt = ctorArgs.nationPrompt || "";	
	this.autocompleteURL = ctorArgs.autocompleteURL || this.type;
    this.nationCompleteUrl = ctorArgs.nationCompleteUrl;
	this.type = ctorArgs.type || this.type;
	this.onClean = ctorArgs.onClean || this.onClean;
	this.defaultNation = ctorArgs.defaultNation || "";
    this.readOnly = !!ctorArgs.nationReadOnly;
    this.continentCode = ctorArgs.continentCode || "";
	this.fields = [];
    this.aspect = ctorArgs.aspect || "default";
	this.onChildComplete = ctorArgs.onComplete || this.onChildComplete;
    this.datasource = ctorArgs.datasource || this.datasource;
    this.onChangeNation = ctorArgs.onChangeNation || this.onChangeNation;
    this.onChangeArea = ctorArgs.onChangeArea || this.onChangeArea;
    this.firstOption = ctorArgs.firstOption;
    this.selectUrl = ctorArgs.selectUrl || this.selectUrl;
    this.nationUnderlined = !!ctorArgs.nationUnderlined;
    this.validateFromArea = !!ctorArgs.validateFromArea;
    this.onFirstSelectionChange = ctorArgs.onFirstSelectionChange || this.onFirstSelectionChange;
    this.onRemoveChild = ctorArgs.onRemoveChild || this.onRemoveChild;
    this.setCloserButtons = ctorArgs.setCloserButtons || this.setCloserButtons;
    this.onAddChild = ctorArgs.onAddChild || this.onAddChild;
    this.asynchAreaLoad = ctorArgs.asynchAreaLoad === false ? false : true;
    this.areaDataKey = ctorArgs.areaDataKey;
    this.selectContentType = ctorArgs.selectContentType || "";
    this.selectClass = ctorArgs.selectClass || ch.exmachina.bravofly.Select;
    for(var i = 0; i < this.minFields; i++){
		//this.fieldsCount++;
		this.createField();
	}

	this.bindEvents();
};

ch.exmachina.bravofly.GeographicGroup.prototype = {
	// ****************************************************************************************************
	// members
    _childNum: 0,
	nationPrompt: "",
	areaPrompt: "",
	fields: [],
	minFields: 1,
	maxFields: 2,
	searchLanguage: "EN",
	autocompleteURL: "",
    nationCompleteUrl: "",
	type: "",
	promptText: "",
    readOnly: false,
    defaultNation: "",
    continentCode: "",
    aspect: "",
    datasource: "net",
    selectUrl: "",
    nationUnderlined: false,
    groupData: null,
    nations: null,
    firstOption: null,
    validateFromArea: false,
    asynchAreaLoad: true,
    areaDataKey: "",
    selectClass: null,
    // hooks
    onAddChild: function(){},
    onRemoveChild: function(){},
    setCloserButtons: function(){
    	if(this.fields.length == 1){
    		this.fields[0].nationField.clearButton.style.visibility = "hidden";
    	}else{
    		this.fields[0].nationField.clearButton.style.visibility = "visible";
    	}
    },
    onFirstSelectionChange: function(){},
    onChangeNation: function(){},
    onChangeArea: function(){},
	onClean: function(){},
	// domNodes
	domNode: null,
	containerNode: null,
	addNode: null,
	// status
	disabled: false,
	// const
	symbols:{
		SEARCHING: "Searching..."
	},
	// ****************************************************************************************************
	// methods
    atLeastOneValid: function(){
        var validFields = 0,
        	targetField
        ;
		for(var i = 0; i < this.fields.length; i++){
			targetField = this.validateFromArea ? this.fields[i] : this.fields[i].areaField;
			if(targetField.isValid()){
				validFields++;
			}
		}
        return validFields;
    },
	getField: function(index){
		return this.fields[index];
	},
	getLastField: function(){
		return this.fields[this.fields.length - 1];
	},
	hideAddNode: function(){
		this.addNode.className = "ta_new_airport_hidden";
	},
	// hooks
	onChildComplete: function(){
	},
	// evt handlers
	clickHandler: function(){
		if(this.disabled){ return; }
        if(this.aspect != "doubleSelect"){
            if(this.fields.length < this.maxFields && this.allFreezed()){
            	if(!this.defaultNation || (this.defaultNation && this.fields[0].areaField.isValid())){
                    this.createField();
            	}
            }
        }else{
            if(this.fields.length < this.maxFields && this.atLeastOneValid()){
	            // riempio di nuovo aree e aeroporti
                var fld = this.createField();
                fld.nationField.enable();
                fld.areaField.enable();
                fld.nationField.fillInData(this.nations);
                fld.areaField.fillInData([{ key: "", value: "---" }]);
            }
        }
	},
	enableAddNode: function(){
		this.addNode.className="ta_new_airport";
	},
	disableAddNode: function(){
		this.addNode.className="ta_new_airport_disabled";
	},
    setNations: function(/** Object */ n){
        this.nations = n;
    },
    setGroupData: function(/** Object */ gd){
        this.groupData = gd;
    },
	createField: function(){
		var self = this;
		if(this.addNode){
			this.disableAddNode();
		}
		// GeographicInput here
        this._childNum++;
		this.fields.push(new ch.exmachina.bravofly.GeographicInput({
			geoCompleteURL: this.autocompleteURL,
            aspect: this.aspect,
            selectContentType: this.selectContentType,
            searchLanguage: this.searchLanguage,
			nodeId: this.domNode,
			containerNode: this.containerNode,
			areaPrompt: this.areaPrompt,
            nationCompleteUrl: this.nationCompleteUrl,
            continentCode: this.continentCode,
            datasource: this.datasource,
			nationPrompt: this.nationPrompt,
			onFirstSelectionChange: this.onFirstSelectionChange,
            areaDataKey: this.areaDataKey,
            defaultNation: this.defaultNation,
            pGroup: this,
            nationUnderlined: this.nationUnderlined,
            firstOption: this.firstOption,
            selectUrl: this.selectUrl,
            selectClass: this.selectClass,
            readOnly: this.readOnly,
            asynchAreaLoad: this.asynchAreaLoad,
            onChangeNation: this.onChangeNation,
            onChangeArea: this.onChangeArea,
			onFreeze: function(){ self.onComplete.call(self); },
			onClose: function(){ self.closeChild.call(self, this); }
		}));
        this._readOnlyCheck();
        this.onAddChild();
		var f = this.fields;
		this.setChildrenPosition();
        return f[f.length - 1];
	},
	setChildrenPosition: function(){
		var f = this.fields;
		for(var i = 0, zi = 100, l = f.length; i < l; i++){
			//console.log(this.fields[i].domNode);
			Element.absolutize(f[i].domNode);
			f[i].domNode.style.width = "100%";
			f[i].domNode.style.top = i * 22 + "px";
			f[i].domNode.style.zIndex = zi--;
		}
		this.addNode.style.top = 110 + (f.length) * 22 + "px";
	},
    _readOnlyCheck: function(){
        if(this.readOnly){
            if(this.fields.length == 1){
                this.fields[0].nationField.closerNode.style.visibility = "hidden";
            }else{
                this.fields[0].nationField.closerNode.style.visibility = "visible";
            }
        }
    },
	onComplete: function(/** Object */ self){
		if(this.addNode && this._childNum < this.maxFields && !this.defaultNation){
			this.enableAddNode();
		}
		this.onChildComplete();
	},
	bindEvents: function(){
		if(this.addNode){
			Event.observe($(this.addNode), 'click', this.clickHandler.bindAsEventListener(this));
		}
	},
	disable: function(){
		this.disabled = true;
	},
	enable: function(){
		this.disabled = false;
	},
	closeChild: function(/* GeographicalInput */ child){
		if(this.disabled){
			return;
		}
		var fields = this.fields;

		if(this.fields.length > this.minFields){
			var idx = fields.indexOf(child);
			child.destroy();
            this._childNum--;
			fields.splice(idx, 1);
			this.setChildrenPosition();
            this._readOnlyCheck();
		}else{
			child.clean();
		}
		if(this.aspect != "doubleSelect" && !this.defaultNation){
			if(this.addNode){
				if(!this.allFreezed()){
					this.disableAddNode();
				}else{
					this.enableAddNode();
				}
			}
		}else{
			// onRemoveChild
		}
	},
	collapse: function(){
		if(this.fields.length > 1 && !this.fields[0].disabled){
			this.fields[0].destroy();
			this.fields.splice(0, 1);
		}
	},
	removeField: function(index){
		this.fields[index].destroy();
        this._childNum--;
        this.fields.splice(index, 1);
		this.setChildrenPosition();
	},
	allAreasValid: function(){
		var validFields = 0;
		for(var i = 0, l = this.fields.length; i < l; i++){
			if(this.fields[i].areaField.isValid()){
				validFields++;
			}
		}
		return (validFields === l);
	},
	allValid: function(){
		var invalidFields = 0,
			freezedFields = 0
		;
		for(var i = 0; i < this.fields.length; i++){
			if(this.fields[i].isDisabled() === false && this.fields[i].isDirty() === true){
				invalidFields++;
			}
			if(this.fields[i].isFreezed()){
				freezedFields++;
			}
		}
		return !invalidFields && !!freezedFields;
	},
	allFreezed: function(){
		var unfreezedFields = 0;
		for(var i = 0; i < this.fields.length; i++){
			if(this.fields[i].isFreezed() === false){
				unfreezedFields++;
			}
		}
		return !unfreezedFields;
	},
	toString: function(){
		return "[ch.exmachina.bravofly.GeographicGroup]";
	}
};

// static methods
ch.exmachina.bravofly.FieldGroup.copy = function(cpyArgs){
	var src = cpyArgs.src,
		dest = cpyArgs.dest
	;
	dest.fieldNode.className = src.fieldNode.className;
	dest.closerNode.className = src.closerNode.className;
	dest.fieldNode.value = src.fieldNode.value;
	if(src.disabled){
		dest.disable();
	}else{
		dest.enable();
	}
};