﻿/**
 * Create a new header.
 * @constructor
 * @class Represents a HTTP Request header..
 */
Ext.onReady(function() {

	Ext.form.GeoBox = Ext.extend(Ext.form.ComboBox, {
		afterRender : function(){
        	Ext.form.TriggerField.superclass.afterRender.call(this);
		}
	});
});

var loadingTxt = {
	'en': "Loading...",
	'es': "Cargando...",
	'de': "Übertrage Daten...",
	'pt': "Carregando...",
	'nl': "Bezig met laden...",
	'it': "Caricamento in corso...",
	'fr': "En cours de chargement..."
};

var selectCityTxt = {
	'en': "Select a city from the list",
	'es': "Seleccione una ciudad propuesta",
	'de': "Wählen Sie ein vorgechlagen Stadt",
	'pt': "Selecione uma cidade proposta",
	'nl': "Selecteer een aangegeven stad",
	'it': "Seleziona una città proposta",
	'fr': "Merci de sélectionner votre ville dans la liste"
};

var selectRegionTxt = {
	'en': "Select your region from the list",
	'es': "Escoja su región en la lista",
	'de': "Wählen Sie Ihr Region in der Liste",
	'pt': "Escolha sua região na lista",
	'nl': "Selecteer Uw streek in de lijst",
	'it': "Scegli la tua regione nell’elenco",
	'fr': "Sélectionnez une région"
};

