﻿/*
 * Ext JS Library 2.2.1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

Ext.onReady(function(){
	var lang_contact_form = 'Formulaire de contact';
	var lang_general_info = 'Via le formulaire';
	var lang_title = 'Intitulé';
	var lang_choose_title = 'Veuillez choisir...';
	var lang_last_name = 'Nom';
	var lang_first_name = 'Prénom';
	var lang_address = 'Adresse';
	var lang_city = 'Ville';
	var lang_choose_city = 'Veuillez choisir une ville...';
	var lang_postal_code = 'Code postal';
	var lang_country = 'Pays';
	var lang_choose_country = 'Veuillez choisir un pays...';
	var lang_tel1 = 'Téléphone fixe';
	var lang_tel2 = 'Téléphone mobile';
	var lang_email = 'Email';
	
	var lang_saving = 'En train d\'envoyer...';
	var lang_submit = 'Envoyer';
	var lang_submit_ok = 'Les informations ont été enregistrées.';
	var lang_submit_error = 'Erreur de téléchargement';
	var lang_captcha_error = 'Erreur captcha';
	var lang_back = 'Retour en arrière';

	var pid = document.getElementById('mobi-contact-form-pid').innerHTML;
	var j = 0;
	var i = 0;
	
	var connUrl='/fileadmin/ressources_mob/mt_contact_form/form_functions.php';
	var conn = new Ext.data.Connection();
	var responseObject = new Object();
	conn.request({
		url: connUrl,
		method: 'POST',
		params:{
			actionMobi: 'getList',
			pid: pid
		},
		success: function(responseObject){	
			var json = Ext.util.JSON.decode(responseObject.responseText);
			var list = json.list[0];
			var currentModule = 0;
			
			var contactFormPanel = new Ext.Panel({
				id: 'mobi-mt-contact-form-top-panel',
				frame:true,
				width:'auto',
				title: json.title
			});

			// genarate the modules
			var panelArr = new Array();
			while (i < list.length){
				panelArr[i] = null;
				var module = list[i];
				if (module.length > 0){
					eval('var '+module+' = new '+module.toUpperCase()+'();'+
						module+'.on(\'finished\', function(panel){'+
							'var index = list.indexOf(panel.mobiClass.toLowerCase());'+
							'currentModule++;'+
							'panelArr[index]=panel;'+
							'if (currentModule == list.length){'+
								'j = 0;'+
								'while (j < panelArr.length){'+
									'contactFormPanel.add(panelArr[j]);'+
									'j++;'+
								'}'+
								
								'contactFormPanel.render(\'mobi-contact-form-top\');'+
								
							'}'+
						'});'
					);
					// var value = eval('json.'+module);
					var value = '';
					eval(module+'.create(pid, \''+value+'\');');
				}
				i++;
			}
			
			contactFormPanel.render('mobi-contact-form-top');
		},
		failure:function(){ 
			Ext.Msg.alert('ERR', lang_server_unreachable);
		}
	});
	
	var dsCityURL = mainUrl+'form_functions.php?actionMobi=importCity';
	var dsCity = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url:dsCityURL}),
		method: 'POST',
		reader: new Ext.data.JsonReader({
			id: 'menu_url'
			},[
				{name: 'menu_url', mapping: 'menu_url'},
				{name: 'menu_item', mapping: 'menu_item'},
				{name: 'pc', mapping: 'pc'}
			]),
		remoteSort: false
	});
	
	var dsCountryURL = mainUrl+'form_functions.php?actionMobi=importCountry';
	var dsCountry = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url:dsCountryURL}),
		method: 'POST',
		reader: new Ext.data.JsonReader({
			id: 'menu_url'
			},[
				{name: 'menu_url', mapping: 'menu_url'},
				{name: 'menu_item', mapping: 'menu_item'},
				{name: 'pc', mapping: 'pc'}
			]),
		remoteSort: false
	});

    Ext.QuickTips.init();

    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'side';
	
	var navPanel = new Ext.Panel({
		hideLabel: true,
		id: 'mobi-mt-results-nav-panel',
		html: '<div class="mobi-mt-contact-form-nav-panel-elem" onclick="history.go(-1)">'+lang_back+'</div>'
	});
	
    var fs = new Ext.FormPanel({
        frame: true,
        //title: lang_contact_form,
        labelAlign: 'left',
        labelWidth: 146,
        width: 'auto',
        waitMsgTarget: true,
        items: [
            new Ext.form.FieldSet({
                title: lang_general_info,
                autoHeight: true,
                defaultType: 'textfield',
                items: [
						 new Ext.form.ComboBox({
							id: 'mobi-contact-title',
	                        fieldLabel: lang_title,
	                        hiddenName: 'title',
	                        store: new Ext.data.SimpleStore({
	                            fields: ['abbr', 'id'],
	                            data : [
									        ['M.', '1'],
									        ['Mlle.', '2'],
									        ['Mme.', '3'],
									        ['Dr.', '4'],
									        ['Prof.', '5']
										]
	                        }),
	                        valueField:'id',
	                        displayField:'abbr',
	                        typeAhead: true,
	                        mode: 'local',
	                        triggerAction: 'all',
							emptyText: lang_choose_title,
							forceSelection: true,
	                        selectOnFocus:true,
	                        width:273
	                    }),
					{
                        fieldLabel: lang_last_name,
						id: 'mobi-contact-first-name',
						//vtype:'alpha',
						allowBlank: false,
                        name: 'first',
                        width:273
                    }, {
                        fieldLabel: lang_first_name,
						id: 'mobi-contact-last-name',
						//vtype:'alpha',
						allowBlank: false,
                        name: 'last',
                        width:273
                    }, {
                        fieldLabel: lang_address,
						id: 'mobi-contact-address',
                        name: 'address',
                        width:273
					}, 
						new Ext.form.ComboBox({
	                        store: dsCity,
							hideTrigger:true,							
							id: 'mobi-contact-city',
							fieldLabel: lang_city,	
							name: 'city',
							//hiddenName: 'mobi-search-city-combobox_hidden',						
							displayField:'menu_item',
							valueField:'menu_url',
	                        typeAhead: true,
	                        mode: 'remote',
	                        triggerAction: 'all',
	                        //emptyText:lang_choose_city,
	                        selectOnFocus:true,
	                        width:273,
							//forceSelection: true,
							listeners: {
								"select": function(combo, record, index){
									Ext.getCmp('mobi-contact-city-hidden').setRawValue(record.data.menu_url); 
									Ext.getCmp('mobi-contact-postal-code').setRawValue(record.data.pc); 
									Ext.getCmp('mobi-contact-country').setRawValue('France'); 
								},
								"focus": function(field){
									Ext.getCmp('mobi-contact-city-hidden').setRawValue(''); 
								}
							}
	                    })
					, {
                        fieldLabel: lang_postal_code,
						id: 'mobi-contact-postal-code',
                        name: 'pc',
                        width:273
					}, 
                        new Ext.form.ComboBox({
	                        store: dsCountry,
							hideTrigger:true,							
							id: 'mobi-contact-country',
							fieldLabel: lang_country,	
							name: 'country',
							//hiddenName: 'mobi-search-country-combobox_hidden',						
							displayField:'menu_item',
							valueField:'menu_url',
	                        typeAhead: true,
	                        mode: 'remote',
	                        triggerAction: 'all',
	                        //emptyText:lang_choose_country,
	                        selectOnFocus:true,
	                        width:273
	                    })
					, {
                        fieldLabel: lang_tel1,
						id: 'mobi-contact-tel1',
                        name: 'tel1',
                        width:273
					}, {
                        fieldLabel: lang_tel2,
						id: 'mobi-contact-tel2',
                        name: 'tel2',
                        width:273
                    }, {
                        fieldLabel: lang_email,
						id: 'mobi-contact-email',
						allowBlank: false,
                        name: 'email',
                        vtype:'email',
                        width:273
                    },{
						hidden: true,
						hideLabel: true,
						id: 'mobi-contact-city-hidden',
                        name: 'cid',
                        width:273
					},
					/*
						new Ext.form.HtmlEditor({
							id: 'mobi-contact-text',
							name: 'text',
							enableLists: false,
							enableSourceEdit: false,
							hideLabel: true,
							width: 423,
							height: 200
						})
					*/
						new Ext.form.TextArea({
							id: 'mobi-contact-text',
							name: 'text',
							hideLabel: true,
						    width: 423,
						    height: 200
						})
                ]
            })
        ]
    });

    var submit = fs.addButton({
        text: lang_submit,
        handler: function(){
            fs.getForm().submit({
				url: 'index.php?eID=tx_mtcontactform_ajax', 
				method: 'POST',
				params:{
					actionMobi: 'submit',
					pid: pid,
					idObject: getUrlItem('idObject'),
					interval: getUrlItem('do'),	// TODO: Dates Réservation ( 'dr' )
					opid: getUrlItem('opid'),
					other: (typeof Recaptcha === 'undefined' ? 
								'': 
								Ext.util.JSON.encode({
									challenge: Recaptcha.get_challenge(),
									response: Recaptcha.get_response()
								})
							)
				},
				waitMsg: lang_saving,
				success: function(form, action) {
					Ext.Msg.alert('Info', lang_submit_ok);
					//clear all the fields
					Ext.getCmp('mobi-contact-title').setRawValue(lang_choose_title);
					Ext.getCmp('mobi-contact-first-name').setRawValue('');
					Ext.getCmp('mobi-contact-last-name').setRawValue('');
					Ext.getCmp('mobi-contact-address').setRawValue('');
					Ext.getCmp('mobi-contact-city').setRawValue('');
					Ext.getCmp('mobi-contact-postal-code').setRawValue('');
					Ext.getCmp('mobi-contact-country').setRawValue('');
					Ext.getCmp('mobi-contact-tel1').setRawValue('');
					Ext.getCmp('mobi-contact-tel2').setRawValue('');
					Ext.getCmp('mobi-contact-email').setRawValue('');
					Ext.getCmp('mobi-contact-text').setRawValue('');
					
					(typeof Recaptcha === 'undefined' ? 
								'': 
								Recaptcha.reload()
							)
				},            
				failure: function(form, action) { 
					var obj = Ext.util.JSON.decode(action.response.responseText);
					if (obj.msg == '100'){
						Ext.Msg.alert('ERR', lang_captcha_error);
						(typeof Recaptcha === 'undefined' ? 
								'': 
								Recaptcha.reload()
							)
					}
					else{
						Ext.Msg.alert('ERR', lang_submit_error);
					}
				}
			});
        }
    });
	
    navPanel.render('mobi-contact-form');
    fs.render('mobi-contact-form');
});
