Ext.BLANK_IMAGE_URL = '/js/script/ext/resources/images/default/s.gif';

var form;
var multiMode=false;
var submitRegBtn;
var choosedLng = false;

Ext.onReady(function(){
	Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';

	var converted = new Ext.form.ComboBox({
	    typeAhead: true,
	    triggerAction: 'all',
	    transform:'languageCode',
	    width:135,
	    forceSelection:true,
		allowBlank: true,
		onSelect: function(o){ 
			choosedLng = o.id;
			this.collapse();
			if( form.isDirty() ) {
				Ext.Msg.confirm('Confirm', bundle[actLng]['selLangConfirm'],switchLanguage);
			} else {
				switchLanguage('yes');
			}
		}
	});
	converted.setValue(actLng);

	var ds = new Ext.data.Store({
	        proxy: new Ext.data.HttpProxy({
	            url: '/page/fetchSerial/pageId/13281',
				method: 'GET'
	        }),
	        reader: new Ext.data.JsonReader({
	            root: 'types',
				id: 'type'
	        }, [
	            {name: 'name'}
	        ])
	    });

	    var resultTpl = new Ext.Template(
	        '<div class="search-item">{name}</div>'
	    );

    form = new Ext.form.Form({
        labelAlign: 'right',
		url: '/page/submitProductReg/pageId/13281', 
		method:'POST',
        labelWidth: 100
    });

form.container({clear:true});
    form.fieldset(
        {legend:bundle[actLng]['CI'], style:'background-color:#f3f3f3;', labelWidth:120},
        new Ext.form.TextField({
            fieldLabel: bundle[actLng]['fullName'],
            name: 'fullName',
            allowBlank:false
        }),

        new Ext.form.TextField({
            fieldLabel: bundle[actLng]['position'],
            name: 'position',
            allowBlank:true
        }),

        new Ext.form.TextField({
            fieldLabel: bundle[actLng]['company'],
            name: 'company',
            allowBlank:false
        }),
        
        new Ext.form.TextField({
            fieldLabel: bundle[actLng]['phone'],
            name: 'phone',
            allowBlank:true
        }),
        
        new Ext.form.TextField({
            fieldLabel: bundle[actLng]['email'],
            name: 'email',
            vtype:'email',
            allowBlank:false
        }),

		new Ext.form.ComboBox({
            fieldLabel: bundle[actLng]['country'],
            hiddenName:'country',
			valueField: 'country',
            store: new Ext.data.SimpleStore({
                fields: ['country'],
                data : Weller.productReg.countries
            }),
            displayField:'country',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'query',
            emptyText:bundle[actLng]['selCountry'],
            selectOnFocus: true,
			readOnly: true,
			forceSelection: true,
            allowBlank: false
        }),

        new Ext.form.TextArea({
            fieldLabel: bundle[actLng]['address'],
            name: 'address',
            grow: true,
            maxLength: 500,
            growMax: 500,
            preventScrollbars:true,
            allowBlank:false
        })
    );
	form.end();
form.end();


form.container({clear:true});
    var snFs = form.fieldset(
        {id:'serialnumbers', legend:bundle[actLng]['serialnumbers'], hideLabels: true, style:'background-color:#f3f3f3;'},

		new Ext.form.TextField({
			hidden: true,
			id: 'typeID',
			name: 'typeID'
        }),

    new Ext.form.ComboBox({
			valueField: 'type',
			displayField:'name',
			cls: 'snTypeField',
			id: 'type',
			name: 'type',
			minChars: 2,
			queryDelay: 200,
			forceSelection: false,
      store: ds,
	    typeAhead: false,
			mode: 'remote',
	        loadingText: 'Searching...',
	        hideTrigger:true,
			grow: true,
			allowBlank: false,
	    tpl: resultTpl,
	    
			onSelect: function(record){ form.findField('typeID').setValue( record.id ); this.setValue( record.data.name ); this.collapse(); }
        }),

        new Ext.form.TextField({
            fieldLabel: bundle[actLng]['serial'],
            name: 'serial',
			id: 'serial',
            allowBlank:false
        })

    );
	form.end();
form.end();

form.column({width:380, labelWidth:110});
    var snDetails = form.fieldset(
        {id:'snDetails', legend:bundle[actLng]['serialnumberDetails'], hideLabels: false, style:'background-color:#f3f3f3;'},
        new Ext.form.DateField({
            fieldLabel: bundle[actLng]['date'],
            name: 'date',
            value: '01.07.2007',
            format: 'd.m.Y',
            allowBlank:true
        }),

		 new Ext.form.TextField({
	        fieldLabel: bundle[actLng]['distri'],
	        name: 'distributor',
			id: 'distributor',
	        allowBlank:false
	    }),

		new Ext.form.ComboBox({
	        fieldLabel: bundle[actLng]['app'],
	        hiddenName:'app',
			valueField: 'app',
	        store: new Ext.data.SimpleStore({
	            fields: ['app','name'],
	            data : Weller.productReg.applications
	        }),
	        displayField:'name',
	        typeAhead: true,
	        mode: 'local',
	        triggerAction: 'all',
	        selectOnFocus: true,
			readOnly: true,
			forceSelection: true,
	        allowBlank: true
	    })

    );
	form.end();
form.end();

form.column({width:202, style:'margin-left:10px', clear:true});
    form.fieldset({legend:bundle[actLng]['regSerials'], hideLabels:true, hidden:false, id: 'submittedSerials', style:'height:90px;background-color:#f3f3f3;'});
	form.end();
form.end();

form.column({width:380, labelWidth:110});
	form.fieldset(
		{ legend:bundle[actLng]['newsletter'], hideLabels:true, id:'newsletter', style:'height:130px;background-color:#f3f3f3;' },
			new Ext.form.Checkbox({
				boxLabel:bundle[actLng]['newsletterText'],
				name:'newsletterCheck',
				id:'newsletterCheck',
				width:'auto'
			 })
		);
	form.end();
form.end();

form.column({width:202, style:'margin-left:10px;'});
	form.fieldset({ legend:bundle[actLng]['disclaimer'], hideLabels:true, id:'disclaimer', style:'height:130px;background-color:#f3f3f3;' });
	form.end();
form.end();
 
	
    form.applyIfToFields({ width:230 });
	form.addButton( bundle[actLng]['submit'], submitForm );
    form.render('form-ct4');
    var photo = Ext.get('serialnumbers');	
    var c = photo.createChild({
        tag:'center', 
        cn: {
            tag:'img',
            src: '/plate.png',
            //src: 'http://www.weller.de/registration/img/plate.png',
            width: '100%'
        }
    });

 	var newsletterCheck = Ext.get('newsletter');	
    c = newsletterCheck.createChild({
        tag:'span', 
		cls: 'newsletterText2',
		html: bundle[actLng]['newsletterText2']
    });

	var disclaimer = Ext.get('disclaimer');	
    c = disclaimer.createChild({
        tag:'span', 
		cls: 'newsletterText2',
		html: bundle[actLng]['disclaimerText']
    });

	form.isValid()
});