var geoname = function(baseurl) {
	var self = this;
	// 1er chargement
	// evite qu'on efface les donnees utilisateur avant un eventuel changement
	this.firstLoad = true,
	this.loadingTxt = typeof(currentLanguage) === 'undefined' ? loadingTxt['fr'] : loadingTxt[currentLanguage],
	this.selectCityTxt = typeof(currentLanguage) === 'undefined' ? selectCityTxt['fr'] : selectCityTxt[currentLanguage],
	this.selectRegionTxt = typeof(currentLanguage) === 'undefined' ? selectRegionTxt['fr'] : selectRegionTxt[currentLanguage],
	// URLS
	this.url_geoname_city = typeof(baseurl) === 'undefined' ? "/geoname/city_ext/" : baseurl + 'city_ext/',
	this.url_geoname_state = typeof(baseurl) === 'undefined' ? "/geoname/state/" : baseurl + 'state/',
    // FORMS ELEMS
	this.country_selectbox = Ext.get("id_countrycode",true) ? Ext.get("id_countrycode",true) : Ext.get(Ext.DomQuery.select("select[class*=geoCountryCode]")[0],true),
	this.region_input = Ext.get("id_region",true) ? Ext.get("id_region",true) : Ext.get(Ext.DomQuery.select("input[class*=geoRegion]")[0],true),  
	this.mobility_input = Ext.get("id_mobility",true) ? Ext.get("id_mobility",true) : Ext.get(Ext.DomQuery.select("select[class*=geoMobility]")[0],true),  
	this.municipality_input = Ext.get("id_municipality",true) ? Ext.get("id_municipality",true) : Ext.get(Ext.DomQuery.select("input[class*=geoMunicipality]")[0],true),
	this.place_input = Ext.get("id_place",true) ? Ext.get("id_place",true) : Ext.get(Ext.DomQuery.select("input[class*=geoPlace]")[0],true),
	this.postcode_input = Ext.get("id_postcode",true) ? Ext.get("id_postcode",true) : Ext.get(Ext.DomQuery.select("input[class*=geoPostCode]")[0],true),
	// TPLS
	this.resultTpl = new Ext.XTemplate('<p style="width:370px;padding:3px;background:red;color:#fff;margin-bottom:5px;">'+this.selectCityTxt+'</p><tpl for="."><div style="width:370px;" class="search-item">','<h3>{name}</h3>','{state} {[this.division(values)]}','</div></tpl>',{division: function(value) { if(value.division) { return ' - ' + value.division; } else { return ''; }  }}),
	// HTML ELEM
	this.region_p = false,
	this.region_label = false,
	this.region_loading = false,
	this.region_selectbox = false,
	this.mobility_p = false,
	this.mobility_label = false,
	this.mobility_selectbox = false,
	this.mobility_loading = false,
	// STORES
	this.ds_region = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url: this.url_geoname_state,
			methode: 'GET'
		}),
		sortInfo: {field: "name", direction: "ASC"},
		reader: new Ext.data.JsonReader({
			root: 'rows',
			totalProperty: 'results',
			id: 'code'
			}, ['code','name']
		)
	}),
	/* store municipality */
	this.ds_municipality = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url: this.url_geoname_city
		}),
		reader: new Ext.data.JsonReader({
			root: 'rows',
			totalProperty: 'results',
			id: 'place'
			}, [
				'place',
				{name: 'division', mapping: 'division'},
				{name: 'state', mapping: 'state'},
				{name: 'name', mapping: 'name'}
			]
		)
	});
	if(this.municipality_input) {
		// COMBO CITY
		this.city_combo = new Ext.form.GeoBox({
			minChars:2,
			id:'municipality_search',
			store: this.ds_municipality,
			displayField:'title',
			typeAhead: false,
			loadingText: 'Searching...',
			width: 400,
			minListWidth:400,
			hideTrigger:true,
			tpl: this.resultTpl,
			applyTo: this.municipality_input.dom.id,
			//renderTo:'MCVforms',
			itemSelector: 'div.search-item',
			onSelect: function(record) {
			 	self.place_input.dom.value = record.id;
				this.collapse();
			 	self.municipality_input.dom.value = record.data.name;
			}
		})
	}     
	/** 
	 * Function populate_region_id
	 * Peuple la selectbox region_id avec les région 
	 * correspondants au pays selectionne 
	 */
	this.populate_region = function() {
		this.region_selectbox.dom.options.length = 0;
		// on  loop sur les regions
		this.region_selectbox.dom.options[0] = new Option('--'+this.selectRegionTxt+'--','');
		for (var i = 1; i <= this.ds_region.getCount(); i++) {
			record = this.ds_region.getAt(i-1);
			this.region_selectbox.dom.options[i] = new Option(record.data.name,record.data.code);
		}
		// on selectionne la bonne options
		for (loop=0; loop < this.region_selectbox.dom.options.length; loop++) {
			if (this.region_selectbox.dom.options[loop].value == this.region_input.dom.value){
				this.region_selectbox.dom.options[loop].selected = true;
			}
		}
		//
		this.region_loading.dom.style.display = 'none';
		this.region_p.dom.style.display = '';
		this.region_selectbox.dom.style.display = '';  
	},
	/** 
	 * Function populate_region_id
	 * Peuple la selectbox region_id avec les région 
	 * correspondants au pays selectionne 
	 */
	this.populate_mobility = function(){
		this.mobility_selectbox.dom.options.length = 0;
		//
		var options = [];
		// on  loop sur les regions
		for (var i = 0; i < this.ds_region.getCount(); i++) {
			record = this.ds_region.getAt(i);
			this.mobility_selectbox.dom.options[i] = new Option(record.data.name,record.data.code);
			options.push(record.data.code)
		}
		// on selectionne la bonne options
		var mobility_list = this.mobility_input.dom.value.split(',');
		
		for (loop=0; loop < mobility_list.length; loop++) {
			if(options.indexOf(mobility_list[loop]) >= 0 ) {
				this.mobility_selectbox.dom.options[options.indexOf(mobility_list[loop])].selected = true;
			}  
		}
		//
		this.mobility_loading.dom.style.display = 'none';
		this.mobility_p.dom.style.display = 'block';
		this.mobility_selectbox.dom.style.display = 'block';  
	}; 
	/** 
	 * Function loadState
	 * Charge les regions 
	 * correspondants au pays selectionne 
	 */
	this.loadState = function() {
		if(this.country_selectbox.dom.value) {
			this.ds_region.baseParams = {'country_iso_alpha2':this.country_selectbox.dom.value};
			this.ds_region.load();
		} 
	}, 
	/** 
	 * Function clean_all
	 */   
	this.clean_all = function() {
		if(!this.firstLoad) {
			if(this.region_selectbox) this.region_input.dom.value = '';
			if(this.place_input) this.place_input.dom.value = '';
			if(this.municipality_input) this.municipality_input.dom.value = '';
			if (this.postcode_input) { this.postcode_input.dom.value = ''; } 
			if (this.mobility_input) { 
				this.mobility_input.dom.value = '';
				for (loop=0; loop < this.mobility_selectbox.dom.options.length; loop++) {
					this.mobility_selectbox.dom.options[loop].selected = false;
				} 
			}
		}
	},
	
	this.init = function() {
		//        
		if(!this.country_selectbox) {
			return;
		}
		if(this.mobility_input) {
			this.mobility_p= this.mobility_input.findParentNode('div',1,true);
			this.mobility_label = this.mobility_p.child('label');
			this.mobility_selectbox = this.mobility_label.insertHtml('afterEnd','<select class="vSelectMultipleField" multiple=\'multiple\'></select>',true);
			this.mobility_loading = this.mobility_label.insertHtml('afterEnd','<div class="loading-indicator">'+this.loadingTxt+'</div>',true); 
			this.mobility_loading.dom.style.display = 'none';
			this.mobility_input.dom.style.display = 'none';
			this.mobility_selectbox.dom.style.display = 'none';
		}

		if(this.region_input) {
			this.region_p = this.region_input.findParentNode('div',1,true);
			this.region_label = this.region_p.child('label');
			this.region_loading = this.region_label.insertHtml('afterEnd','<div class="loading-indicator">'+this.loadingTxt+'</div>',true);
			this.region_selectbox = this.region_label.insertHtml('afterEnd','<select class="vSelectField"></select>',true);
			this.region_loading.dom.style.display = 'none';
			//this.region_input.dom.style.display = 'none';
			this.region_selectbox.dom.style.display = 'none';
		}

		
		
		// EVENTS
		if(this.city_combo) {
			this.city_combo.on('expand',function() {
			   this.place_input.dom.value = '';
			},this);
		}
		//
		this.ds_region.on('beforeload', function()	{
			this.clean_all();
			//
			if(this.region_selectbox) {
				this.region_p.dom.style.display = '';
				this.region_loading.dom.style.display = '';
	    		this.region_selectbox.dom.style.display = 'none';   
			}
            //
			if(this.mobility_input) {
				this.mobility_p.dom.style.display = 'block'; 
				this.mobility_loading.dom.style.display = 'block';
 				this.mobility_selectbox.dom.style.display = 'none';
			}
		},this),
		//
		this.ds_region.on('load',function() {
			if(this.ds_region.getCount() > 0) {
				if(this.region_selectbox) {
					this.populate_region();  
				}
				//mobility
				if(this.mobility_input) {
					this.populate_mobility();
				} 
			} else {
				this.region_p.dom.style.display = 'none';
				if(this.mobility_input) {
					this.mobility_p.dom.style.display = 'none'; 
				}
			}
			//
			this.firstLoad = false;
		},this);
        //
		this.country_selectbox.on('change',function() {
			this.loadState();
		},this);
		//
		this.ds_municipality.on('beforeload', function()	{
			this.ds_municipality.baseParams.country = this.country_selectbox.dom.value;
			this.ds_municipality.baseParams.state = this.region_input.dom.value;
		},this);
		//
		if(this.region_selectbox) {
			this.region_selectbox.on('change',function(){ 
				this.clean_all();
				this.region_input.dom.value = this.region_selectbox.dom.value;
				this.city_combo.store.baseParams['state'] = this.region_input.dom.value;
			},this);
		}
		//
		if(this.mobility_input) {
			this.mobility_selectbox.on('change',function(){ 
				var selection = [];
				for(loop=0;loop < this.mobility_selectbox.dom.options.length; loop++) {
					if(this.mobility_selectbox.dom.options[loop].selected) {
						selection.push(this.mobility_selectbox.dom.options[loop].value);
					}
				}
				this.mobility_input.dom.value = selection.toString();
 			},this); 
		}
	}
	
	// CHARGEMENT DES REGIONS
	this.loadState();   
};