﻿/* ********************************************************** */
/* Initialise tab manager                                     */        
/* ********************************************************** */
(function () {

    // Add tab to the tab manager.
    if (!ECBCalculator.tabManager.tab1) {
        var tab = ECBCalculatorTab( { index: 0, validationGroupCount: 2 } );
        ECBCalculator.tabManager.addTab(tab);
        ECBCalculator.tabManager.tab1 = tab;
    }
            
})();

/* ********************************************************** */
/* Initialise tab                                             */        
/* ********************************************************** */
(function() {

    /* *************************************** */
    // Private properties/methods.
    /* *************************************** */

    // A matrix of div Id's (by building type) for visibility toggling.
    var matrixForVisibility =
        [
            ['_t4p1Div', '_t1p2_div8', '_t1p2_div9', '_t1p2_div10', '_t1p2_div11', '_t1p2_div12', '_t1p2_div13', '_t1p2_div14', '_t1p2_div15'],
            ['_t4p2Div', '_t1p2_div8'],
            ['_t4p3Div'],
            ['_t4p4Div', '_t3p1_div4']
        ];
    // A matrix of control Id's (by building type) for validator toggling.
    var matrixForValidators =
        [
            ['_t1p2_ApartmentsCount', '_t1p2_ApartmentsCount1Room', '_t1p2_ApartmentsCount2Room', '_t1p2_ApartmentsCount3Room', '_t1p2_ApartmentsCount4Room', '_t1p2_ApartmentsCount5Room', '_t1p2_ApartmentsCount6Room', '_t1p2_ApartmentsCountOver6Room'],
            ['_t1p2_ApartmentsCount'],
            [],
            ['_t3p1_DaysPerWeekGymOtherUse']
        ];

    // Toggles control state by executing the passed handler.
    function toggleState(buildingType, matrix, toggleStateHandler) {
        var controls, controlId, i, j;
        // Hide controls not related to building type.
        for (i = 0; i < matrix.length; i += 1) {
            if (i !== (buildingType - 1)) {
                controls = matrix[i];
                for (j = 0; j < controls.length; j += 1) {
                    controlId = controls[j];
                    toggleStateHandler(controlId, false);
                }
            }
        }
        // Display controls related to building type.
        controls = matrix[(buildingType - 1)];
        for (j = 0; j < controls.length; j += 1) {
            controlId = controls[j];
            toggleStateHandler(controlId, true);
        }
    }

    /* *************************************** */
    // Public properties/methods.
    /* *************************************** */


    /* ********************************************************** */
    /* Building type events handlers                              */
    /* ********************************************************** */

    /* Building type change event handler. */
    if (typeof ECBCalculator.tabManager.tab1.onBuildingTypeChange !== 'function') {
        ECBCalculator.tabManager.tab1.onBuildingTypeChange = function(buildingTypeAsString) {
            if (buildingTypeAsString) {
                // Derive building type.
                var buildingType = parseInt(buildingTypeAsString);

                // Toggle input control state.
                toggleState(buildingType, matrixForValidators, ECBCalculator.toggleInputControlState);

                // Only the active index (control) will be validated
                ECBCalculator.tab4ActiveIndex = buildingType;

                // Toggle visibilty state.
                toggleState(buildingType, matrixForVisibility, KeaneUtils.toggleVisibilityState);
                var txtAppartmentCount = window['_t1p2_ApartmentsCount'];
                if (txtAppartmentCount !== undefined) {
                    if (buildingType === 1) {
                        txtAppartmentCount.SetEnabled(false);
                        ECBCalculator.tabManager.tab1.CalculateRoomComboIndex();
                    }
                    else {
                        txtAppartmentCount.SetEnabled(true);
                    }
                }
            }
        };
    }

    /* Room count index event handler. */
    if (typeof ECBCalculator.tabManager.tab1.onRoomCountTextChanged !== 'function') {
        ECBCalculator.tabManager.tab1.onRoomCountTextChanged = function(appartmentCount) {
            if (ECBCalculator.tab4ActiveIndex === 1) {
                ECBCalculator.tabManager.tab1.CalculateRoomComboIndex();
                ECBCalculator.tabManager.tab4.SetAverageRoomCalculatedIndex();
            }
        };
    }

    if (typeof ECBCalculator.tabManager.tab1.CalculateRoomComboIndex !== 'function') {
        ECBCalculator.tabManager.tab1.CalculateRoomComboIndex = function() {
            var totalRoom = 0;
            var totalAppartmentCount = 0;
            for (var i = 1; i < 8; i++) {
                totalRoom = totalRoom + GetAppartmentCountAt(i) * i;
                totalAppartmentCount = totalAppartmentCount + GetAppartmentCountAt(i);
            }
            var averageRoom = Math.round(totalRoom / totalAppartmentCount);
            if (((totalRoom / totalAppartmentCount) - Math.floor((totalRoom / totalAppartmentCount))) === 0.5) {
                averageRoom = averageRoom - 1;
            }
            //selected index is between 0 and 6
            if (averageRoom >= 1 && averageRoom <= 7) {
                if (averageRoom === 7) {
                    _tab1Tracker.Set('roomAverageIndex', averageRoom - 2);
                }
                else {
                    _tab1Tracker.Set('roomAverageIndex', averageRoom - 1);
                }
            }
            else {
                _tab1Tracker.Set('roomAverageIndex', 0);
            }
            var txtAppartmentCount = window['_t1p2_ApartmentsCount'];
            if (txtAppartmentCount !== undefined) {
                txtAppartmentCount.SetText(totalAppartmentCount);
                txtAppartmentCount.Validate();
            }
        };
    }

    /* return the room count for the given text box index (between 0 and 7) */
    function GetAppartmentCountAt(index) {
        var result = 0;
        var txtRoomCount = GetAppartmentCountControlAt(index);
        if (txtRoomCount !== null && txtRoomCount !== undefined) {
            result = parseInt(txtRoomCount.GetValue());
        }
        if (isNaN(result)) {
            result = 0;
        }
        return result;
    }

    /* Return the room count control for the given text box index (between 0 and 7) */
    function GetAppartmentCountControlAt(index) {
        var txtRoomCountControl;
        var result;
        var txtRoomCountControlName = '_t1p2_ApartmentsCount{0}Room';
        if (index === 7) {
            txtRoomCountControlName = '_t1p2_ApartmentsCountOver6Room';
        }
        else {
            txtRoomCountControlName = txtRoomCountControlName.replace('{0}', index)
        }
        return window[txtRoomCountControlName];
    }

    /* ********************************************************** */
    /* Total appartment count validation                        */
    /* ********************************************************** */
    /* GetAppartmentCountAt(i) */
    var totalAppartmentCountInValidation = false;
    if (typeof ECBCalculator.tabManager.tab1.Validate_TotalAppartmentCount !== 'function') {
        ECBCalculator.tabManager.tab1.Validate_TotalAppartmentCount = function(s, e, controlId) {
            var appartmentCountControl;
            if (ECBCalculator.tab4ActiveIndex === 1 && controlId !== '_t1p2_ApartmentsCount') {
                // Check if total is between 1 and 999.
                var totalAppartmentCount = 0;
                for (var i = 1; i < 8; i++) {
                    totalAppartmentCount = totalAppartmentCount + GetAppartmentCountAt(i);
                }
                e.isValid = (totalAppartmentCount > 0 && totalAppartmentCount < 1000);

                if (!totalAppartmentCountInValidation) {
                    // Validate the other controls.
                    totalAppartmentCountInValidation = true;
                    for (var index2 = 1; index2 < 8; index2++) {
                        appartmentCountControl = GetAppartmentCountControlAt(index2);
                        if (appartmentCountControl.name.indexOf(controlId) < 0) {
                            appartmentCountControl.Validate()
                        }
                    }
                    totalAppartmentCountInValidation = false;
                }
            }
            else if (ECBCalculator.tab4ActiveIndex === 2 && controlId === '_t1p2_ApartmentsCount') {
                appartmentCountControl = window['_t1p2_ApartmentsCount'];
                if (appartmentCountControl !== null && appartmentCountControl !== undefined) {
                    var result = parseInt(appartmentCountControl.GetValue());
                    if (isNaN(result)) {
                        result = 0;
                    }
                    e.isValid = (result > 0 && result < 3);
                }
            }
        };
    }

    /* Initialize all renovation year */
    if (typeof ECBCalculator.tabManager.tab1.initializeAllRenovationYear !== 'function') {
        ECBCalculator.tabManager.tab1.initializeAllRenovationYear = function(s, e) {
            initializeRenovationYear(s, '_t2p3_AtticFloorRenovationYear');
            initializeRenovationYear(s, '_t2p2_RoofRenovationYear');
            initializeRenovationYear(s, '_t2p4_ExternalWallsRenovationYear');
            initializeRenovationYear(s, '_t2p5_PartsNearEarthRenovationYear');
            initializeRenovationYear(s, '_t2p6_WindowsYearOfBuilt');
            initializeRenovationYear(s, '_t2p6_WindowsRenovationYear');
            initializeRenovationYear(s, '_t3p1_RenovationYear');
            initializeRenovationYear(s, '_t3p2_RenovationYear');
        };
    }

    /* Validate construction year */
    if (typeof ECBCalculator.tabManager.tab1.validateConstructionYear1291 !== 'function') {
        ECBCalculator.tabManager.tab1.validateConstructionYear1291 = function(s, e) {
            e.isValid = (s.GetValue() >= 1291 &&
                         s.GetValue() <= new Date().getFullYear());
        };
    }

    /* Validate renovation year */
    if (typeof ECBCalculator.tabManager.tab1.validateRenovationYear1291 !== 'function') {
        ECBCalculator.tabManager.tab1.validateRenovationYear1291 = function(s, e) {
            e.isValid = internalValidateRenovationYear(s, 1291);
        };
    }

    /* Validate renovation year */
    function internalValidateRenovationYear(s, minYear) {
        // Check if renovation year is not smaller than construction year and in valid range.
        var controlConstYear = window['_t1p2_YearOfConstruction'];
        return (s.GetValue() >= controlConstYear.GetValue() &&
                s.GetValue() >= minYear &&
                s.GetValue() <= new Date().getFullYear());
    }

    /* Initialize renovation year */
    function initializeRenovationYear(constructionYearControl, renovationYearControlId) {
        var controlRenovYear = window[renovationYearControlId];
        if (constructionYearControl !== null && constructionYearControl !== undefined &&
            controlRenovYear !== null && controlRenovYear !== undefined &&
            controlRenovYear.GetClientVisible() &&
            controlRenovYear.GetValue() < constructionYearControl.GetValue()) {
            controlRenovYear.SetValue(constructionYearControl.GetValue());
        }
    }

})();