function switchLanguage( btn ) {
	if( btn=='yes' && choosedLng ) {
		console.log()
		window.location = String.format(uri+'/lang/{0}', choosedLng);
	}
}


function submitFormSwitch( btn ){
	if( btn=='ok' ){
		anotherSerial();
	} else {
		Ext.Msg.alert('Success', bundle[actLng]['thanks']);
		form.reset();
		form.clearInvalid();
	}
}

function anotherSerial(){	
	var submittedSerials = Ext.get('submittedSerials');	
	var sno = form.findField('serial');	
	var pto = form.findField('type');
	var dio = form.findField('distributor');
	var snv = sno.getValue();
	var ptv = pto.getValue();

	if( !submittedSerials.isDisplayed() ){
		submittedSerials.fadeIn({endOpacity:1,easing:'easeIn',duration:.9,block:true});
	}
    var c = submittedSerials.createChild({
        cn: {
            tag: 'input',
			value: snv+' ('+ptv+')',
			name: 'displayedSn[]',
			readonly: true,
			cls: 'snfields'
        }
    });
	c.fadeIn({endOpacity:1,easing:'easeIn',duration:1,block:true});
	pto.reset();
	sno.reset();
	form.clearInvalid();
	multiMode=true;
}

function submitForm(){
	if( form.isValid() && form.isDirty ) {
		checkSerial();
	}
}

function completeFormSubmit(){
	if( form.submit() ) {}
	Ext.Msg.show({
	    modal: true,
		title: 'Question',
		msg: bundle[actLng]['regAnotherConfirm'],
		width: 300,
	    shadow: true,
		buttons: {ok:bundle[actLng]['regAnotherYES'], cancel:bundle[actLng]['regAnotherNO']},
		closable: false,
		scope: this,
		animEl: 'form-ct4',
		fn: submitFormSwitch
	});
}

function checkSerialAfter(res){
	if(res=='SUCCESS') {
		//checkProductType();
		completeFormSubmit();
	} else if(res=='FAILED') {
		Ext.Msg.alert('Error',bundle[actLng]['serialInvalid']);
	}
}
function checkProductTypeAfter(res) {
	if(res=='SUCCESS') {
		completeFormSubmit();
	} else if(res=='FAILED') {
		//Ext.Msg.alert('Error',bundle[actLng]['ptInvalid']);
	}
}

function checkSerial() {
	var sn = form.findField('serial').getValue();
	Ext.Ajax.request({
		url: '/page/serialseeker/pageId/13281',
	    params: {serial:sn},
	    method: 'GET',
	    //success: function(o){ checkSerialAfter(o.responseText); },
		success: function(o){ checkSerialAfter('SUCCESS'); },
	    failure: function(o){ Ext.Msg.alert('Error','Unexpected error occured.'); checkSerialAfter(false); },
	    isUpload: false,
	    disableCaching: false
	});
}

function checkProductType() {
	var type = form.findField('typeID').getValue();
	Ext.Ajax.request({
		url: uri+'/typeSeeker.php',
	    params: {type:type},
	    method: 'GET',
	    //success: function(o){ checkProductTypeAfter(o.responseText) },
		success: function(o){ checkProductTypeAfter('SUCCESS') },	
	    failure: function(o){ Ext.Msg.alert('Error','Unexpected error occured.'); checkProductTypeAfter(false) },
	    isUpload: false,
	    disableCaching: false
	});
}