dojo.provide("ww.app.spritspar");
var spc = {

    logged_in: false,
    current_tab: 0,
    viewmode: 'screen',
    results: [],
    _in_change_callback: 0,
    wiz_forward: function() {
        errors = dojo.query('.dijitError',spc.current_tab.domNode);
        if( errors.length == 0 || logged_in) {
            if( ungesehende_gruppen[spc.current_tab.id]
               && ungesehende_gruppen[spc.current_tab.id].length ) {

               paneToShow=dijit.byId(ungesehende_gruppen[spc.current_tab.id][0])
               paneToShow.getParent().selectChild(paneToShow);
            } else {
                mainTabContainer.forward();
            }
        } else {
            this.showDialog('inputerror');
        }
    },
    wiz_back: function() {
        if( this.viewmode=='print' ) {
            this.unprint();
            return;
        }
        errors = dojo.query('.dijitError',spc.current_tab.domNode);
        if( errors.length == 0 || logged_in) {
            mainTabContainer.back();
        } else {
            this.showDialog('inputerror');
        }
    },
    showDialog: function( which ) {
        dialog = dijit.byId('invalid_dialog');
        href = "?action=dialog&which="+which;
        if( dialog.href != href ) {
            dialog.href=href;
            dialog.refresh()
        }
        dialog.show();
    },
    onTabChange: function( newTab ) {
        errors = dojo.query('.dijitError',spc.current_tab.domNode);
        if( spc.current_tab != newTab && errors.length != 0 && !logged_in) {
            mainTabContainer.selectChild(spc.current_tab);
            this.showDialog('inputerror');
            return false;
        }
        if( dijit._masterTT )
        	dijit.hideTooltip(dijit._masterTT.aroundNode );
        spc.current_tab=newTab;
        dojo.query(".needs_resize").forEach(function(el){
            if( typeof( dijit.byId(el.id).resize ) == 'function' )
            	dijit.byId(el.id).resize();
        });

        // paneChange für aktuelle AccordionPane dieses Tabs aufrufen
        // um die enthaltenen Widgets spielen dann ihre Animation ab
        nodelist = dojo.query('.dijitAccordionPane', newTab.domNode ).filter(function(thisNode){
            return dojo.query('.dijitAccordionTitle-selected', thisNode ).length > 0;
        });
        if( nodelist[0] )
            setTimeout( dojo.hitch(dijit.byNode(nodelist[0]),this.onPaneChange), 50);

	    if( newTab.id == 'Tab4' ) {
            if( this.results.length == 0) {
                dijit.show( 'noResulttext' );
                dijit.hide( 'resultstable' );
                dijit.hide( 'Tab4HeadText' );
            } else {
            	dojo.hide( 'Tab4_buttons' );
                dijit.hide( 'noResulttext' );
                dijit.show( 'Tab4HeadText' );
                dijit.byId( 'resultstable' ).update( this.results );
                dijit.show( 'resultstable' );
                dojo.show( 'Tab4_buttons' );
            }
        }
    },
    onPaneChange: function( ) {
        _this=this;
        setTimeout(function(){
            if(    replaygruppen[spc.current_tab.id]
                && replaygruppen[spc.current_tab.id][_this.id] ) {
                dojo.forEach( replaygruppen[spc.current_tab.id][_this.id], function(item, i){
                    widget=dijit.byId(item);
                    if ( widget &&  typeof(widget.replay) == "function" ) {
                        widget.replay();
                    }
                });
            }
            var _thisgroup=ungesehende_gruppen[spc.current_tab.id];
            if( _thisgroup && dojo.indexOf(_thisgroup, _this.id) >= 0) {
                _thisgroup.splice( dojo.indexOf(_thisgroup, _this.id) ,1 );
            }
            dijit.byId(_this.id).containerNode.style.overflow="hidden";
        },250);
    },
    has_helptext: function ( el )  {
        var frageId = dojo.attr(dojo.byId(el),'helpfor') || el['helpfor'];
        if( !dijit.byId( frageId ) ) return false;
        var id = frageId.replace(/^(.*)_.*$/,'$1');
        var matches = frageId.match(/^(.*)_(.*)$/);
        if( !matches ) matches = [,,"start"];    // nicht-start und nicht-ziel Fragen werden wie Startfragen behandelt

        if( matches[2] != "start" ) return true; // Zielfragen haben immer Hilfebuttons, 
                                                 // die aber nicht klickbar sind, wenn man nicht eingeloggt ist
                                                 // siehe showHelp
        else return ( fragen[id] && fragen[id]['helptext'] )  // Startfragen können auch hilfelos sein
    },
    getHelpText: function( id, helptext ) {
        if( !fragen[id] || !fragen[id][helptext] ) {
            if(!fragen[id]) fragen[id]={};
            fragen[id][helptext]='...leer...';
        }
        if( !fragen[id].helptitle ) {
            fragen[id].helptitle=id;
        }
        return fragen[id][helptext];
    }, 
    showHelp: function ( item ) {
        var frageId = dojo.attr(dojo.byId(item),'helpfor') || item['helpfor'];
        if( !dijit.byId( frageId ) ) return;
        helptext=( dijit.byId( frageId ).attr('answerstate') || 'help' )+'text';
        var id = frageId.replace(/^(.*)_.*$/,'$1');
        var matches = frageId.match(/^(.*)_(.*)$/);
        if( matches && matches[2] == "ziel" && !logged_in ) return; // Zielfragen zeigen keine Hilfe an, wenn man nicht eingeloggt ist. 

        text=spc.getHelpText(id, helptext);
        
        helpWidget=dijit.byId('userHelp');
        helpWidget.setCaller( item );
        helpWidget.setHelpItem({
            textid: id,
            texttype: helptext,
            title:fragen[id].helptitle,
            text:fragen[id][helptext]
        });

        dojo.place(helpWidget.domNode, spc.current_tab.domNode,'last');
        setTimeout( function(){ helpWidget.show(); }, 100 );
    },
    closeHelp: function(){
        if(typeof(helpWidget) != 'undefined')
            helpWidget.hide();
    },
    uploadComplete: function( data, ioArgs, widgetRef ) {
        dojo.hide( "upload_error" );
    	if(data){
    		if(data.status && data.status == "OK"){
    			widgetRef.overlay.innerHTML = data.message;
    			dojo.show( 'restart_app' );
    		}else{
                dojo.byId("upload_error").innerHTML = data.message;
                if( data.detail ) {
                    dojo.html.set(dojo.byId("error_detail"),data.detail);
                    dojo.show( "error_detail" );
                }
                dojo.show( "upload_error" );
    			console.warn('error',data,ioArgs);
    			setTimeout(function(){widgetRef.reset();},500);
    		}
    	}else{
    		// debug assist
    		console.warn('ugh?',arguments);
    	}
    },
    onEditorChangeComplete: function( args ) {
        fragen[args.textid][args.texttype]=args.value;
    },
    onDatReceive: function( wsResult ) {
    	dijit.byId('verbrauch').attr('value',wsResult.fuelConsumption);
    	dijit.byId('verbrauch').displayMessage('Dies ist Ihr ermittelter Verbrauch. Sie können den Wert bei Bedarf korrigieren.');
    	if( wsResult.fuelType=='D' )
    		dijit.byId('kraftstoffart_1').attr('checked',true);
    	else
    		dijit.byId('kraftstoffart_0').attr('checked',true);
    },
    onDatError: function( error ) {
        this.showDialog('datError');
    },
    onDatDisabled: function( disabled ) {
    	if( disabled )
    		dijit.byId('verbrauch').displayMessage('Korrigieren Sie ggf. den vorgegebenen Wert für den Verbrauch.');
    	else
    		dijit.byId('verbrauch').displayMessage(false);
    },
    onFormChange: function( args, fullProcessing ) {
//        console.log(args);
        // change-events für dijit-controls (nach ID) aufrufen
        if( this.type != 'radio' ) {
            callback_name = this.id+'_changed';
            if( spc[callback_name] && spc._in_change_callback != callback_name && !fullProcessing) {
                spc._in_change_callback=callback_name;
                ret=dojo.hitch(spc,callback_name)(args);
                if( ret!='delayed' ) {
                    spc._in_change_callback='';
                }
                if( ret == 'stopProcessing' && !fullProcessing ) {
                    return;
                }
            }
//            else
//                console.log("define spc."+this.id+'_changed to be notified of this change.');
        } else {
            // change-events für radio-controls (nach name) aufrufen
            if( this.name && spc[this.name+'_changed'] )
                dojo.hitch(spc,this.name+'_changed')(this);
        }

        // wert des aktuellen radio-controls im zugehörigen containerWidget speichern
        // wenn es dieses containerWidget denn gibt.
        if( this.type == 'radio') {
            if(    this.checked
                && dijit.byId(this.name) )
            {
                dijit.byId(this.name).attr('value',this.attr('value'));
            }

        }
        // ausgewählten wert ins ziel-widget übertragen
        target_widget_id = this.name.replace(/^(.*)_.*$/,'$1_ziel');
        if( dijit.byId(target_widget_id) && target_widget_id != this.id ){
            dijit.byId(target_widget_id).attr('value',this.attr('value'));
        }

        if( this.type == 'checkbox') {
            funcname = this.id.replace(/^(.*)_.*$/,'$1_changed');
            if( spc[funcname] )
                dojo.hitch(spc,funcname)(this);
//            else
//                console.log(funcname+' not found in spc');
        }
        spc.berechne_sonderfaelle();
        spc.berechne_potenzial();
    },
    interpolate_answer: function( answer, idx ) {
        var idx_floor = Math.floor( idx );
        var idx_ceil = Math.ceil( idx );
        var anteil = idx - idx_floor;
        var ret = {};

        var val_floor = parseFloat(answer[ idx_floor ].p_stadt);
        var val_ceil  = parseFloat(answer[ idx_ceil ].p_stadt);
        ret.p_stadt    = val_floor    + anteil * (val_ceil-val_floor);

        val_floor  = parseFloat(answer[ idx_floor ].p_land);
        val_ceil   = parseFloat(answer[ idx_ceil ].p_land);
        ret.p_land = val_floor    + anteil * (val_ceil-val_floor);

        val_floor      = parseFloat(answer[ idx_floor ].p_autobahn);
        val_ceil       = parseFloat(answer[ idx_ceil ].p_autobahn);
        ret.p_autobahn = val_floor    + anteil * (val_ceil-val_floor);

        return ret;
    },
    berechne_sonderfaelle:function() {
        var tmp_value = Math.round(fahrstil_start.getValue());
        fahrstil_ziel.attr('answervalue',tmp_value);
        sparsonderfaelle['fahrstil'] = this.interpolate_answer( fragen['fahrstil'].antworten, fahrstil_start.getValue());

        tmp_value = topspeed_start.getValue();
        topspeed_ziel.attr('answervalue',tmp_value <= topspeed_ziel.attr('indicatorvalue') ? topspeed_ziel.attr('indicatorvalue') : tmp_value );
        tmp_value = (tmp_value - 130) / 10 ;
        sparsonderfaelle['topspeed']=fragen['topspeed'].antworten[ tmp_value ];

        sparsonderfaelle['elektro'] = elektro_start.getValue();
        elektro_ziel.attr('indicatorvalue',0)
        elektro_ziel.attr('answervalue',sparsonderfaelle['elektro'].getSum() < 0.005 ? 0:1);

        tmp_value =  Math.round(fenster_start.getValue());
        fenster_ziel.attr('answervalue',tmp_value);
        sparsonderfaelle['fenster']=fragen['fenster'].antworten[tmp_value];

        tmp_value = Math.round(ladung_start.getValue())
        ladung_ziel.attr('answervalue',tmp_value <= ladung_ziel.attr('indicatorvalue') ? ladung_ziel.attr('indicatorvalue') : tmp_value);
        sparsonderfaelle['ladung']=this.interpolate_answer( fragen['ladung'].antworten, ladung_start.getValue()/25 );

        bikes_ziel.attr('answervalue',bikes_start.getValue() > 0 ? 1:0 );
        sparsonderfaelle['bikes']={
            p_stadt:0, p_land:0,
            p_autobahn:fragen['bikes'].antworten[ 1 ].p_autobahn * bikes_start.getValue() / jahreslaufleistung.getValue()
        };
    },
    gewichtete_summe: function( p_stadt, p_land, p_autobahn ) {
        return 1- ( ( 1 - p_stadt    / 100 ) * (streckenanteil_stadt    / 100) +
                    ( 1 - p_land     / 100 ) * (streckenanteil_land     / 100) +
                    ( 1 - p_autobahn / 100 ) * (streckenanteil_autobahn / 100)    );
    },
    berechne_potenzial: function(){
        x = jahreslaufleistung.getValue();
        y = verbrauch.getValue()/100;
        var jahresverbrauch = x * y;

        var jahreskosten    = jahresverbrauch * spritpreis.getValue();
        var jahresemission  = jahresverbrauch * emission.getValue()/1000;
        if( !isNaN(jahresverbrauch) && !isNaN(jahreskosten) ) {
            values = [ dojo.number.format(jahresverbrauch, { places: 2 }),
                       dojo.number.format(jahreskosten,    { places: 2 }),
                       dojo.number.format(jahresemission,  { places: 2 })
            ];
            dojo.byId('jahresverbrauch').innerHTML = values[0];
            dojo.byId('jahreskosten').innerHTML    = values[1];
            dojo.byId('jahresemission').innerHTML  = values[2];
        }

        var html="<table>";
        p_gruppe = [];
        p_gesamt = 0;
        spc.results = [];
        dojo.forEach( inputs, function(gruppe, i ) {
            p_gruppe[i]=0;
            dojo.forEach( gruppe, function ( item, k ) {
                p_stadt=p_land=p_autobahn='n/a';
                idx = item.id.replace(/^(.*)_.*$/,'$1') ;
                antwort = false;
                if( sparsonderfaelle[ idx ] ) {
                    antwort = sparsonderfaelle[ idx ];
                }
                else if( fragen[ idx ] ) {
                    antwort = fragen[idx].antworten[item.getValue()];
                }
                if( antwort ) {
                    p_stadt    = antwort.p_stadt;
                    p_land     = antwort.p_land;
                    p_autobahn = antwort.p_autobahn;
                    tmp        = spc.gewichtete_summe( p_stadt, p_land, p_autobahn );
                    p_gruppe[i] += tmp;
                    if( !isNaN( tmp ) && tmp > 0.005 ) spc.results.push(
		        { id: idx, value: Math.round(tmp*100,2),
			  title: fragen[idx].helptitle,
			  text: fragen[idx].noktext
			}
		      );
                }
                html += ('<tr><td>'+item.id+'</td><td>'+Math.round(item.getValue())+' '+p_stadt+'|'+p_land+'|'+p_autobahn+' </td></tr>');
            });
            html += ('<tr><td colspan="2" class="sep">'+Math.round(p_gruppe[i]*100)+'%</td></tr>');
        });
        html+="</table>"
//        dojo.byId('value_debug').innerHTML=html;

        p_gesamt=1;
        dojo.forEach( p_gruppe, function( p, k ) {
            p_gesamt *= (1-p);
        });
        p_gesamt = 1 - p_gesamt;
        html = Math.round(p_gesamt*100)+"% <br/>";
        jahresverbrauch_spar  = jahresverbrauch * (1 - p_gesamt);
        jahreskosten_spar     = jahreskosten    * (1 - p_gesamt);
        jahresemission_spar   = jahresemission  * (1 - p_gesamt);

        jahresverbrauch_delta = jahresverbrauch - jahresverbrauch_spar;
        jahreskosten_delta    = jahreskosten    - jahreskosten_spar;
        jahresemission_delta  = jahresemission  - jahresemission_spar;

        var anzeigewerte = [];
        var anzeigeeinheiten = [];
        if( jahresverbrauch_delta > 9999 ) {
            anzeigewerte[0] = jahresverbrauch_delta/100;
            anzeigeeinheiten[0] = 'hl'
        } else {
            anzeigewerte[0] = jahresverbrauch_delta;
            anzeigeeinheiten[0] = 'Liter'
        }
        if( jahreskosten_delta > 9999 ) {
            anzeigewerte[1] = jahreskosten_delta/1000;
            anzeigeeinheiten[1] = 'TEUR'
        } else {
            anzeigewerte[1] = jahreskosten_delta;
            anzeigeeinheiten[1] = 'Euro'
        }
        if( jahresemission_delta > 9999 ) {
            anzeigewerte[2] = jahresemission_delta/1000;
            anzeigeeinheiten[2] = 't CO<sub>2</sub>'
        } else {
            anzeigewerte[2] = jahresemission_delta;
            anzeigeeinheiten[2] = 'kgCO<sub>2</sub>'
        }

        dijit.byId('anzeige').attr('value',anzeigewerte);
        dijit.byId('anzeige').attr('units',anzeigeeinheiten);

        mehrkilometer         = Math.round( jahresverbrauch_delta * 100 / verbrauch.getValue(),2);
        jahresverbrauch_spar  = Math.round( jahresverbrauch_spar, 2 );
        jahreskosten_spar     = Math.round( jahreskosten_spar, 2 );
        jahresemission_spar   = Math.round( jahresemission_spar, 2 );
        jahresverbrauch_delta = Math.round( jahresverbrauch_delta, 2 );
        jahreskosten_delta    = Math.round( jahreskosten_delta, 2 );
        baum = Math.round( jahresemission_delta / 10, 1);
        jahresemission_delta  = Math.round( jahresemission_delta, 2 );
        dojo.forEach(['spargrafik1','spargrafik2'],function(id){
            var el = dijit.byId(id);
            el.attr('bar1',baum);
            el.attr('bar2',mehrkilometer);
            el.attr('bar3',jahreskosten_delta);
            el.attr('emission',jahresemission_delta);
            el.attr('potenzial',p_gesamt);
            el.update();
        });

        html += jahresverbrauch_delta+' Liter weniger sprit (='+jahresverbrauch_spar+')<br/>';
        html += mehrkilometer+' Kilometer/Jahr weiter fahren<br/>';
        html += jahreskosten_delta+' € weniger kosten (='+jahreskosten_spar+')<br/>';
        html += jahresemission_delta+' t weniger CO<sub>2</sub> ^ '+baum+' Bäume (='+jahresemission_spar+')<br/>';
        dojo.byId('value_potenzial').innerHTML=html;
    },
    streckenanteile_changed: function( args ) {
        stadt    = args[0];
        land     = ( args[1]-args[0] );
        autobahn = (100-args[1]);
        move=[];
        move[0] = {x:(stadt<6?6:stadt)/2,                                 y:stadt    <  6 ? 21:0};
        move[1] = {x:parseFloat((land<10?8:land)-1)/2+parseFloat(stadt), y:land     < 10 ? 21:0};
        move[2] = {x:100-((autobahn<5?5:autobahn)/2),                     y:autobahn <  6 ? 21:0};

        if( move[1].x < 15 ) {
            dojo.addClass(dojo.byId("str_0_top"),'str_display_hop_down');
            dojo.addClass(dojo.byId("str_1_top"),'str_display_hop_up');
            if( move[1].x < 7 ) move[1].x = 7;
            
        }
        if( move[1].x > 80 ) {
            dojo.addClass(dojo.byId("str_2_top"),'str_display_hop_down');
            dojo.addClass(dojo.byId("str_1_top"),'str_display_hop_up');
            if( move[1].x > 93 ) move[1].x = 93;
            
       }
        if( move[1].x > 13 && move[1].x < 83) {
            dojo.removeClass(dojo.byId("str_0_top"),'str_display_hop_down');
            dojo.removeClass(dojo.byId("str_1_top"),'str_display_hop_up');
            dojo.removeClass(dojo.byId("str_2_top"),'str_display_hop_down');
        }

        dojo.forEach( move, function(item,i) {
            move[i].x += '%';
            move[i].y = -19+move[i].y+'px';
        });
        dojo.style("str_0_bottom", "left",move[0].x);
        dojo.style("str_1_bottom", "left",move[1].x);
        dojo.style("str_2_bottom", "left",move[2].x);
        dojo.style("str_0_bottom", "top",move[0].y);
        dojo.style("str_1_bottom", "top",move[1].y);
        dojo.style("str_2_bottom", "top",move[2].y);
        dojo.style("str_0_top", "left",move[0].x);
        dojo.style("str_1_top", "left",move[1].x);
        dojo.style("str_2_top", "left",move[2].x);


        stadt    = Math.round(stadt,2);
        land     = Math.round(land,2);
        autobahn = Math.round(autobahn,2);
        dojo.byId("str_0_bottom").innerHTML = '<span class="dijitRuleLabelH">'+stadt+'%</span>';
        dojo.byId("str_1_bottom").innerHTML = '<span class="dijitRuleLabelH">'+land+'%</span>';
        dojo.byId("str_2_bottom").innerHTML = '<span class="dijitRuleLabelH">'+autobahn+'%</span>';
        dojo.byId("streckenanteil_stadt").value         = stadt;
        dojo.byId("streckenanteil_land").value          = land;
        dojo.byId("streckenanteil_autobahn").value      = autobahn;

        var _args = args;
        clearTimeout( spc.streckenanteile_changed_timer );
        spc.streckenanteile_changed_timer = setTimeout(function(){
            dojo.hitch(streckenanteile, spc.onFormChange)( _args, true );
        },100);
        return "stopProcessing";
    },
    emptyInput: function() {
        if( this.attr('displayedValue') == '---') this.attr('displayedValue', '');
    },
    pkw_hersteller_changed: function(){
        pkw_modell.setValue(null);
        pkw_modell.attr('displayedValue', '---');
        pkw_modell._isvalid=true;
        if (!this.item ) {
            pkw_modell.attr('disabled', true);
            pkw_typ.attr('disabled', true);
        } else {
            pkw_modell.attr('disabled', false);
            pkw_typ.attr('disabled', false);
            filterexpr = {
                ref: "" + this.item.id
            };
            pkw_modell.query = filterexpr;
            pkw_modell.store.fetch();
        }
    },
    pkw_modell_changed: function (){
        pkw_typ.setValue(null);
        pkw_typ.attr('displayedValue', '---');
        pkw_typ._isvalid=true;
        if( !this.item )
            pkw_typ.attr('disabled', true);
        else {
            pkw_typ.attr('disabled', false);
            filterexpr = { ref: ""+ this.item.id };
            pkw_typ.query=filterexpr;
            pkw_typ.store.fetch();
        }
    },
    kraftstoffart_changed: function( thing ) {
        if( thing.attr && thing.attr('checked') )
            emission.setValue(emissionswerte[thing.getValue()]);
    },
    jahreslaufleistung_changed: function ( newMax ) {
        if(newMax > 5000) newMax = 5000;
        dojo.forEach([ 'bikes_start', 'bikes_ziel' ], function(id) {
            dijit.byId( id ).attr( 'maximum', newMax );
    		newValue = dijit.byId( id ).getValue();
    		if( newValue > newMax ) newValue = newMax;
            dijit.byId( id ).setValue( newValue );
            dojo.query( '.dijitRuleLabelContainer:last-child > span', dojo.byId( id ) ).shift().innerHTML=dojo.number.format(newMax, { places: 0 })+' km';
        });
    },
    topspeed_start_changed: function( value ) {
        var newvalue = Math.round(value/10,2)*10
        setTimeout(function(){
            topspeed_start.attr('value',newvalue);
            spc._in_change_callback='';
        },10);
        return 'delayed';
    },
    fenster_start_changed: function( value ) {
        var newvalue = Math.round(value);
        setTimeout(function(){
            fenster_start.attr('value',newvalue);
            spc._in_change_callback='';
        },10);
        return 'delayed';
    },
    elektro_start_changed: function( widget ){
        if( widget.type == 'checkbox' ) {
            var newvalue = [];
            for( var i = 0; i<=4; i++ ) {
                var w = dijit.byId('elektro_start_'+i);
                if( w.checked ) newvalue.push( fragen['elektro'].antworten[ w.value ] )
            }
            elektro_value = elektro_start.attr('value');
            elektro_value.p_stadt = 0;
            elektro_value.p_land = 0;
            elektro_value.p_autobahn = 0;

            dojo.forEach(newvalue, function( item ) {
                elektro_value.p_stadt += parseFloat(item.p_stadt);
                elektro_value.p_land += parseFloat(item.p_land);
                elektro_value.p_autobahn += parseFloat(item.p_autobahn);
            });
            elektro_start.attr('value',elektro_value);

            targetname = widget.id.replace(/start/,'ziel' );
            if( dijit.byId( targetname ) )
                dijit.byId( targetname ).attr('checked',widget.attr('checked'));
        }
    },
    bikes_start_changed: function( args ) {
        value = dojo.number.format(Math.round(bikes_start.getValue()),{ places: 0 })+' km';
        dojo.html.set(dojo.byId('bikes_start_value'), value );
        dojo.html.set(dojo.byId('bikes_ziel_value'), value );

        var _args = args;
        clearTimeout( spc.bikes_changed_timer );
        spc.bikes_changed_timer = setTimeout(function(){
            dojo.hitch(bikes_start, spc.onFormChange)( _args, true );
        },250);
        return "stopProcessing";
    },
    fahrstil_start_changed: function( args ) {
        var _args = args;
        clearTimeout( spc.fahrstil_changed_timer );
        spc.fahrstil_changed_timer = setTimeout(function(){
            dojo.hitch(fahrstil_start, spc.onFormChange)( _args, true );
        },250);
        return "stopProcessing";
    },
    ladung_start_changed: function( args ) {
        var _args = args;
        clearTimeout( spc.ladung_changed_timer );
        spc.ladung_changed_timer = setTimeout(function(){
            dojo.hitch(ladung_start, spc.onFormChange)( _args, true );
        },250);
        return "stopProcessing";
    },
    print: function() {
        dojo.byId('mainTabContainer').style.display='none';
        if(dojo.byId('bild_oben')) dojo.byId('bild_oben').style.display='none';
        pcont = dojo.byId('printContainer');
        pcont.style.display='block';
        this.anzeige_bg = dojo.byId('anzeige_bg').src;
        dojo.byId('anzeige_bg').src=dojo.byId('anzeige_bg').src.replace(/\.png/,'_print.png');

        if(this.results.length) {
            dojo.place(dojo.byId('topRow'),dojo.byId('printContainer'),'first');
            dojo.place(dojo.byId('leftCol'),dojo.byId('printContainer'),'first');

            dojo.place(dijit.byId('spargrafik2').domNode,dojo.byId('printmode_buttons'),'before');
            dojo.place(dijit.byId('resultstable').domNode,dojo.byId('printmode_buttons'),'before');
        } else {
            dojo.place(dijit.byId('noResulttext').domNode,dojo.byId('printmode_buttons'),'before');
        }
//         var tableHeight= dojo.style('ResultsTable_measure','height');
        this.viewmode='print';
        dojo.addClass(dojo.body(),'print');
        setTimeout(function(){window.print();},500);
    },
    unprint: function() {
        dojo.removeClass(dojo.body(),'print');
        dojo.byId('mainTabContainer').style.display='block';
        if(dojo.byId('bild_oben')) dojo.byId('bild_oben').style.display='block';

        dojo.byId('anzeige_bg').src=this.anzeige_bg;
        pcont = dojo.byId('printContainer');
        if(this.results.length) {
            dojo.place(dojo.byId('topRow'),dojo.byId('mainApp'),'first');
            dojo.place(dojo.byId('leftCol'),dojo.byId('mainApp'),'first');
            dojo.place(dijit.byId('spargrafik2').domNode,dojo.byId('Tab4HeadText'),'before');
            dojo.place(dijit.byId('resultstable').domNode,dojo.byId('Tab4_buttons'),'before');
        } else {
            dojo.place(dijit.byId('noResulttext').domNode,dojo.byId('Tab4HeadText'),'after');
        }
        pcont.style.display='none';
        this.viewmode='screen';
        setTimeout(function(){ dijit.byId('mainTabContainer').resize(); }, 100);
    }
}
dojo.hide = function( id ) {
    dojo.addClass( dojo.byId(id),'hidden' );
}
dojo.show = function( id ) {
    dojo.removeClass( dojo.byId(id),'hidden' );
}
dijit.hide = function( id ) {
    dojo.addClass( dijit.byId(id).domNode,'hidden');
}
dijit.show = function( id ) {
    dojo.removeClass( dijit.byId(id).domNode,'hidden');
}