/* ********************************************************** */
/* Retrieve postal data callback
/* ********************************************************** */
/* Callback type change event handler. */
if (typeof ECBCalculator.tabManager.tab1.PerformLocation_CallBack !== 'function') {
    ECBCalculator.tabManager.tab1.PerformLocation_CallBack = function() {
        var zipControl = window['_t1p2_Zip'];
        if (zipControl !== null && zipControl !== undefined) {
            if (zipControl.GetValue() !== null) {
                zipControl.Validate();
                if (zipControl.GetIsValid()) {
                    var townControl = window['_t1p2_Town'];
                    if (townControl !== null && townControl !== undefined) {
                        // Empty text box
                        _t1p2_BuildingNumber.SetValue(null);
                        _t1p2_EGID.SetValue(null);
                        //Populating Towns
                        townControl.PerformCallback('RetrieveTownData');
                        ECBCalculator.tabManager.tab1.PerformStreet_CallBack();
                        ECBCalculator.tabManager.tab1.PerformWeatherStation_CallBack();
                    }
                }
            }
        }
    };
}

/* Callback type change event handler. */
if (typeof ECBCalculator.tabManager.tab1.PerformStreet_CallBack !== 'function') {
    ECBCalculator.tabManager.tab1.PerformStreet_CallBack = function() {
        var control = window['_t1p2_Zip'];
        if (control !== null && control !== undefined) {
            if (control.GetValue() !== null) {
                control.Validate();
                if (control.GetIsValid()) {
                    control = window['_t1p2_Street'];
                    //Populating streets
                    if (control !== null && control !== undefined) {
                        control.PerformCallback('RetrieveStreetData');
                    }
                }
            }
        }
    };
}

