/**
 * ToolTip
 * Tooltip class based on Element
 */
var ToolTip = Class.create({

    /**
    * init item
    */
    initialize: function(target, label) {

        if (!target.id) {
            //var myDate = new Date();
            //target.id = 'id' + Math.round(Math.abs(Math.sin(myDate.getTime()))*1000000000)%10000000;
            target.id = 'id' + (Math.random() + 1);
        }

        var objBody = document.getElementsByTagName('body')[0];

        this.toolTip = new Element("div");
        this.toolTip.id = 'tooltip' + target.id;
        this.toolTip.innerHTML = label;
        this.toolTip.hide();
        this.toolTip.style.position = 'absolute';
        this.toolTip.style.zIndex = '302';

        this.offX = 15;
        this.offY = 15;

        objBody.appendChild(this.toolTip);

        Event.observe(target, "mouseover", this.start.bind(this));
        Event.observe(target, "mouseout", this.stop.bind(this));

    },

    /**
     * show tooltip
     */
    start: function(event){
        this.render(event);
        new Effect.Appear(this.toolTip.id, { duration: 0.4, from: 0.0, to: 1.0 });

        var obj = this;
        document.observe('mousemove', this.render.bind(this));
    },

    /**
     * hide tooltip
     */
    stop: function(event){
        new Effect.Fade(this.toolTip.id, { duration: 0.4});
        document.stopObserving('mousemove', this.render.bind(this));
    },

    /**
     * render tooltip
     */
    render: function(evt){
        var obj = this.toolTip.style;
        obj.left = (parseInt(this.mouseX(evt))+ this.offX) + 'px';
        obj.top = (parseInt(this.mouseY(evt))+ this.offY) + 'px';
    },

    /**
     * mouse follow xpoisition
     */
    mouseX: function(evt) {
        if (!evt) {
            evt = window.event;
        }
        if (evt.pageX) {
            return evt.pageX;
        } else if (evt.clientX) {
            return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft);
        } else {
            return 0;
        }
    },

    /**
     * mouse follow ypoisition
     */
    mouseY: function(evt) {
        if (!evt) {
            evt = window.event;
        }
        if (evt.pageY) {
            return evt.pageY;
        } else if (evt.clientY) {
            return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
        } else {
            return 0;
        }
    },

    addClassName: function(className) {
        this.toolTip.addClassName(className);
    }

});

DivDialog = Class.create({

    initialize: function(baseUrl) {
        var displayState = false;
        this.baseUrl = baseUrl;

        this.close = function() {
            this.hideDialogs();
            displayState = false;
        }

        this.showDialog = function(dialog) {
            this.hideDialogs();
            this.closeErrorMessages();
            if (! displayState) {
                displayState = true;
            }
            dialog.show();
        }

        this.hideDialogs = function() {
            //var dialogs = document.getElementsByClassName('divPopupDialog');
            var dialogs = $$('div.divPopupDialog');
            for (var i = 0; i < dialogs.length; i++) {
                $(dialogs[i]).hide();
            }
        }

        this.showErrorMessages = function(errorMessages) {
            this.closeErrorMessages();
            var errorMsgDiv = $('calculatorErrorMessage');
            for (var i = 0; i < errorMessages.length; i++) {
                var errorMsg = new Element('p');
                errorMsg.style.display = 'block';
                errorMsg.appendChild(document.createTextNode(errorMessages[i]));
                errorMsgDiv.appendChild(errorMsg);
            }
            errorMsgDiv.style.display = 'block';
        }

        this.closeErrorMessages = function() {
            var errorMsgDiv = $('calculatorErrorMessage');
            errorMsgDiv.update();
            errorMsgDiv.hide();
        }

        //Event.observe($('calculatorBubbleTR'), 'click', this.close.bind(this));
    }
});