dojo.string.simple_subst = function( /*String*/      template,
                                    /*Object|Array*/ map ){

    return template.replace(/\$\{([^\s\}]+)\}/g, function(match, key){
        var value = dojo.getObject(key, false, map);
        return value;
    }); // string
};

var inputs = [];
// Diese Accordionpanes müssen mindestens ein mal aufgeklappt werden, wenn 'weiter geklickt wird
var ungesehende_gruppen = {
    Tab2:['fragengruppe_2_start','fragengruppe_3_start','fragengruppe_4_start'],
    Tab3:['fragengruppe_2_ziel','fragengruppe_3_ziel','fragengruppe_4_ziel']
};

// für diese Widgets wird die 'replay' funktion aufgerufen, wenn deren contentPane sichtbar wird
// diese Widgets werden disabled
var replaygruppen = {
    Tab3:{  fragengruppe_1_ziel:['fahrstil_ziel','topspeed_ziel', 'gear_ziel','motorstop_ziel'],
            fragengruppe_2_ziel:['wartung_ziel', 'llreifen_ziel', 'reifendruck_ziel', 'motoroel_ziel'],
            fragengruppe_3_ziel:['fenster_ziel', 'klima_ziel', 'elektro_ziel' ],
            fragengruppe_4_ziel:['ladung_ziel','dach_ziel', 'bikes_ziel']
         }
};