/* Callback type change event handler. */
if (typeof ECBCalculator.tabManager.tab1.PerformBuildingNumber_CallBack !== 'function') {
    ECBCalculator.tabManager.tab1.PerformBuildingNumber_CallBack = function() {
        var control = window['_t1p2_Street'];
        if (control !== null && control !== undefined) {
            if (control.GetValue() !== null) {
                control.Validate();
                if (control.GetIsValid()) {
                    control = window['_t1p2_BuildingNumber'];
                    // Empty text box
                    _t1p2_EGID.SetValue(null);

                    //Populating Building numbers
                    if (control !== null && control !== undefined) {
                        control.PerformCallback('RetrieveBuildingNumberData');
                    }
                }
            }
        }
    };
}

/* Callback type change event handler. */
if (typeof ECBCalculator.tabManager.tab1.PerformWeatherStation_CallBack !== 'function') {
    ECBCalculator.tabManager.tab1.PerformWeatherStation_CallBack = function() {
        var control = window['_t1p2_Zip'];
        if (control !== null && control !== undefined) {
            if (control.GetValue() !== null) {
                control.Validate();
                if (control.GetIsValid()) {
                    control = window['_t1p2_WeatherStation'];
                    //Populating weather stations
                    if (control !== null && control !== undefined) {
                        control.PerformCallback('RetrieveWeatherStationData');
                    }
                }
            }
        }
    };
}

/* Callback type change event handler. */
if (typeof ECBCalculator.tabManager.tab1.PerformEGIDNumber_CallBack !== 'function') {
    ECBCalculator.tabManager.tab1.PerformEGIDNumber_CallBack = function() {
        var control = window['_t1p2_Zip'];
        if (control !== null && control !== undefined) {
            if (control.GetValue() !== null) {
                control.Validate();
                if (control.GetIsValid()) {
                    // Retrieve.
                    var command = GuiController.getCommand('RetrieveEGIDNumber');
                    if (!command) {
                        return;
                    }
                    command.onInvoke();
                }
            }
        }
    };
}