ModernisationLayouter = Class.create({

    initialize: function() {
        this.body = $("modernisationResultsContainer");
    },

    wait: function() {
        Element.update(this.body, null);
        this.body.style.textAlign = 'center';
        var loadingImg = new Element("img");
        loadingImg.src = 'images/loading.gif';
        loadingImg.addClassName('loadingImg');
        loadingImg.style.margin = '80px auto';
        Element.insert(this.body, loadingImg);
        Element.show(this.body);
    },

    hide: function() {
        Element.hide(this.body);
    },

    toggleTabs: function(activeTab) {
        if (activeTab == 'modernisationResultsInsulatedButton') {
            $('modernisationResultsInsulatedButton').style.height = '41px';
            $('modernisationResultsUninsulatedButton').style.height = '40px';
        } else {
            $('modernisationResultsInsulatedButton').style.height = '40px';
            $('modernisationResultsUninsulatedButton').style.height = '41px';
        }
    },

    renderErrors: function(errors) {
        Element.update(this.body, null);
        if (Object.isArray(errors)){
            for (var error in errors) {
                if (Object.isString(errors[error])){
                    Element.insert(this.body, new Element("p").addClassName("error").update(errors[error]));
                }
            }
        }
        if (Object.isString(errors)){
            Element.insert(this.body, new Element("p").addClassName("error").update(errors));
        }

    },

    renderResult: function(result) {
        Element.update(this.body, null);
        var resultList = result.body;
        if (resultList.size() > 0) {

            try {
                // get isolation
                var isolation = resultList[0].isolation == 'gedaemmt' ? 'gedaemmt' : 'ungedaemmt';

                //insert header
                var header = new Element('div');
                if (isolation == 'gedaemmt') {
                    header.id = 'modernisationInsulatedHeader';
                } else {
                    header.id = 'modernisationUninsulatedHeader';
                }
                Element.insert(this.body, header);

                // insert result div container
                var resultTableContainer = new Element('div');
                var resultTableContainerCss = isolation == 'gedaemmt' ? 'resultTableContainerInsulated' : 'resultTableContainerUninsulated';
                Element.addClassName(resultTableContainer, resultTableContainerCss);
                Element.insert(this.body, resultTableContainer);

                // insert resulttable
                var resultTable = new Element("table").addClassName('modernisationResultTable');
                resultTable.setAttribute('cellspacing', '1px');
                if (isolation == 'gedaemmt') {
                    resultTable.addClassName('modernisationResultTableGedaemmt');
                } else {
                    resultTable.addClassName('modernisationResultTableUngedaemmt');
                }

                Element.insert(resultTableContainer, resultTable);

                // add initial state
                var formValues = $('modernisationForm').serialize(true);
                var stateRow = resultTable.insertRow(-1);
                var stateCell = stateRow.insertCell(-1);
                var stateString = 'Ausgangssituation: ';
                stateString += formValues['modernisationState'] == 'alt1' ? 'Öl-Heizung' : 'Gas-Heizung';
                stateString += ', ';
                switch (formValues['modernisationType']) {
                    case 'rh':
                        stateString += 'Reihenhaus';
                        break;
                    case '6fh':
                        stateString += 'Mehrfamilienhaus';
                        break;
                    default:
                        stateString += 'Einfamilienhaus';
                }
                stateString += ', Wärmeschutzverordnung ' + formValues['modernisationWsv'];
                stateCell.innerHTML = stateString;
                stateCell.colSpan = "5";
                stateCell.style.textAlign = 'left';
                stateCell.style.padding = '10px';
                Element.addClassName(stateCell, 'default');

                // add table header
                var toolTip;
                var tooltipClassName = isolation == 'gedaemmt' ? 'modernisationTooltipInsulated' : 'modernisationTooltipUninsulated';
                var resultRow = resultTable.insertRow(-1);
                var resultCell;

                resultCell = resultRow.insertCell(-1);
                resultCell.innerHTML = 'Modernisierungsoptionen';
                resultCell.style.textAlign = 'left';
                Element.addClassName(resultCell, 'header');

                resultCell = resultRow.insertCell(-1);
                resultCell.innerHTML = 'Investitionskosten';
                Element.addClassName(resultCell, 'header');
                toolTip = new ToolTip(resultCell, this.getTooltipText('investitionskosten'));
                toolTip.addClassName(tooltipClassName);

                resultCell = resultRow.insertCell(-1);
                resultCell.innerHTML = 'Minderungsinvestition CO<sub>2</sub>-Ausstoß';
                Element.addClassName(resultCell, 'header');
                toolTip = new ToolTip(resultCell, this.getTooltipText('emission_minderungsinvestition_jahr'));
                toolTip.addClassName(tooltipClassName);

                resultCell = resultRow.insertCell(-1);
                resultCell.innerHTML = 'relative CO<sub>2</sub>-Einsparung';
                Element.addClassName(resultCell, 'header');
                toolTip.addClassName(tooltipClassName);

                resultCell = resultRow.insertCell(-1);
                resultCell.innerHTML = 'Amortisationszeit (in Jahren)';
                Element.addClassName(resultCell, 'header');
                toolTip = new ToolTip(resultCell, this.getTooltipText('energiekosten_einsparungsinvestition'));
                toolTip.addClassName(tooltipClassName);

                // add result rows
                for (var i = 0; i < resultList.size(); i++) {
                    var row = resultList[i];
                    // zeile ohne modernisierungsmaßnahme (alter kessel bleibt) bei ungedämmt ausblenden
                    if (!(isolation == 'ungedaemmt' && (row.anlagensanierung == 'oel_standard' || row.anlagensanierung == 'gas_standard'))) {
                        resultRow = resultTable.insertRow(-1);

                        // style (bgcolor) setzen, um sanierungsoptionen thematisch zu gruppieren
                        var styleClass = 'default';
                        switch (row.anlagensanierung) {
                            case 'gas_brennwert':
                                styleClass = 'subjectArea gas';
                                break;
                            case 'gas_brennwert_solar_warmwasser':
                            case 'gas_brennwert_solar_heizung':
                                styleClass = 'gas';
                                break;

                            case 'gas_standard':
                            case 'oel_standard':
                                styleClass = 'subjectArea insulated';
                                break;

                            case 'oel_brennwert':
                                styleClass = 'subjectArea oil';
                                break;
                            case 'oel_brennwert_solar_heizung':
                            case 'oel_brennwert_solar_warmwasser':
                                styleClass = 'oil';
                                break;

                            case 'pellets':
                                styleClass = 'subjectArea other';
                                break;
                            case 'elektrowaermepumpe':
                                styleClass = 'other';
                                break;

                        }

                        // add row headline (first cell in row)
                        resultCell = resultRow.insertCell(-1);
                        resultCell.innerHTML = this.getHeaterName(row.anlagensanierung);
                        Element.addClassName(resultCell, styleClass + 'RowHeader');
                        
                        // add result cells
                        resultCell = resultRow.insertCell(-1);
                        Element.addClassName(resultCell, styleClass);
                        resultCell.innerHTML = this.formatNumber(Math.round(parseFloat(row.investitionskosten))) + ' &euro;';
                        resultCell = resultRow.insertCell(-1);
                        Element.addClassName(resultCell, styleClass);
                        resultCell.innerHTML = this.formatNumber(parseFloat(row.emission_minderungsinvestition_jahr).toFixed(2)) + ' &euro;';
                        resultCell = resultRow.insertCell(-1);
                        Element.addClassName(resultCell, styleClass);
                        resultCell.innerHTML = this.formatNumber(Math.round(100 * parseFloat(row.emission_einsparung_relativ))) + ' %';
                        resultCell = resultRow.insertCell(-1);
                        Element.addClassName(resultCell, styleClass);
                        resultCell.innerHTML = this.formatNumber(parseFloat(row.energiekosten_einsparungsinvestition).toFixed(1));
                    }
                }

            } catch(e) {
                alert("Bei der Anzeige der Ergebnisse ist ein Javascriptfehler aufgetreten!\n\n" + e.message);
            }
        } else {
            alert('Wegen Verbindungsproblemen zur Datenbank konnten die Ergebnisse leider nicht geladen werden!');
        }
    },

    getTooltipText: function(key) {
        switch (key) {
            case 'investitionskosten':
                return 'Wie viel muss ich investieren?';
            case 'emission_minderungsinvestition_jahr':
                return 'CO<sub>2</sub>-Minderungsinvestition ist die Investitionssumme die notwendig ist, um 1 kg Kohlendioxyd pro Jahr einzusparen.';
            case 'energiekosten_einsparungsinvestition':
                return 'Wann zahlt sich meine Investition aus?';
        }
        return null;
    },

    getHeaterName: function(key) {
        switch (key) {
            case "oel_standard":
                //return 'Öl-Standardkessel';
                return 'Dämmung';
            case "gas_brennwert":
                return 'Erdgas-Brennwert';
            case "gas_brennwert_solar_warmwasser":
                return 'Erdgas-Brennwert + Solarthermie';
            case "gas_brennwert_solar_heizung":
                return 'Erdgas-Brennwert + Solarthermie + Heizungsunterstützung'
            case "oel_brennwert":
                return 'Öl-Brennwert';
            case "oel_brennwert_solar_warmwasser":
                return 'Öl-Brennwert + Solarthermie';
            case "oel_brennwert_solar_heizung":
                return 'Öl-Brennwert + Solarthermie + Heizungsunterstützung'
            case "pellets":
                return 'Holzpelletanlage';
            case "elektrowaermepumpe":
                return 'Luft-Wasser-Elektrowärmepumpe';
            case "gas_standard":
                //return 'Erdgas-Standardkessel';
                return 'Dämmung';
        }
        return null;
    },

    formatNumber: function(number) {
        var nStr = number;
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? ',' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + '.' + '$2');
        }
        return x1 + x2;
    }

});