var sparsonderfaelle = [];
var emissionswerte = [2370, 2650]
var topspeed_table = [];

dojo.addOnLoad(function(){
    document.getElementById('loaderText').innerHTML = "Programm startet...";
    document.getElementById('loaderDetail').innerHTML="bitte warten...";
    dojo.parser.parse(dojo.byId('mainApp'));
    input_names = [  [ 'kraftstoffart', 'streckenanteile', 'notlisted',
                       'streckenanteil_stadt', 'streckenanteil_land','streckenanteil_autobahn',
                       'emission', 'spritpreis','jahreslaufleistung', 'verbrauch' ],

                     [ 'fahrstil_start', 'gear_start', 'topspeed_start', 'motorstop_start' ],

                     [ 'wartung_start', 'llreifen_start', 'reifendruck_start', 'motoroel_start' ],
                     [ 'klima_start', 'elektro_start',   'elektro_start_0', 'elektro_start_1', 'elektro_start_2',
                                      'elektro_start_3', 'elektro_start_4', 'fenster_start' ],
                     [ 'ladung_start', 'dach_start', 'bikes_start' ]
    ];

    inputs = [];
    dojo.forEach(input_names, function( input_name_group,i ) {
        input_group = []
        dojo.forEach( input_name_group, function( input_name ){
            el = dijit.byId( input_name );
            if( el && el.domNode ) {
                eval('var '+input_name+' = el');
                input_group.push( el );
            }
        });
        inputs.push( input_group );
    });

    inputgroups = ['kraftstoffart','gear_start','llreifen_start','motorstop_start','reifendruck_start','motoroel_start',
                    'wartung_start','klima_start','dach_start'
                    ];

/*
    dojo.connect(pkw_hersteller, "onChange", spc.pkw_hersteller_changed);
    dojo.connect(pkw_modell,     "onChange", spc.pkw_modell_changed);
    dojo.connect(pkw_hersteller, "onFocus",  spc.emptyInput);
    dojo.connect(pkw_modell,     "onFocus",  spc.emptyInput);
    dojo.connect(pkw_typ,        "onFocus",  spc.emptyInput);
*/
    dojo.query(".needs_text").forEach(function(el){
        dijit.byId(el.id).setHelpItem({
            textid: el.id,
            texttype: 'helptext',
            title:fragen[el.id].helptitle,
            text:fragen[el.id].helptext
        });
    });



    dojo.connectPublisher("/ajax/start", dojo, "xhrPost");

    dojo.query('[id^=fragengruppe]').forEach(function(item){
        dojo.connect(dijit.byId(item.id), 'onSelected', spc.onPaneChange);
    });
    dojo.subscribe("mainTabContainer-selectChild", spc, "onTabChange");
    dojo.subscribe("/dat/FuelConsumption/complete", spc, "onDatReceive");
    dojo.subscribe("/dat/FuelConsumption/error", spc, "onDatError");
    dojo.subscribe("/dat/FuelConsumption/disablestate", spc, "onDatDisabled");
    
    spc.current_tab=dijit.byId('Tab1');
    spc.logged_in = logged_in;
    if( spc.logged_in) {
        dojo.subscribe("/ww/HelpPane/edit/complete", spc ,"onEditorChangeComplete");
    }
    // explizit angegebene Hilfe-Buttons verdrahten
    setTimeout( function(){
        dojo.query('[helpfor].help_info')
        .filter(function(el){
            if( spc.has_helptext( el ) || logged_in ) return true;
            else { dojo.hide( el ); return false; } })
        .onclick(function( el ){
            spc.showHelp(this);
             })
        ;
    },1000 );

    // inputs mit spc.onFormChange verdrahten
    dojo.forEach( inputs, function( gruppe ) {
        dojo.forEach( gruppe, function ( item ) {
            dojo.connect(item,       "onChange", item, spc.onFormChange);
        });
    });

    // inputgruppen (Radiobuttons) mit spc.onFormChange verdrahten
    dojo.forEach( inputgroups, function( item ){
        dojo.query("[name="+item+"]").forEach(function(control){
            dojo.connect(dijit.byId(control.id), "onChange", dijit.byId(control.id), spc.onFormChange);
        });
    });
    
    // Replay-Widgets konfigurieren
    for( var tab in replaygruppen) {
        for( replaygruppe in replaygruppen[tab] ) {
            dojo.forEach( replaygruppen[tab][replaygruppe], function(item, i){
                widget=dijit.byId(item);
                if ( widget &&  typeof(widget.replay) == "function" ) {
                    widget.attr('disabled',true);
                    widget.attr('showindicators',true);
                    widget.init(); // setzt den Anzeigewert (also welche Antwort als 'korrekt' angezeigt wird)
                }
            });
        }
    }
    dojo.forEach(sliderTooltips, function(t) {
        new dijit.Tooltip(t,t.srcNode);
    });


    dojo.byId('loader').style.display = "none";
    if( typeof(loaderInterval) != "undefined" ) window.clearTimeout( loaderInterval );
    spc.startupHelper = setInterval(function() {
        if( dijit.byId('streckenanteile') ) {
            clearInterval( spc.startupHelper );
            elektro_start.attr('value', { p_stadt:0,p_land:0,p_autobahn:0,getSum:function(){ return spc.gewichtete_summe( this.p_stadt, this.p_land, this.p_autobahn ); }} );
            spc.bikes_start_changed();
            dijit.byId('streckenanteile').setValue(40,70);
            if( theme !== false && theme.kraftstoffpreis != undefined ) {
                spritpreis.setValue(theme.kraftstoffpreis);
            }
            if( theme !== false ) {
                var logo = dojo.query('#img_iuma_logo')[0];
		if( logo ) {
                  dojo.style(logo,'display','block');
                  var a = dojo.byId('logo_a');
                  var logowidth = dojo.coords(logo).w;
                  var logoheight = dojo.coords(logo).h;
                  if( a ) {
                      dojo.style(a,'width',logowidth+'px');
                      dojo.style(a,'height',logoheight+'px');
                  } else {
                      dojo.style(logo,'left',270/2 - Math.floor(logowidth/2)+'px');
                      dojo.style(logo,'top', 140/2 - Math.floor(logoheight/2)+'px');
                  }
		}
            }
            dijit.byId('anzeige').attr('format',{pattern:'0000.00'});
            dijit.byId('anzeige').attr('units',['Liter','Euro','kgCO<sub>2</sub>']);
        }
    }, 100);
});