AjaxModernisationControl = Class.create({

    initialize: function(url, resultLayouter) {
        this.url = url;
        this.resultLayouter = resultLayouter;
    },

    load: function(parameter) {
        CommonUtils.cursorWait();
        this.resultLayouter.wait();
        var mySelf = this;
        var opt = {
            method: 'get',
            parameters: parameter,
            onSuccess: function(t) {
                mySelf.response(t.responseJSON, t.responseText);
            }
        };

        new Ajax.Request(this.url, opt);
    },

    hide: function() {
        CommonUtils.cursorDefault();
        this.resultLayouter.hide();
    },

    response: function(jsonResult, text) {
        CommonUtils.cursorDefault();
        if (jsonResult == null) {
            this.resultLayouter.renderErrors(text);
            return;
        }
        if (! jsonResult.success){
            this.resultLayouter.renderErrors(jsonResult.errors);
        }
        if (jsonResult.success){
            this.resultLayouter.renderResult(jsonResult.result);
        }
    }
});

ModernisationCalculator = Class.create(DivDialog,{

    initialize: function($super, baseUrl) {
        $super(baseUrl);
        this.modernisationControl = new AjaxModernisationControl('home.AjaxModernisation.html', new ModernisationLayouter());
        Event.observe($('modernisationFormDialogNextButton'), 'click', this.showModernisationResults.bind(this));
        Event.observe($('modernisationResultsInsulatedButton'), 'click', this.loadResults.bind(this));
        Event.observe($('modernisationResultsUninsulatedButton'), 'click', this.loadResults.bind(this));
        Event.observe($('modernisationResultsDialogRestartButton'), 'click', this.start.bind(this));

        this.evaluateForm = function() {
            var errors = new Array();
            var modernisationState = $('modernisationForm').getInputs('radio', 'modernisationState').find(function(r){return r.checked}).value;
            if (modernisationState != 'alt1' && modernisationState != 'alt2') {
                errors[errors.length] = 'Die Heizungsart ist nicht zulässig.';
            }
            if ($F('modernisationType') != 'efh' && $F('modernisationType') != 'rh' && $F('modernisationType') != '6fh') {
                errors[errors.length] = 'Der Typ der Immobilie ist nicht zulässig.';
            }
            var now = new Date()
            if (! $('modernisationWsv1978').checked && ! $('modernisationWsv1984').checked) {
                errors[errors.length] = 'Bitte wählen Sie das Wärmeschutzniveau Ihres Hauses.';
            }
            return errors;
        }

        this.isFormValid = function() {
            if (this.evaluateForm().length > 0) {
                return false;
            }
            return true;
        }
    },

    getTooltipText: function(key) {
        switch (key) {
            case 'helpWsv':
                return 'Das Einsparpotenzial von Sanierungsmaßnahmen ist wesentlich vom Zustand der Gebäude vor der  Sanierung  abhängig.  Für  die  nachfolgenden  Berechnungen  werden  zwei  verschiedene Ausgangszustände betrachtet:<ul><li>Wärmeschutz etwa entsprechend Wärmeschutzverordnung 1978 (WSV 1978)</li><li>Wärmeschutz etwa entsprechend Wärmeschutzverordnung 1984 (WSV 1984)</li></ul>Wurde Ihr Haus nach 1978 bzw. 1984 erbaut oder saniert, entspricht es in der Regel der Wärmeschutzverordnung von 1978 bzw. 1984.';
        }
        return null;
    },

    start: function() {
        var dialog = $('modernisationFormDialog');
        this.showDialog(dialog);
    },

    showModernisationForm: function() {
        var dialog = $('modernisationFormDialog');
        toolTip = new ToolTip($('helpWsvLink'), this.getTooltipText('helpWsv'));
        toolTip.addClassName('modernisationTooltip');
        this.showDialog(dialog);
        return false;
    },

    showModernisationResults: function() {
        var dialog = $('modernisationResults');
        try {
            if (this.isFormValid()) {
                this.showDialog(dialog);
                this.loadResults(Event.fire($('modernisationResultsUninsulatedButton'), 'click'));
            } else {
                var errors = this.evaluateForm();
                var errorOutput = 'Leider sind Ihre Angaben nicht vollständig oder enthalten Fehler.' + "\n\n";
                for (var i = 0; i < errors.length; i++) {
                    errorOutput += errors[i] + "\n";
                }
                alert(errorOutput);
            }
        } catch(e) {
            alert(e);
        }
        return false;
    },

    loadResults: function(event) {
        var parameters = $('modernisationForm').serialize(true);
        var parameterString = 'type=' + parameters['modernisationType'];
        parameterString += '&state=' + $('modernisationForm').getInputs('radio', 'modernisationState').find(function(r){return r.checked}).value;
        parameterString += '&wsv=' + parameters['modernisationWsv']

        if (event.target.id == 'modernisationResultsInsulatedButton') {
            parameterString += '&isolation=gedaemmt';
        } else {
            parameterString += '&isolation=ungedaemmt';
        }
        this.modernisationControl.resultLayouter.toggleTabs(event.target.id);
        //alert(Event.element(event.target.id));
        this.modernisationControl.load(parameterString);
    }
});