<commit_before>(function () {
    'use strict';
    angular.module('app.form')
        .controller('indFormController', indFormController);
    function indFormController() {
        var vm = this;
        vm.set1 = null;
        vm.set2 = null;
        vm.set3 = null;
        vm.set4a = null;
        vm.set4b = null;
        vm.set5a = null;
        vm.set5b = null;
        vm.set6 = null;
        vm.indivContrib = null;
        vm.coCare = null;
        vm.diff = null;
        vm.sumCheckResult = null;
        vm.form = {
            premium: 0,
            deductible: 0,
            copay: 0,
            expenses: 0,
            w2: 0,
            otherIncome: null,
            filing: null,
            irsSum: 0,
            irs20b: 0,
            spouseA: {
                age: null,
                monthlySS: 0,
                irsRetirement: 0,
                ssShare: null,
                exemption: null
            },
            spouseB: {
                age: null,
                monthlySS: 0,
                irsRetirement: 0,
                ssShare: null,
                exemption: null
            }
        };

        vm.sumCheck = sumCheck;
        vm.move = move;
        vm.startOver = startOver;

        activate();

        function activate() {
            vm.set1 = true;
            console.log('init indFormController vm.set1', vm.set1);
        }

        function move(set){
            switch(set){
                case 'set1':
                    vm.set1 = true;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set2':
                    vm.set1 = null;
                    vm.set2 = true;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set3':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = true;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set4a':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = true;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set4b':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = true;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set5a':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = true;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set5b':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = true;
                    vm.set6 = null;
                    break;
                case 'set6':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = true;
                    calc();
                    break;
            }
        }

        function startOver() {
            vm.form = {
                premium: 0,
                deductible: 0,
                copay: 0,
                expenses: 0,
                w2: 0,
                otherIncome: null,
                filing: null,
                irsSum: 0,
                irs20b: 0,
                spouseA: {
                    age: null,
                    monthlySS: 0,
                    irsRetirement: 0,
                    ssShare: null,
                    exemption: null
                },
                spouseB: {
                    age: null,
                    monthlySS: 0,
                    irsRetirement: 0,
                    ssShare: null,
                    exemption: null
                }
            };
            move('set1');
        }

        function sumCheck() {
            switch(vm.form.filing){
                case 'single':
                    console.log('single sumCheck', vm.form.irs20b + vm.form.spouseA.irsRetirement > vm.form.irsSum);
                    if(vm.form.irs20b + vm.form.spouseA.irsRetirement > vm.form.irsSum){
                        return true;
                    }
                    break;
                case 'joint':
                    if(vm.form.irs20b + vm.form.spouseA.irsRetirement + vm.form.spouseB.irsRetirement > vm.form.irsSum){
                        return true;
                    }
                    break;
            }
        }

        function ssRatioCalc(){
            vm.form.spouseA.ssShare = (12 * vm.form.spouseA.monthlySS)/ vm.form.irs20b;
            vm.form.spouseB.ssShare = (12 * vm.form.spouseB.monthlySS)/ vm.form.irs20b;
        }

        function jointCalc(){
            console.log('jointCalc vm.form', vm.form);
            var taxIncome = vm.form.irsSum - (vm.form.spouseA.exemption + vm.form.spouseB.exemption);
            if(taxIncome > 0){
                vm.coCare = Number((taxIncome * 0.1) + (vm.form.w2 * 0.0333)).toFixed(2);
            }
            else {
                vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(2);
            }
            vm.diff = (vm.indivContrib - vm.coCare).toFixed(2);
        }

        function calc() {
            vm.indivContrib = (vm.form.premium * 12) + vm.form.deductible + vm.form.copay + vm.form.expenses;
            switch(vm.form.filing){
                case 'single':
                    if(vm.form.w2 > 350000){
                        console.log('single w2 limit');
                        vm.form.w2 = 350000;
                    }
                    switch(vm.form.spouseA.age){
                        case 'under':
                            vm.coCare = Number((vm.form.w2 * 0.0333) + (vm.form.irsSum) * 0.1).toFixed(2);
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                        case 'between':
                            var sum = vm.form.irs20b + vm.form.spouseA.irsRetirement;
                            console.log('between sum', sum);
                            if(sum > 20000){
                                if(vm.form.irsSum - 20000 > 0){
                                    vm.coCare = Number((vm.form.w2 * 0.0333) + ((vm.form.irsSum - 20000) * 0.1)).toFixed(2);
                                }
                                else {
                                    vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(0);
                                }
                            }
                            else {
                                if(vm.form.irsSum - sum > 0){
                                    vm.coCare = Number((vm.form.w2 * 0.0333) + ((vm.form.irsSum - sum)* 0.1)).toFixed(2);
                                }
                                else {
                                    vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(2);
                                }
                            }
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                        case 'over':
                            var sum = vm.form.irs20b + vm.form.spouseA.irsRetirement;
                            console.log('over sum', sum);
                            if(sum > 24000){
                                if(vm.form.irsSum - 24000 > 0){
                                    vm.coCare = Number((0.1 * (vm.form.irsSum - 24000)) + (vm.form.w2 * 0.0333)).toFixed(2);
                                }
                                else {
                                    vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(2);
                                }
                            }
                            else{
                                if(vm.form.irsSum - sum > 0){
                                    vm.coCare = Number((0.1 * (vm.form.irsSum - sum)) + (vm.form.w2 * 0.0333)).toFixed(2);
                                }
                                else {
                                    vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(2);
                                }
                            }
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                    }
                    break;
                case 'joint':
                    if(vm.form.w2 > 450000){
                        console.log('joint w2 limit');
                        vm.form.w2 = 450000;
                    }
                    if(vm.form.spouseA.age === 'under' && vm.form.spouseB.age === 'under'){
                        vm.coCare = Number((0.1 * vm.form.irsSum) + (vm.form.w2 * 0.0333)).toFixed();
                        vm.diff = vm.indivContrib - vm.coCare;
                    }
                    else{
                        ssRatioCalc();
                        switch(vm.form.spouseA.age){
                            case 'under':
                                vm.form.spouseA.exemption = 0;
                                break;
                            case 'between':
                                var sum = vm.form.irs20b * vm.form.spouseA.ssShare + vm.form.spouseA.irsRetirement;
                                console.log('over sum', sum);
                                if(sum > 20000){
                                    vm.form.spouseA.exemption = 20000;
                                }
                                else{
                                    vm.form.spouseA.exemption = sum;
                                }
                                break;
                            case 'over':
                                var sum = vm.form.irs20b * vm.form.spouseA.ssShare + vm.form.spouseA.irsRetirement;
                                console.log('over sum', sum);
                                if(sum > 24000){
                                    vm.form.spouseA.exemption = 24000;
                                }
                                else{
                                    vm.form.spouseA.exemption = sum;
                                }
                                break;
                        }
                        switch(vm.form.spouseB.age){
                            case 'under':
                                vm.form.spouseB.exemption = 0;
                                break;
                            case 'between':
                                var sum = vm.form.irs20b * vm.form.spouseB.ssShare + vm.form.spouseB.irsRetirement;
                                console.log('between sum', sum);
                                if(sum > 20000){
                                    vm.form.spouseB.exemption = 20000;
                                }
                                else{
                                    vm.form.spouseB.exemption = sum;
                                }
                                break;
                            case 'over':
                                var sum = vm.form.irs20b * vm.form.spouseB.ssShare + vm.form.spouseB.irsRetirement;
                                console.log('over sum', sum);
                                if(sum > 24000){
                                    vm.form.spouseB.exemption = 24000;
                                }
                                else{
                                    vm.form.spouseB.exemption = sum;
                                }
                                break;
                        }
                        jointCalc();
                    }
                    break;
                default:
                    vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(2);
                    vm.diff = (vm.indivContrib - vm.coCare).toFixed(2);
            }
        }
    }
})();<commit_msg>Example of the max check as a comment<commit_after>(function () {
    'use strict';
    angular.module('app.form')
        .controller('indFormController', indFormController);
    function indFormController() {
        var vm = this;
        vm.set1 = null;
        vm.set2 = null;
        vm.set3 = null;
        vm.set4a = null;
        vm.set4b = null;
        vm.set5a = null;
        vm.set5b = null;
        vm.set6 = null;
        vm.indivContrib = null;
        vm.coCare = null;
        vm.diff = null;
        vm.sumCheckResult = null;
        vm.form = {
            premium: 0,
            deductible: 0,
            copay: 0,
            expenses: 0,
            w2: 0,
            otherIncome: null,
            filing: null,
            irsSum: 0,
            irs20b: 0,
            spouseA: {
                age: null,
                monthlySS: 0,
                irsRetirement: 0,
                ssShare: null,
                exemption: null
            },
            spouseB: {
                age: null,
                monthlySS: 0,
                irsRetirement: 0,
                ssShare: null,
                exemption: null
            }
        };

        vm.sumCheck = sumCheck;
        vm.move = move;
        vm.startOver = startOver;

        activate();

        function activate() {
            vm.set1 = true;
            console.log('init indFormController vm.set1', vm.set1);
        }

        function move(set){
            switch(set){
                case 'set1':
                    vm.set1 = true;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set2':
                    vm.set1 = null;
                    vm.set2 = true;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set3':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = true;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set4a':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = true;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set4b':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = true;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set5a':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = true;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set5b':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = true;
                    vm.set6 = null;
                    break;
                case 'set6':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = true;
                    calc();
                    break;
            }
        }

        function startOver() {
            vm.form = {
                premium: 0,
                deductible: 0,
                copay: 0,
                expenses: 0,
                w2: 0,
                otherIncome: null,
                filing: null,
                irsSum: 0,
                irs20b: 0,
                spouseA: {
                    age: null,
                    monthlySS: 0,
                    irsRetirement: 0,
                    ssShare: null,
                    exemption: null
                },
                spouseB: {
                    age: null,
                    monthlySS: 0,
                    irsRetirement: 0,
                    ssShare: null,
                    exemption: null
                }
            };
            move('set1');
        }

        function sumCheck() {
            switch(vm.form.filing){
                case 'single':
                    console.log('single sumCheck', vm.form.irs20b + vm.form.spouseA.irsRetirement > vm.form.irsSum);
                    if(vm.form.irs20b + vm.form.spouseA.irsRetirement > vm.form.irsSum){
                        return true;
                    }
                    break;
                case 'joint':
                    if(vm.form.irs20b + vm.form.spouseA.irsRetirement + vm.form.spouseB.irsRetirement > vm.form.irsSum){
                        return true;
                    }
                    break;
            }
        }

        function ssRatioCalc(){
            vm.form.spouseA.ssShare = (12 * vm.form.spouseA.monthlySS)/ vm.form.irs20b;
            vm.form.spouseB.ssShare = (12 * vm.form.spouseB.monthlySS)/ vm.form.irs20b;
        }

        function jointCalc(){
            console.log('jointCalc vm.form', vm.form);
            var taxIncome = vm.form.irsSum - (vm.form.spouseA.exemption + vm.form.spouseB.exemption);
            if(taxIncome > 0){
                vm.coCare = Number((taxIncome * 0.1) + (vm.form.w2 * 0.0333)).toFixed(2);
            }
            else {
                vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(2);
            }
            vm.diff = (vm.indivContrib - vm.coCare).toFixed(2);
        }

/*
     results.incomeTaxCap = incomeTaxCap;
    // TAX CAP
  	// first tax on the w2 income - tax this first for individual as employer has already paid on this one
  	if (w2 >= incomeTaxCap) {
  		w2 = incomeTaxCap;
  		incomeTaxCap = 0;
  	} else if (w2 > 0) {
  		incomeTaxCap -= w2;
  	}

  	// second apply the remaining cap to nonw2 income - paying full tax, so after w2 tax this last
  	if (nonw2 >= incomeTaxCap) {
  		nonw2 = incomeTaxCap;
  		incomeTaxCap = 0;
  	} else if (nonw2 > 0) {
  		incomeTaxCap -= nonw2;
  	}

  	// third apply the remaining cap to after exemptionRetirement income - paying full tax, so after w2 tax this last
  	if (incomeRetirement >= incomeTaxCap) {
  		incomeRetirement = incomeTaxCap;
  		incomeTaxCap = 0;
  	} else if (incomeRetirement > 0) {
  		incomeTaxCap -= incomeRetirement;
  	}

    let w2Tax = w2 * ($scope.CCW2PercentTax - formData.workPercentageSubsidy/100);
    let nonw2Tax = nonw2 * $scope.CCPercentTax;
    let incomeRetirementTax = incomeRetirement * $scope.CCPercentTax;

 */

        function calc() {
            vm.indivContrib = (vm.form.premium * 12) + vm.form.deductible + vm.form.copay + vm.form.expenses;
            switch(vm.form.filing){
                case 'single':
                    if(vm.form.w2 > 350000){
                        console.log('single w2 limit');
                        vm.form.w2 = 350000;
                    }
                    switch(vm.form.spouseA.age){
                        case 'under':
                            vm.coCare = Number((vm.form.w2 * 0.0333) + (vm.form.irsSum) * 0.1).toFixed(2);
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                        case 'between':
                            var sum = vm.form.irs20b + vm.form.spouseA.irsRetirement;
                            console.log('between sum', sum);
                            if(sum > 20000){
                                if(vm.form.irsSum - 20000 > 0){
                                    vm.coCare = Number((vm.form.w2 * 0.0333) + ((vm.form.irsSum - 20000) * 0.1)).toFixed(2);
                                }
                                else {
                                    vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(0);
                                }
                            }
                            else {
                                if(vm.form.irsSum - sum > 0){
                                    vm.coCare = Number((vm.form.w2 * 0.0333) + ((vm.form.irsSum - sum)* 0.1)).toFixed(2);
                                }
                                else {
                                    vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(2);
                                }
                            }
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                        case 'over':
                            var sum = vm.form.irs20b + vm.form.spouseA.irsRetirement;
                            console.log('over sum', sum);
                            if(sum > 24000){
                                if(vm.form.irsSum - 24000 > 0){
                                    vm.coCare = Number((0.1 * (vm.form.irsSum - 24000)) + (vm.form.w2 * 0.0333)).toFixed(2);
                                }
                                else {
                                    vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(2);
                                }
                            }
                            else{
                                if(vm.form.irsSum - sum > 0){
                                    vm.coCare = Number((0.1 * (vm.form.irsSum - sum)) + (vm.form.w2 * 0.0333)).toFixed(2);
                                }
                                else {
                                    vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(2);
                                }
                            }
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                    }
                    break;
                case 'joint':
                    if(vm.form.w2 > 450000){
                        console.log('joint w2 limit');
                        vm.form.w2 = 450000;
                    }
                    if(vm.form.spouseA.age === 'under' && vm.form.spouseB.age === 'under'){
                        vm.coCare = Number((0.1 * vm.form.irsSum) + (vm.form.w2 * 0.0333)).toFixed();
                        vm.diff = vm.indivContrib - vm.coCare;
                    }
                    else{
                        ssRatioCalc();
                        switch(vm.form.spouseA.age){
                            case 'under':
                                vm.form.spouseA.exemption = 0;
                                break;
                            case 'between':
                                var sum = vm.form.irs20b * vm.form.spouseA.ssShare + vm.form.spouseA.irsRetirement;
                                console.log('over sum', sum);
                                if(sum > 20000){
                                    vm.form.spouseA.exemption = 20000;
                                }
                                else{
                                    vm.form.spouseA.exemption = sum;
                                }
                                break;
                            case 'over':
                                var sum = vm.form.irs20b * vm.form.spouseA.ssShare + vm.form.spouseA.irsRetirement;
                                console.log('over sum', sum);
                                if(sum > 24000){
                                    vm.form.spouseA.exemption = 24000;
                                }
                                else{
                                    vm.form.spouseA.exemption = sum;
                                }
                                break;
                        }
                        switch(vm.form.spouseB.age){
                            case 'under':
                                vm.form.spouseB.exemption = 0;
                                break;
                            case 'between':
                                var sum = vm.form.irs20b * vm.form.spouseB.ssShare + vm.form.spouseB.irsRetirement;
                                console.log('between sum', sum);
                                if(sum > 20000){
                                    vm.form.spouseB.exemption = 20000;
                                }
                                else{
                                    vm.form.spouseB.exemption = sum;
                                }
                                break;
                            case 'over':
                                var sum = vm.form.irs20b * vm.form.spouseB.ssShare + vm.form.spouseB.irsRetirement;
                                console.log('over sum', sum);
                                if(sum > 24000){
                                    vm.form.spouseB.exemption = 24000;
                                }
                                else{
                                    vm.form.spouseB.exemption = sum;
                                }
                                break;
                        }
                        jointCalc();
                    }
                    break;
                default:
                    vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(2);
                    vm.diff = (vm.indivContrib - vm.coCare).toFixed(2);
            }
        }
    }
})();<|endoftext|>


<commit_before>"use strict";

define(['logManager',
    'clientUtil',
    'js/DragDrop/DragHelper',
    'js/Widgets/DiagramDesigner/DiagramDesignerWidget',
    'js/Controls/iCheckBox',
    './MetaEditorPointerNamesDialog',
    'js/Toolbar/ToolbarButton',
    'js/Toolbar/ToolbarDropDownButton',
    'css!/css/Widgets/MetaEditor/MetaEditorWidget'], function (logManager,
                                                             clientUtil,
                                                             DragHelper,
                                                             DiagramDesignerWidget,
                                                             iCheckBox,
                                                             MetaEditorPointerNamesDialog,
                                                             ToolbarButton,
                                                             ToolbarDropDownButton) {

    var MetaEditorWidget,
        __parent__ = DiagramDesignerWidget,
        __parent_proto__ = DiagramDesignerWidget.prototype,
        SHEETS_CONTAINER = "sheets-container",
        ADD_SHEET_CONTAINER_CLASS = 'add-sheet-container',
        SHEET_LIST_CONTAINER_CLASS = 'sheet-list-container',
        SHEET_SCROLL = 200,
        SHEET_ID = 'SHEET_ID';

    MetaEditorWidget = function (container, params) {
        params = params || {};
        params.loggerName = "MetaEditorWidget";

        __parent__.call(this, container, params);

        this.logger.debug("MetaEditorWidget ctor");
    };

    _.extend(MetaEditorWidget.prototype, DiagramDesignerWidget.prototype);

    MetaEditorWidget.prototype._initializeUI = function (containerElement) {
        __parent_proto__._initializeUI.apply(this, arguments);
        this.logger.debug("MetaEditorWidget._initializeUI");

        //disable connection to a connection
        this._connectToConnection = false;

        this._initializeFilterPanel();

        this._initializeSheets();
    };

    MetaEditorWidget.prototype._afterManagersInitialized = function () {
        //turn off item rotation
        this.enableRotate(false);
    };

    MetaEditorWidget.prototype._initializeFilterPanel = function () {
        /**** create FILTER PANEL ****/
        this.$filterPanel = $('
', {
            'class': 'filterPanel'
        });

        this.$filterPanel.html('
FILTER

');

        this.$filterHeader = this.$filterPanel.find('.header');
        this.$filterUl = this.$filterPanel.find('ul.body');

        this.$el.parent().append(this.$filterPanel);

        this._filterCheckboxes = {};
    };

    MetaEditorWidget.prototype._checkChanged = function (value, isChecked) {
        this._refreshHeaderText();
        this.logger.debug("CheckBox checkChanged: " + value + ", checked: " + isChecked);
        this.onCheckChanged(value, isChecked);
    };

    MetaEditorWidget.prototype.onCheckChanged = function (value, isChecked) {
        this.logger.warning('MetaEditorWidget.onCheckChanged(value, isChecked) is not overridden!');
    };

    MetaEditorWidget.prototype.addFilterItem = function (text, value, iconEl) {
        var item = $('
', {
                'class': 'filterItem'
            }),
            checkBox,
            self = this;

        checkBox = new iCheckBox({
            "checkChangedFn": function (data, isChecked) {
                self._checkChanged(value, isChecked);
            }});

        item.append(iconEl.addClass('inline'));
        item.append(text);
        item.append(checkBox.el);

        this.$filterUl.append(item);

        this._refreshHeaderText();

        this._filterCheckboxes[value] = checkBox;

        return item;
    };

    MetaEditorWidget.prototype._refreshHeaderText = function () {
        var all = this.$filterUl.find('.iCheckBox').length,
            on = this.$filterUl.find('.iCheckBox.checked').length;

        this.$filterHeader.html('FILTER' + (all === on ? '' : ' *'));
    };

    MetaEditorWidget.prototype.selectNewPointerName = function (existingPointerNames, notAllowedPointerNames, isPointerList, callBack) {
       new MetaEditorPointerNamesDialog().show(existingPointerNames, notAllowedPointerNames, isPointerList, callBack);
    };

    MetaEditorWidget.prototype.setFilterChecked = function (value) {
        if (this._filterCheckboxes[value] && !this._filterCheckboxes[value].isChecked()) {
            this._filterCheckboxes[value].setChecked(true);
        }
    };

    MetaEditorWidget.prototype.getDragEffects = function (selectedElements, event) {
        //the only drag is a MOVE
        return [DragHelper.DRAG_EFFECTS.DRAG_MOVE];
    };

    /* OVERWRITE DiagramDesignerWidget.prototype._dragHelper */
    MetaEditorWidget.prototype._dragHelper = function (el, event, dragInfo) {
        var helperEl = DiagramDesignerWidget.prototype._dragHelper.apply(this, [el, event, dragInfo]);

        //clear out default 'Move' text from helperEl
        helperEl.html('');

        return helperEl;
    };

    MetaEditorWidget.prototype._initializeSheets = function () {
        var self = this;

        this.$sheetsContainer = $('
', { 'class': SHEETS_CONTAINER });

        this.$el.parent().append(this.$sheetsContainer);

        this._sheetCounter = 0;

        this._selectedSheet = undefined;

        this.$divAddSheet = $('
', {'class': ADD_SHEET_CONTAINER_CLASS});

        this.$btnAddSheet = new ToolbarButton({ "title": "Add new sheet...",
            "icon": "icon-plus",
            "clickFn": function (/*data*/) {
                self.onSheetAddClicked();
            }});
        this.$divAddSheet.append(this.$btnAddSheet.el);

        this.$ddlSheetsList = new ToolbarDropDownButton({ "title": "Sheet list",
            "icon": "icon-list"});
        this.$divAddSheet.append(this.$ddlSheetsList.el);

        this.$btnScrollLeft = new ToolbarButton({ "title": "Scroll left",
            "icon": "icon-chevron-left",
            "clickFn": function (/*data*/) {
                self._sheetsScrollLeft();
            } });
        this.$divAddSheet.append(this.$btnScrollLeft.el);

        this.$btnScrollRight = new ToolbarButton({ "title": "Scroll right",
            "icon": "icon-chevron-right",
            "clickFn": function (/*data*/) {
                self._sheetsScrollRight();
            } });
        this.$divAddSheet.append(this.$btnScrollRight.el);

        this.$divSheetList = $('
', {'class': SHEET_LIST_CONTAINER_CLASS});
        this.$ulSheetTab = $('
', {'class': 'nav nav-tabs'});
        this.$divSheetList.append(this.$ulSheetTab);

        this._makeTabsSortable();

        this.$sheetsContainer.append(this.$divAddSheet);
        this.$sheetsContainer.append(this.$divSheetList);

        this._sheetScrollValue = 0;

        //hook up sheet rename
        // set title editable on double-click
        this.$ulSheetTab.on("dblclick.editOnDblClick", '.sheet-title', function (event) {
            if (self.getIsReadOnlyMode() !== true) {
                $(this).editInPlace({"class": "",
                    "onChange": function (oldValue, newValue) {
                        var li = $(this).parent().parent();
                        self.onSheetTitleChanged(li.data(SHEET_ID), oldValue, newValue);
                    }});
            }
            event.stopPropagation();
            event.preventDefault();
        });

        //sheet delete handler
        this.$ulSheetTab.on("click.deleteSheetClick", 'a > i', function (event) {
            if (self.getIsReadOnlyMode() !== true) {
                    self.onSheetDeleteClicked($(this).parent().parent().data(SHEET_ID));
            }
            event.stopPropagation();
            event.preventDefault();
        });

        //sheet selection handler
        this.$ulSheetTab.on("click.selectSheetClick", 'li', function (event) {
            self.selectSheet($(this).data(SHEET_ID));
            event.stopPropagation();
            event.preventDefault();
        });
    };

    MetaEditorWidget.prototype.clearSheets = function () {
        this.$ulSheetTab.sortable('destroy');
        this.$ulSheetTab.empty();
        this._makeTabsSortable();
        this.$ddlSheetsList.clear();
        this._sheetCounter = 0;
        this._selectedSheet = undefined;
        this._scrollSheetListBy(0 - this._sheetScrollValue);
    };

    MetaEditorWidget.prototype._makeTabsSortable = function () {
        var self = this;

        this.$ulSheetTab.sortable({'dropBehaviour': true, 'stop': function () {
            self._onTabsSortStop();
        }});
    };

    MetaEditorWidget.prototype.addSheet = function (title, deletable) {
        var self = this;
        var li = $('

');

        li.find('a').append('
' + title + '
');
        li.data(SHEET_ID, this._sheetCounter + "");
        this._sheetCounter += 1;

        if (deletable === true) {
            li.find('a').append($(''));
            li.find('a').attr('title', 'Delete sheet');
        }

        this.$ulSheetTab.append(li);

        this.$ddlSheetsList.addButton({ "title": title,
            "text": title,
            "data": { 'SHEET_ID': li.data(SHEET_ID)},
            "clickFn": function (data) {
                self.selectSheet(data.SHEET_ID);
            }});

        return li.data(SHEET_ID);
    };

    MetaEditorWidget.prototype._sheetsScrollLeft = function () {
        if (this._sheetScrollValue < 0) {
            this._scrollSheetListBy(Math.min(Math.abs(this._sheetScrollValue), SHEET_SCROLL));
        }
    };

    MetaEditorWidget.prototype._sheetsScrollRight = function () {
        var overflowRightBy = this.$ulSheetTab.width() - this.$sheetsContainer.width() + this.$divAddSheet.outerWidth(true) + this._sheetScrollValue;

        if (overflowRightBy > 0) {
            overflowRightBy = Math.min(overflowRightBy, SHEET_SCROLL);
            this._scrollSheetListBy(-overflowRightBy);
        }
    };

    MetaEditorWidget.prototype._scrollSheetListBy = function (value) {
        this._sheetScrollValue += value;
        this.$ulSheetTab.css('left', this._sheetScrollValue);
    };

    MetaEditorWidget.prototype.selectSheet = function (sheetID) {
        var liToSelect,
            allLi = this.$ulSheetTab.find('li'),
            allDropDownLi = this.$ddlSheetsList.el.find('li'),
            i,
            li,
            ddlSelectedIcon = 'icon-ok';

        if (this._selectedSheet !== sheetID) {
            //select tab
            for(i = 0; i < allLi.length; i += 1) {
                li = $(allLi[i]);
                if (li && li.data(SHEET_ID) === sheetID) {
                    liToSelect = li;
                    break;
                }
            }

            if (liToSelect) {
                this.$ulSheetTab.find('li.active').removeClass('active');
                liToSelect.addClass('active');
                this._selectedSheet = liToSelect.data(SHEET_ID);
                this.onSelectedSheetChanged(this._selectedSheet);
            }

            //select in DropDown
            liToSelect = undefined;
            for(i = 0; i < allDropDownLi.length; i += 1) {
                li = $(allDropDownLi[i]).find('a').first();
                if (li && li.data(SHEET_ID) === sheetID) {
                    liToSelect = $(allDropDownLi[i]);
                    break;
                }
            }

            if (liToSelect) {
                this.$ddlSheetsList.el.find('i.' + ddlSelectedIcon).remove();
                liToSelect.find('a').prepend('');
            }
        }
    };

    MetaEditorWidget.prototype._onTabsSortStop = function () {
        var ul = this.$ulSheetTab,
            allLi = ul.find('li'),
            i,
            li,
            order = [];

        for (i = 0; i < allLi.length; i += 1) {
            li = $(allLi[i]);
            order.push(li.data(SHEET_ID));
        }

        if (order.length > 0) {
            this.onTabsSorted(order);
        }
    };

    MetaEditorWidget.prototype.onSheetDeleteClicked = function (sheetID) {
        this.logger.warning('onSheetDeleteClicked not implemented: "' + sheetID + '"');
    };

    MetaEditorWidget.prototype.onSheetAddClicked = function () {
        var sheetID = this.addSheet('New sheet', true);
        this.logger.warning('onSheetAddClicked not implemented: "' + sheetID + '"');
    };

    MetaEditorWidget.prototype.onSheetTitleChanged = function (sheetID, oldValue, newValue) {
        this.logger.warning('onSheetTitleChanged not implemented: ID: ' + sheetID + ' "' + oldValue + '" --> "' + newValue + '"');
    };

    MetaEditorWidget.prototype.onSelectedSheetChanged = function (sheetID) {
        this.logger.warning('onSelectedSheetChanged not implemented: "' + sheetID + '"');
    };

    MetaEditorWidget.prototype.onTabsSorted = function (newSheetIDOrder) {
        this.logger.warning('onTabsSorted not implemented: "' + newSheetIDOrder + '"');
    };

    return MetaEditorWidget;
});<commit_msg>enable/disable tab scroll buttons when needed, scroll selected tab into view if needed<commit_after>"use strict";

define(['logManager',
    'clientUtil',
    'js/DragDrop/DragHelper',
    'js/Widgets/DiagramDesigner/DiagramDesignerWidget',
    'js/Controls/iCheckBox',
    './MetaEditorPointerNamesDialog',
    'js/Toolbar/ToolbarButton',
    'js/Toolbar/ToolbarDropDownButton',
    'css!/css/Widgets/MetaEditor/MetaEditorWidget'], function (logManager,
                                                             clientUtil,
                                                             DragHelper,
                                                             DiagramDesignerWidget,
                                                             iCheckBox,
                                                             MetaEditorPointerNamesDialog,
                                                             ToolbarButton,
                                                             ToolbarDropDownButton) {

    var MetaEditorWidget,
        __parent__ = DiagramDesignerWidget,
        __parent_proto__ = DiagramDesignerWidget.prototype,
        SHEETS_CONTAINER = "sheets-container",
        ADD_SHEET_CONTAINER_CLASS = 'add-sheet-container',
        SHEET_LIST_CONTAINER_CLASS = 'sheet-list-container',
        SHEET_SCROLL = 200,
        SHEET_ID = 'SHEET_ID';

    MetaEditorWidget = function (container, params) {
        params = params || {};
        params.loggerName = "MetaEditorWidget";

        __parent__.call(this, container, params);

        this.logger.debug("MetaEditorWidget ctor");
    };

    _.extend(MetaEditorWidget.prototype, DiagramDesignerWidget.prototype);

    MetaEditorWidget.prototype._initializeUI = function (containerElement) {
        __parent_proto__._initializeUI.apply(this, arguments);
        this.logger.debug("MetaEditorWidget._initializeUI");

        //disable connection to a connection
        this._connectToConnection = false;

        this._initializeFilterPanel();

        this._initializeSheets();
    };

    MetaEditorWidget.prototype._afterManagersInitialized = function () {
        //turn off item rotation
        this.enableRotate(false);
    };

    MetaEditorWidget.prototype._initializeFilterPanel = function () {
        /**** create FILTER PANEL ****/
        this.$filterPanel = $('
', {
            'class': 'filterPanel'
        });

        this.$filterPanel.html('
FILTER

');

        this.$filterHeader = this.$filterPanel.find('.header');
        this.$filterUl = this.$filterPanel.find('ul.body');

        this.$el.parent().append(this.$filterPanel);

        this._filterCheckboxes = {};
    };

    MetaEditorWidget.prototype._checkChanged = function (value, isChecked) {
        this._refreshHeaderText();
        this.logger.debug("CheckBox checkChanged: " + value + ", checked: " + isChecked);
        this.onCheckChanged(value, isChecked);
    };

    MetaEditorWidget.prototype.onCheckChanged = function (value, isChecked) {
        this.logger.warning('MetaEditorWidget.onCheckChanged(value, isChecked) is not overridden!');
    };

    MetaEditorWidget.prototype.addFilterItem = function (text, value, iconEl) {
        var item = $('
', {
                'class': 'filterItem'
            }),
            checkBox,
            self = this;

        checkBox = new iCheckBox({
            "checkChangedFn": function (data, isChecked) {
                self._checkChanged(value, isChecked);
            }});

        item.append(iconEl.addClass('inline'));
        item.append(text);
        item.append(checkBox.el);

        this.$filterUl.append(item);

        this._refreshHeaderText();

        this._filterCheckboxes[value] = checkBox;

        return item;
    };

    MetaEditorWidget.prototype._refreshHeaderText = function () {
        var all = this.$filterUl.find('.iCheckBox').length,
            on = this.$filterUl.find('.iCheckBox.checked').length;

        this.$filterHeader.html('FILTER' + (all === on ? '' : ' *'));
    };

    MetaEditorWidget.prototype.selectNewPointerName = function (existingPointerNames, notAllowedPointerNames, isPointerList, callBack) {
       new MetaEditorPointerNamesDialog().show(existingPointerNames, notAllowedPointerNames, isPointerList, callBack);
    };

    MetaEditorWidget.prototype.setFilterChecked = function (value) {
        if (this._filterCheckboxes[value] && !this._filterCheckboxes[value].isChecked()) {
            this._filterCheckboxes[value].setChecked(true);
        }
    };

    MetaEditorWidget.prototype.getDragEffects = function (/*selectedElements, event*/) {
        //the only drag is a MOVE
        return [DragHelper.DRAG_EFFECTS.DRAG_MOVE];
    };

    /* OVERWRITE DiagramDesignerWidget.prototype._dragHelper */
    MetaEditorWidget.prototype._dragHelper = function (el, event, dragInfo) {
        var helperEl = DiagramDesignerWidget.prototype._dragHelper.apply(this, [el, event, dragInfo]);

        //clear out default 'Move' text from helperEl
        helperEl.html('');

        return helperEl;
    };

    MetaEditorWidget.prototype._initializeSheets = function () {
        var self = this;

        this.$sheetsContainer = $('
', { 'class': SHEETS_CONTAINER });

        this.$el.parent().append(this.$sheetsContainer);

        this._sheetCounter = 0;

        this._selectedSheet = undefined;

        this.$divAddSheet = $('
', {'class': ADD_SHEET_CONTAINER_CLASS});

        this.$btnAddSheet = new ToolbarButton({ "title": "Add new sheet...",
            "icon": "icon-plus",
            "clickFn": function (/*data*/) {
                self.onSheetAddClicked();
            }});
        this.$divAddSheet.append(this.$btnAddSheet.el);

        this.$ddlSheetsList = new ToolbarDropDownButton({ "title": "Sheet list",
            "icon": "icon-list"});
        this.$divAddSheet.append(this.$ddlSheetsList.el);

        this.$btnScrollLeft = new ToolbarButton({ "title": "Scroll left",
            "icon": "icon-chevron-left",
            "clickFn": function (/*data*/) {
                self._sheetsScrollLeft();
            } });
        this.$divAddSheet.append(this.$btnScrollLeft.el);

        this.$btnScrollRight = new ToolbarButton({ "title": "Scroll right",
            "icon": "icon-chevron-right",
            "clickFn": function (/*data*/) {
                self._sheetsScrollRight();
            } });
        this.$divAddSheet.append(this.$btnScrollRight.el);

        this.$divSheetList = $('
', {'class': SHEET_LIST_CONTAINER_CLASS});
        this.$ulSheetTab = $('
', {'class': 'nav nav-tabs'});
        this.$divSheetList.append(this.$ulSheetTab);

        this._makeTabsSortable();

        this.$sheetsContainer.append(this.$divAddSheet);
        this.$sheetsContainer.append(this.$divSheetList);

        this._sheetScrollValue = 0;

        //hook up sheet rename
        // set title editable on double-click
        this.$ulSheetTab.on("dblclick.editOnDblClick", '.sheet-title', function (event) {
            if (self.getIsReadOnlyMode() !== true) {
                $(this).editInPlace({"class": "",
                    "onChange": function (oldValue, newValue) {
                        var li = $(this).parent().parent();
                        self.onSheetTitleChanged(li.data(SHEET_ID), oldValue, newValue);
                    }});
            }
            event.stopPropagation();
            event.preventDefault();
        });

        //sheet delete handler
        this.$ulSheetTab.on("click.deleteSheetClick", 'a > i', function (event) {
            if (self.getIsReadOnlyMode() !== true) {
                    self.onSheetDeleteClicked($(this).parent().parent().data(SHEET_ID));
            }
            event.stopPropagation();
            event.preventDefault();
        });

        //sheet selection handler
        this.$ulSheetTab.on("click.selectSheetClick", 'li', function (event) {
            self.selectSheet($(this).data(SHEET_ID));
            event.stopPropagation();
            event.preventDefault();
        });
    };

    MetaEditorWidget.prototype.clearSheets = function () {
        this.$ulSheetTab.sortable('destroy');
        this.$ulSheetTab.empty();
        this._makeTabsSortable();
        this.$ddlSheetsList.clear();
        this._sheetCounter = 0;
        this._selectedSheet = undefined;
        this._scrollSheetListBy(0 - this._sheetScrollValue);
    };

    MetaEditorWidget.prototype._makeTabsSortable = function () {
        var self = this;

        this.$ulSheetTab.sortable({'dropBehaviour': true, 'stop': function () {
            self._onTabsSortStop();
        }});
    };

    MetaEditorWidget.prototype.addSheet = function (title, deletable) {
        var self = this;
        var li = $('

');

        li.find('a').append('
' + title + '
');
        li.data(SHEET_ID, this._sheetCounter + "");
        this._sheetCounter += 1;

        if (deletable === true) {
            li.find('a').append($(''));
            li.find('a').attr('title', 'Delete sheet');
        }

        this.$ulSheetTab.append(li);

        this.$ddlSheetsList.addButton({ "title": title,
            "text": title,
            "data": { 'SHEET_ID': li.data(SHEET_ID)},
            "clickFn": function (data) {
                self.selectSheet(data.SHEET_ID);
            }});

        this._refreshTabScrollButtons();

        return li.data(SHEET_ID);
    };

    MetaEditorWidget.prototype._sheetsScrollLeft = function () {
        if (this._sheetScrollValue < 0) {
            this._scrollSheetListBy(Math.min(Math.abs(this._sheetScrollValue), SHEET_SCROLL));
        }
    };

    MetaEditorWidget.prototype._sheetsScrollRight = function () {
        var overflowRightBy = this.$ulSheetTab.width() - this.$sheetsContainer.width() + this.$divAddSheet.outerWidth(true) + this._sheetScrollValue;

        if (overflowRightBy > 0) {
            overflowRightBy = Math.min(overflowRightBy, SHEET_SCROLL);
            this._scrollSheetListBy(-overflowRightBy);
        }
    };

    MetaEditorWidget.prototype._scrollSheetListBy = function (value) {
        this._sheetScrollValue += value;
        this.$ulSheetTab.css('left', this._sheetScrollValue);

        this._refreshTabScrollButtons();
    };

    MetaEditorWidget.prototype.selectSheet = function (sheetID) {
        var liToSelect,
            allLi = this.$ulSheetTab.find('li'),
            allDropDownLi = this.$ddlSheetsList.el.find('li'),
            i,
            li,
            ddlSelectedIcon = 'icon-ok';

        if (this._selectedSheet !== sheetID) {
            //select tab
            for(i = 0; i < allLi.length; i += 1) {
                li = $(allLi[i]);
                if (li && li.data(SHEET_ID) === sheetID) {
                    liToSelect = li;
                    break;
                }
            }

            if (liToSelect) {
                this.$ulSheetTab.find('li.active').removeClass('active');
                liToSelect.addClass('active');
                this._selectedSheet = liToSelect.data(SHEET_ID);
            }

            //select in DropDown
            liToSelect = undefined;
            for(i = 0; i < allDropDownLi.length; i += 1) {
                li = $(allDropDownLi[i]).find('a').first();
                if (li && li.data(SHEET_ID) === sheetID) {
                    liToSelect = $(allDropDownLi[i]);
                    break;
                }
            }

            if (liToSelect) {
                this.$ddlSheetsList.el.find('i.' + ddlSelectedIcon).remove();
                liToSelect.find('a').prepend('');
            }

            this._scrollSelectedTabIntoView();

            //fire event...
            this.onSelectedSheetChanged(this._selectedSheet);
        }
    };

    MetaEditorWidget.prototype._scrollSelectedTabIntoView = function () {
        //scroll selected sheet's tab into view
        var li = this.$ulSheetTab.find('li.active').first();
        var liPos = li.position();
        var visibleWidth = this.$sheetsContainer.width() - this.$divAddSheet.outerWidth(true);
        var visibleMin = -this._sheetScrollValue;
        var visibleMax = -this._sheetScrollValue + visibleWidth;
        if (liPos.left < visibleMin) {
            this._scrollSheetListBy(visibleMin - liPos.left);
        } else if (liPos.left + li.width() > visibleMax) {
            this._scrollSheetListBy(visibleMax - (liPos.left + li.width()));
        }
    };

    MetaEditorWidget.prototype._refreshTabScrollButtons = function () {
        var overflowRightBy = this.$ulSheetTab.width() - this.$sheetsContainer.width() + this.$divAddSheet.outerWidth(true) + this._sheetScrollValue;

        this.$btnScrollLeft.enabled(this._sheetScrollValue < 0);
        this.$btnScrollRight.enabled(overflowRightBy > 0);
    };

    MetaEditorWidget.prototype._onTabsSortStop = function () {
        var ul = this.$ulSheetTab,
            allLi = ul.find('li'),
            i,
            li,
            order = [];

        for (i = 0; i < allLi.length; i += 1) {
            li = $(allLi[i]);
            order.push(li.data(SHEET_ID));
        }

        if (order.length > 0) {
            this.onTabsSorted(order);
        }
    };

    MetaEditorWidget.prototype.onSheetDeleteClicked = function (sheetID) {
        this.logger.warning('onSheetDeleteClicked not implemented: "' + sheetID + '"');
    };

    MetaEditorWidget.prototype.onSheetAddClicked = function () {
        var sheetID = this.addSheet('New sheet', true);
        this.logger.warning('onSheetAddClicked not implemented: "' + sheetID + '"');
    };

    MetaEditorWidget.prototype.onSheetTitleChanged = function (sheetID, oldValue, newValue) {
        this.logger.warning('onSheetTitleChanged not implemented: ID: ' + sheetID + ' "' + oldValue + '" --> "' + newValue + '"');
    };

    MetaEditorWidget.prototype.onSelectedSheetChanged = function (sheetID) {
        this.logger.warning('onSelectedSheetChanged not implemented: "' + sheetID + '"');
    };

    MetaEditorWidget.prototype.onTabsSorted = function (newSheetIDOrder) {
        this.logger.warning('onTabsSorted not implemented: "' + newSheetIDOrder + '"');
    };

    return MetaEditorWidget;
});<|endoftext|>


<commit_before>goog.provide('owgis.ncwms.animation');

goog.require('ol.source.ImageStatic');
goog.require('ol.source.ImageWMS');
goog.require('goog.events');

owgis.ncwms.animation.animStatus = "none";

var currentFrame; // Current frame that is being displayed
var allFrames; // Will contain the 'dates' for each frame
var animSpeed = 200;
// Is the animation status it can be:
// 		none -> There is not animation or is being stopped
// 		loading -> The animation is being requested but not all of the frames have loaded
//		playing -> Animation is being played at current speed
//		pause   -> Animation paused

var animLayer;
var animSource;
var currUrl;
var animParams; //Parameters requested for the animation
var intervalHandler;// This is the handler of the 'interval' function
var loadedFrames = 0;//Indicates how many frames have been loaded.
var totalNumOfFrames = 0;//Total number of frames
var numberOfParallelRquests = 4;

var errorRetryNumber = 5; //How many times try to reload an image before considering a fail

/**
 * Modifies the visibility of different html elements involved on
 * the displaying of the animations.
 * @param status - the status of the animation
 * ['loading', 'playing', 'none','paused']
 */
function updateMenusDisplayVisibility(status){

    // ------- Visibility of top menus (general menus) -------
	if(netcdf){
		// When we are selecting dates.
		switch( status ){
            case "loading":
                $('#CalendarsAndStopContainer').hide("fade");
				$('#animControls a').hide();// Hidde the rest of the buttons
                $('#animControls').show("fade");//Show the stop button
				$('#stopAnimText').show("fade");
				$('#animControls [class*=stop]').parent().show("fade");
                $('#l-animation').show("fade");
                $('#minPal').disabled = true;
                $('#maxPal').disabled = true;
                $('#hideCalendarButtonParent').hide("fade");
                break;
            case "playing":
                $('#CalendarsAndStopContainer').hide("fade");
				$('#stopAnimText').hide();
				$('#animControls a').show("fade");// Show all the buttons
                $('#l-animation').hide("fade");
                $('#minPal').disabled = true;
                $('#maxPal').disabled = true;
                $('#elevationParent').hide("fade");
                $('#hideCalendarButtonParent').hide("fade");
                break;
            case "none":
            default:
                $("#palettesMenuParent").show();
                $("#lineToggle").show();
//                $("#downloadDataParent").hide();

                if(_mainlayer_zaxisCoord){
                    $('#elevationParent').show("fade");
                }else{
                    $('#elevationParent').hide();
                }
                if(_mainlayer_multipleDates){
                    $('#CalendarsAndStopContainer').show("fade");
                    $('#animControls').hide("fade");
                    $('#minPal').disabled = false;
                    $('#maxPal').disabled = false;
                    $('#hideCalendarButtonParent').show("fade");
                    $('#l-animation').hide("fade");
                }else{
                    $('#CalendarsAndStopContainer').hide("fade");
                }
                break;
		}
    }else{
        //Menus when the layer is not a netcdf
        $("#palettesMenuParent").hide();
        $("#lineToggle").hide();
        $("#downloadDataParent").show();
        $("#elevationParent").hide();
        $('#CalendarsAndStopContainer').hide();
    }

}

/**
 * Moves the animation to the first and last frame
 * @returns {undefined}
 */
function animFirstFrame(){ currentFrame = 0; }
function animLastFrame(){ currentFrame = totalNumOfFrames - 1; }
/**
 * Decreases the frame of the animation, if it is on the first frame
 * it goes to the last one
 * @returns {undefined}
 */
function animDecreaseFrame(){
	if(currentFrame > 0){
		currentFrame--;
	}else{
		currentFrame = totalNumOfFrames - 1;
	}
}
/**
 * Increases the frame of the animation, if it is on the last frame
 * it goes to the first one
 * @returns {undefined}
 */
function animIncreaseFrame(){
	if(currentFrame < (totalNumOfFrames - 1) ){
		currentFrame++;
	}else{
		currentFrame = 0;
	}
}
/**
 * Makes the animation 10% faster.
 * @returns {undefined}
 */
function animFaster(){
	animSpeed = animSpeed*.90;
	startAnimationLoop();
}
/**
 * Makes the animation 10% slower.
 * @returns {undefined}
 */
function animSlower(){
	animSpeed = animSpeed*1.10;
	startAnimationLoop();
}

/**
 * This function is used, to try to cancel image from loading. When
 * the user stops the animation or when the user updates the map before
 * all the images have been loaded
 * @returns {undefined}
 */
function stopImageFromLoading(){
	//cancel image downloads
	for(var i = 0; i < totalNumOfFrames; i++){
		eval("imageNumber"+i+".src ='';");
	}
}
/**
 * This function updates the status of the animation, it can be
 * "paused", "none" or "playing"
 * @param {type} newStatus
 * @returns {undefined}
 */
function updateAnimationStatus(newStatus){
	owgis.ncwms.animation.animStatus = newStatus;
	switch(owgis.ncwms.animation.animStatus){
		case "none"://When the animation has been stoped
			stopImageFromLoading();
			updateMenusDisplayVisibility(owgis.ncwms.animation.animStatus);

			clearLoopHandler();

			if(animLayer !== null){//If the layer already existed, we remove it
				map.removeLayer(animLayer);
			}

			updateTitleAndKmlLink();
			break;
		case "pause": break;
		case "playing": break;
	}

}
/**
 * This function analyses the selected dates by the user and creates all
 * the string dates corresponding for each one
 * @returns {undefined}
 */
function obtainSelectedDates(){
	// Obtains the selected dates
	if(getUserSelectedTimeFrame().indexOf("/") === -1){
		allFrames = getUserSelectedTimeFrame().split(",");
	}else{
		allFrames = new Array();
		totalNumOfFrames = 0;

		var startDate = Calendar.intToDate(calStart.selection.get());
		var endDate = Calendar.intToDate(calEnd.selection.get());

		var currYear, currMonth, currDay;
		currDate= startDate;

		while(currDate <= endDate){
			currYear = currDate.getUTCFullYear();
			currMonth = currDate.getUTCMonth();
			currDay = currDate.getUTCDate();
			//		allFrames.push(currYear+"-"+(currMonth+1)+"-"+currDay+"T00:00:00.000Z");
			allFrames.push(currYear+"-"+(currMonth+1)+"-"+currDay);
			currDate.setDate( currDate.getDate() + 1);
		}
	}

	totalNumOfFrames = allFrames.length;
}

/**
 * This function gets the selected dates from the user and starts
 * the ajax request to generate the animation of the NetCDF files.
 */
owgis.ncwms.animation.dispAnimation = function dispAnimation(){
	obtainSelectedDates();

	//Create the required global variables if they don't exist
	for(var i = 0; i < totalNumOfFrames; i++){
		try{// Hack to test if the variable already exists
			eval('imageNumber'+i);
		}
		catch(e){
			eval('window.imageNumber'+i+';');
			eval("imageNumber"+i+" = document.createElement('img');");
		}
	}

	animSource= new ol.source.ImageCanvas({
		canvasFunction: canvasAnimationFunction,
		projection: _map_projection
	});

	animLayer = new ol.layer.Image({
		source: animSource});

	currentFrame = 0; //Set to use the first frame
	map.addLayer(animLayer);

	owgis.ncwms.animation.animStatus = "loading";
	updateTitleAndKmlLink();
}

/**
 * The resolution of the animation depends on the size of the screen. Assuming
 * that if you have a larger screen then you will have a better internet
 * @returns {Number}
 */
function getResolutionRatio(){
	var selectedRes = $("[name=video_res]:checked").val();
	switch(selectedRes){
		case "high":
			return .55;
			break;
		case "normal":
			return .4;
			break;
		case "low":
			return .3;
			break;
	}
}
/**
 * This is the main function in charge of creating the animatinons.
 * It is called by Ol3 everytime there is a change in the map (zoom, pan, etc).
 * It receives the location and resolution of the map and it returns a canvas with
 * the desired display.
 * @param {type} extent
 * @param {type} resolution
 * @param {type} pixelRatio
 * @param {type} size
 * @param {type} projection
 * @returns {Element|canvasAnimationFunction.canvas}
 */
function canvasAnimationFunction(extent, resolution, pixelRatio, size, projection){

	console.log("----------- Canvas reload -----------");

	owgis.ncwms.animation.animStatus = "loading";
	loadedFrames = 0;// Reset the total number of images loaded
	$("#loadperc").text( Math.ceil(100*(loadedFrames/totalNumOfFrames)));
	updateMenusDisplayVisibility(owgis.ncwms.animation.animStatus);

    var canvasWidth = size[0];
    var canvasHeight = size[1];

    var canvas = document.getElementById('animationCanvas');
	canvas.width = canvasWidth;
	canvas.height = canvasHeight;

    ctx = canvas.getContext('2d');

	/*
	console.log("-----------------------");
	console.log("Extent:" + extent);
	console.log("Resolution: " + resolution);
	console.log("PixelRatio: " + pixelRatio);
	console.log("Size: " + size);
	 */

	originalResolution = resolution;
	originalExtent = extent;
	originalCenter = map.getView().getCenter();
	originalPixelsCenter = map.getPixelFromCoordinate(originalCenter);

	var bbox = extent;
	var animResolution = getResolutionRatio();
	var imgWidth = Math.ceil(canvasWidth*animResolution);
	var imgHeight = Math.ceil(canvasHeight*animResolution);

	//Check status of previous animation and deletes it if exists
	var mainLayer = owgis.layers.getMainLayer();
	var mainSource = mainLayer.getSource();
	var mainParams = mainSource.getParams();
	var layerName = mainParams.LAYERS;

	currUrl = mainSource.getUrls()[0];//Get url for

	animParams = {
		TIME: allFrames[0],
		LAYERS: layerName,
		BBOX: bbox.toString(),
		REQUEST: "GetMap",
		VERSION: "1.3.0",
		STYLES: lay_style+"/"+mappalette,
		FORMAT: "image/png",
		TRANSPARENT: "TRUE",
		CRS:"CRS:84",
		WIDTH: imgWidth,
		HEIGHT: imgHeight,
		NUMCOLORBANDS: 250,
		COLORSCALERANGE:  minPalVal + ',' + maxPalVal};

	if (layerDetails.zaxis !== undefined) {
		animParams.elevation =  layerDetails.zaxis.values[elev_glob_counter];
	}

	var imgSrc;

	currentFrame = 0;// Reset to first frame

	// This loops starts 'n' number of parallel requests for animation
	// images.
	for(i = 0; i < Math.min(numberOfParallelRquests,totalNumOfFrames); i++){
		animParams.TIME = allFrames[i];
		imgSrc = currUrl+"?"+owgis.utils.paramsToUrl(animParams);
		eval('imageNumber'+i+'.src = imgSrc;');
		eval("imageNumber"+i+".id = "+i+";");
		eval("imageNumber"+i+".errorCount = 0;");
		eval("imageNumber"+i+".addEventListener('load', imageHasBeenLoadedParallel);");
		eval("imageNumber"+i+".addEventListener('error', errorFunction);");
	}

	startAnimationLoop();

    return canvas;
}

/**
 * Log the error and try to load the image again
 * @param {type} e
 * @returns {undefined}
 */
function errorFunction(e){

	var currentImage = parseInt(e.target.id);
	var errorCount = parseInt(e.target.errorCount);

	if(errorCount > errorRetryNumber){
		alert("There has been a problem loading image with date: "+ allFrames[currentImage]
					+" please stop the animation and reload it");
	}else{
		console.log("Error loading image: "+currentImage);

		animParams.TIME = allFrames[currentImage];
		var imgSrc = currUrl+"?"+owgis.utils.paramsToUrl(animParams);

		eval('imageNumber'+currentImage+'.src = imgSrc;');
		eval("imageNumber"+currentImage+".errorCount = "+(errorCount+1)+";");
	}
}

function imageHasBeenLoadedParallel(e){
	e.target.removeEventListener('load', imageHasBeenLoadedParallel, false);

	if( owgis.ncwms.animation.animStatus === "loading"){
		var currentImage = parseInt(e.target.id);
		console.log('Loaded image:'+currentImage);

		//Being sure that we are in order, if not then we dont' do anything
		if( (loadedFrames < currentImage + numberOfParallelRquests) &&
				(loadedFrames > currentImage - numberOfParallelRquests) ){
			loadedFrames++;

			if(loadedFrames >= totalNumOfFrames ){
				owgis.ncwms.animation.animStatus = "playing";
				updateMenusDisplayVisibility(owgis.ncwms.animation.animStatus);
			}else{//then we still need to load more
				if( (currentImage + numberOfParallelRquests) < totalNumOfFrames ){
					var nextImage = currentImage + numberOfParallelRquests;
					animParams.TIME = allFrames[nextImage];

					var imgSrc = currUrl+"?"+owgis.utils.paramsToUrl(animParams);
					eval('imageNumber'+nextImage+'.src = imgSrc;');
					eval("imageNumber"+nextImage+".id = "+nextImage+";");
					eval("imageNumber"+nextImage+".addEventListener('load', imageHasBeenLoadedParallel);");
				}
			}

			$("#loadperc").text( Math.ceil(100*(loadedFrames/totalNumOfFrames)));
		}
	}
}

function clearLoopHandler(){
	if(typeof intervalHandler !== 'undefined'){
		clearInterval(intervalHandler);
	}
}

function startAnimationLoop(){
	clearLoopHandler();
	intervalHandler = setInterval(loopAnimation,animSpeed);
}

function loopAnimation(){
	var canvas = document.getElementById('animationCanvas');

	if(owgis.ncwms.animation.animStatus === "playing"){
		currentFrame = currentFrame < (totalNumOfFrames-1)? ++currentFrame: 0;
	}
	if(owgis.ncwms.animation.animStatus === "loading"){
		currentFrame = currentFrame < (loadedFrames)? ++currentFrame: 0;
	}

	//	console.log("Displaying Frame: "+ currentFrame);

	ctx.drawImage(eval('imageNumber'+currentFrame), 0, 0, canvas.width, canvas.height);
	$("#animDate").text(allFrames[currentFrame]);
	ctx.stroke();
	map.render();
}

owgis.ncwms.animation.initAnimationControls = function(){
	$('#animControls a').tooltip({ position: "bottom left", opacity: 0.7});
}
<commit_msg>Fixed parallel requesting of images on the animation<commit_after>goog.provide('owgis.ncwms.animation');

goog.require('ol.source.ImageStatic');
goog.require('ol.source.ImageWMS');
goog.require('goog.events');

owgis.ncwms.animation.animStatus = "none";

var currentFrame; // Current frame that is being displayed
var allFrames; // Will contain the 'dates' for each frame
var animSpeed = 200;
// Is the animation status it can be:
// 		none -> There is not animation or is being stopped
// 		loading -> The animation is being requested but not all of the frames have loaded
//		playing -> Animation is being played at current speed
//		pause   -> Animation paused

var animLayer;
var animSource;
var currUrl;
var animParams; //Parameters requested for the animation
var intervalHandler;// This is the handler of the 'interval' function
var loadedFrames = 0;//Indicates how many frames have been loaded.
var totalNumOfFrames = 0;//Total number of frames
var numberOfParallelRquests = 4;
//This animation is used to stop images requested for a 'different' animation.
var currentAnimation = 0;

var errorRetryNumber = 5; //How many times try to reload an image before considering a fail

/**
 * Modifies the visibility of different html elements involved on
 * the displaying of the animations.
 * @param status - the status of the animation
 * ['loading', 'playing', 'none','paused']
 */
function updateMenusDisplayVisibility(status){

    // ------- Visibility of top menus (general menus) -------
	if(netcdf){
		// When we are selecting dates.
		switch( status ){
            case "loading":
                $('#CalendarsAndStopContainer').hide("fade");
				$('#animControls a').hide();// Hidde the rest of the buttons
                $('#animControls').show("fade");//Show the stop button
				$('#stopAnimText').show("fade");
				$('#animControls [class*=stop]').parent().show("fade");
                $('#l-animation').show("fade");
                $('#minPal').disabled = true;
                $('#maxPal').disabled = true;
                $('#hideCalendarButtonParent').hide("fade");
                break;
            case "playing":
                $('#CalendarsAndStopContainer').hide("fade");
				$('#stopAnimText').hide();
				$('#animControls a').show("fade");// Show all the buttons
                $('#l-animation').hide("fade");
                $('#minPal').disabled = true;
                $('#maxPal').disabled = true;
                $('#elevationParent').hide("fade");
                $('#hideCalendarButtonParent').hide("fade");
                break;
            case "none":
            default:
                $("#palettesMenuParent").show();
                $("#lineToggle").show();
//                $("#downloadDataParent").hide();

                if(_mainlayer_zaxisCoord){
                    $('#elevationParent').show("fade");
                }else{
                    $('#elevationParent').hide();
                }
                if(_mainlayer_multipleDates){
                    $('#CalendarsAndStopContainer').show("fade");
                    $('#animControls').hide("fade");
                    $('#minPal').disabled = false;
                    $('#maxPal').disabled = false;
                    $('#hideCalendarButtonParent').show("fade");
                    $('#l-animation').hide("fade");
                }else{
                    $('#CalendarsAndStopContainer').hide("fade");
                }
                break;
		}
    }else{
        //Menus when the layer is not a netcdf
        $("#palettesMenuParent").hide();
        $("#lineToggle").hide();
        $("#downloadDataParent").show();
        $("#elevationParent").hide();
        $('#CalendarsAndStopContainer').hide();
    }

}

/**
 * Moves the animation to the first and last frame
 * @returns {undefined}
 */
function animFirstFrame(){ currentFrame = 0; }
function animLastFrame(){ currentFrame = totalNumOfFrames - 1; }
/**
 * Decreases the frame of the animation, if it is on the first frame
 * it goes to the last one
 * @returns {undefined}
 */
function animDecreaseFrame(){
	if(currentFrame > 0){
		currentFrame--;
	}else{
		currentFrame = totalNumOfFrames - 1;
	}
}
/**
 * Increases the frame of the animation, if it is on the last frame
 * it goes to the first one
 * @returns {undefined}
 */
function animIncreaseFrame(){
	if(currentFrame < (totalNumOfFrames - 1) ){
		currentFrame++;
	}else{
		currentFrame = 0;
	}
}
/**
 * Makes the animation 10% faster.
 * @returns {undefined}
 */
function animFaster(){
	animSpeed = animSpeed*.90;
	startAnimationLoop();
}
/**
 * Makes the animation 10% slower.
 * @returns {undefined}
 */
function animSlower(){
	animSpeed = animSpeed*1.10;
	startAnimationLoop();
}

/**
 * This function updates the status of the animation, it can be
 * "paused", "none" or "playing"
 * @param {type} newStatus
 * @returns {undefined}
 */
function updateAnimationStatus(newStatus){
	owgis.ncwms.animation.animStatus = newStatus;
	switch(owgis.ncwms.animation.animStatus){
		case "none"://When the animation has been stoped
			currentAnimation++;//It is used to stop any previous images
			updateMenusDisplayVisibility(owgis.ncwms.animation.animStatus);

			clearLoopHandler();

			if(animLayer !== null){//If the layer already existed, we remove it
				map.removeLayer(animLayer);
			}

			updateTitleAndKmlLink();
			break;
		case "pause": break;
		case "playing": break;
	}

}
/**
 * This function analyses the selected dates by the user and creates all
 * the string dates corresponding for each one
 * @returns {undefined}
 */
function obtainSelectedDates(){
	// Obtains the selected dates
	if(getUserSelectedTimeFrame().indexOf("/") === -1){
		allFrames = getUserSelectedTimeFrame().split(",");
	}else{
		allFrames = new Array();
		totalNumOfFrames = 0;

		var startDate = Calendar.intToDate(calStart.selection.get());
		var endDate = Calendar.intToDate(calEnd.selection.get());

		var currYear, currMonth, currDay;
		currDate= startDate;

		while(currDate <= endDate){
			currYear = currDate.getUTCFullYear();
			currMonth = currDate.getUTCMonth();
			currDay = currDate.getUTCDate();
			//		allFrames.push(currYear+"-"+(currMonth+1)+"-"+currDay+"T00:00:00.000Z");
			allFrames.push(currYear+"-"+(currMonth+1)+"-"+currDay);
			currDate.setDate( currDate.getDate() + 1);
		}
	}

	totalNumOfFrames = allFrames.length;
}

/**
 * This function gets the selected dates from the user and starts
 * the ajax request to generate the animation of the NetCDF files.
 */
owgis.ncwms.animation.dispAnimation = function dispAnimation(){
	obtainSelectedDates();

	//Create the required global variables if they don't exist
	console.log("TotalNumber of frames: "+ totalNumOfFrames);
	for(var i = 0; i < totalNumOfFrames; i++){
		try{// Hack to test if the variable already exists
			eval('imageNumber'+i);
		}
		catch(e){
			eval('window.imageNumber'+i+';');
			eval("imageNumber"+i+" = document.createElement('img');");
		}
	}

	animSource= new ol.source.ImageCanvas({
		canvasFunction: canvasAnimationFunction,
		projection: _map_projection
	});

	animLayer = new ol.layer.Image({
		source: animSource});

	currentFrame = 0; //Set to use the first frame
	map.addLayer(animLayer);

//	owgis.ncwms.animation.animStatus = "loading";
	updateTitleAndKmlLink();
}

/**
 * The resolution of the animation depends on the size of the screen. Assuming
 * that if you have a larger screen then you will have a better internet
 * @returns {Number}
 */
function getResolutionRatio(){
	var selectedRes = $("[name=video_res]:checked").val();
	switch(selectedRes){
		case "high":
			return .55;
			break;
		case "normal":
			return .4;
			break;
		case "low":
			return .3;
			break;
	}
}
/**
 * This is the main function in charge of creating the animatinons.
 * It is called by Ol3 everytime there is a change in the map (zoom, pan, etc).
 * It receives the location and resolution of the map and it returns a canvas with
 * the desired display.
 * @param {type} extent
 * @param {type} resolution
 * @param {type} pixelRatio
 * @param {type} size
 * @param {type} projection
 * @returns {Element|canvasAnimationFunction.canvas}
 */
function canvasAnimationFunction(extent, resolution, pixelRatio, size, projection){

	console.log("----------- Canvas reload -----------");

	currentAnimation++;//Increments the animation counter;

	owgis.ncwms.animation.animStatus = "loading";
	loadedFrames = 0;// Reset the total number of images loaded
	$("#loadperc").text( Math.ceil(100*(loadedFrames/totalNumOfFrames)));
	updateMenusDisplayVisibility(owgis.ncwms.animation.animStatus);

    var canvasWidth = size[0];
    var canvasHeight = size[1];

    var canvas = document.getElementById('animationCanvas');
	canvas.width = canvasWidth;
	canvas.height = canvasHeight;

    ctx = canvas.getContext('2d');

	/*
	console.log("-----------------------");
	console.log("Extent:" + extent);
	console.log("Resolution: " + resolution);
	console.log("PixelRatio: " + pixelRatio);
	console.log("Size: " + size);
	 */

	originalResolution = resolution;
	originalExtent = extent;
	originalCenter = map.getView().getCenter();
	originalPixelsCenter = map.getPixelFromCoordinate(originalCenter);

	var bbox = extent;
	var animResolution = getResolutionRatio();
	var imgWidth = Math.ceil(canvasWidth*animResolution);
	var imgHeight = Math.ceil(canvasHeight*animResolution);

	//Check status of previous animation and deletes it if exists
	var mainLayer = owgis.layers.getMainLayer();
	var mainSource = mainLayer.getSource();
	var mainParams = mainSource.getParams();
	var layerName = mainParams.LAYERS;

	currUrl = mainSource.getUrls()[0];//Get url for

	animParams = {
		TIME: allFrames[0],
		LAYERS: layerName,
		BBOX: bbox.toString(),
		REQUEST: "GetMap",
		VERSION: "1.3.0",
		STYLES: lay_style+"/"+mappalette,
		FORMAT: "image/png",
		TRANSPARENT: "TRUE",
		CRS:"CRS:84",
		WIDTH: imgWidth,
		HEIGHT: imgHeight,
		NUMCOLORBANDS: 250,
		COLORSCALERANGE:  minPalVal + ',' + maxPalVal};

	if (layerDetails.zaxis !== undefined) {
		animParams.elevation =  layerDetails.zaxis.values[elev_glob_counter];
	}

	var imgSrc;

	currentFrame = 0;// Reset to first frame

	// This loops starts 'n' number of parallel requests for animation
	// images.
	for(i = 0; i < Math.min(numberOfParallelRquests,totalNumOfFrames); i++){
		animParams.TIME = allFrames[i];
		imgSrc = currUrl+"?"+owgis.utils.paramsToUrl(animParams);
		eval('imageNumber'+i+'.src = imgSrc;');
		eval("imageNumber"+i+".id = "+i+";");
		eval("imageNumber"+i+".errorCount = 0;");
		eval("imageNumber"+i+".belongs = "+currentAnimation+";");//Attach an animation 'counter'
		eval("imageNumber"+i+".addEventListener('load', imageHasBeenLoadedParallel);");
		eval("imageNumber"+i+".addEventListener('error', errorFunction);");
	}

	startAnimationLoop();

    return canvas;
}

/**
 * Log the error and try to load the image again
 * @param {type} e
 * @returns {undefined}
 */
function errorFunction(e){

	var currentImage = parseInt(e.target.id);
	var errorCount = parseInt(e.target.errorCount);

	if(errorCount > errorRetryNumber){
		alert("There has been a problem loading image with date: "+ allFrames[currentImage]
					+" please stop the animation and reload it");
	}else{
		console.log("Error loading image: "+currentImage);

		animParams.TIME = allFrames[currentImage];
		var imgSrc = currUrl+"?"+owgis.utils.paramsToUrl(animParams);

		eval('imageNumber'+currentImage+'.src = imgSrc;');
		eval("imageNumber"+currentImage+".errorCount = "+(errorCount+1)+";");
	}
}

function imageHasBeenLoadedParallel(e){
	e.target.removeEventListener('load', imageHasBeenLoadedParallel, false);

	if( owgis.ncwms.animation.animStatus === "loading"){
		var currentImage = parseInt(e.target.id);
		var currentBelongs = parseInt(e.target.belongs);//Reads the image animation belonging
		console.log('Loaded image:'+currentImage+" belongs: "+currentBelongs);

		//Being sure that we are in order, if not then we dont' do anything
		if( currentBelongs === currentAnimation ){
			loadedFrames++;

			if(loadedFrames >= totalNumOfFrames ){
				owgis.ncwms.animation.animStatus = "playing";
				updateMenusDisplayVisibility(owgis.ncwms.animation.animStatus);
			}else{//then we still need to load more
				if( (currentImage + numberOfParallelRquests) < totalNumOfFrames ){
					var nextImage = currentImage + numberOfParallelRquests;
					animParams.TIME = allFrames[nextImage];

					var imgSrc = currUrl+"?"+owgis.utils.paramsToUrl(animParams);
					eval("imageNumber"+nextImage+".belongs = "+currentAnimation+";");//Attach an animation 'counter'
					eval('imageNumber'+nextImage+'.src = imgSrc;');
					eval("imageNumber"+nextImage+".id = "+nextImage+";");
					eval("imageNumber"+nextImage+".addEventListener('load', imageHasBeenLoadedParallel);");
				}
			}

			$("#loadperc").text( Math.ceil(100*(loadedFrames/totalNumOfFrames)));
		}
	}
}

function clearLoopHandler(){
	if(typeof intervalHandler !== 'undefined'){
		clearInterval(intervalHandler);
	}
}

function startAnimationLoop(){
	clearLoopHandler();
	intervalHandler = setInterval(loopAnimation,animSpeed);
}

function loopAnimation(){
	var canvas = document.getElementById('animationCanvas');

	if(owgis.ncwms.animation.animStatus === "playing"){
		currentFrame = currentFrame < (totalNumOfFrames-1)? ++currentFrame: 0;
	}
	if(owgis.ncwms.animation.animStatus === "loading"){
		currentFrame = currentFrame < (loadedFrames)? ++currentFrame: 0;
	}

	//	console.log("Displaying Frame: "+ currentFrame);

	ctx.drawImage(eval('imageNumber'+currentFrame), 0, 0, canvas.width, canvas.height);
	$("#animDate").text(allFrames[currentFrame]);
	ctx.stroke();
	map.render();
}

owgis.ncwms.animation.initAnimationControls = function(){
	$('#animControls a').tooltip({ position: "bottom left", opacity: 0.7});
}
<|endoftext|>


<commit_before>"use strict";

angular.module("es.logongas.ix3").provider("remoteServiceFactory", [function() {
        this.baseURL;
        this.setBaseURL = function(baseURL) {
            if (!baseURL) {
                throw Error("El argumento baseURL no puede estar vacío");
            }
            if (typeof (baseURL) !== "string") {
                throw Error("El argumento baseURL debe ser un String");
            }

            this.baseURL = baseURL;
        };

        /**
         * Esta es la clase RemoteService verdadera que genera el Factory
         * @param {String} entityName Nombre de la entidad
         * @param {String} baseURL La url en la que se encuentran los servicios.
         */
        function RemoteService(entityName, baseURL,$http,$q) {
            this.entityName = entityName;
            this.baseURL = baseURL;
            this.$http=$http;
            this.$q=$q;
        }

        RemoteService.prototype.create = function(expand, parent) {
            var deferred = this.$q.defer();

            var params = {};
            if (parent) {
                angular.extend(params, parent);
            }
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'GET',
                url: this.baseURL + '/' + this.entityName + "/$create",
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al crear la entidad los datos:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };
        RemoteService.prototype.get = function(id, expand) {
            var deferred = this.$q.defer();

            var params = {};
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'GET',
                url: this.baseURL + '/' + this.entityName + "/" + id,
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al obtener la entidad:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };
        RemoteService.prototype.insert = function(entity,  expand) {
            var deferred = this.$q.defer();

            var params = {};
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'POST',
                url: this.baseURL + '/' + this.entityName + "/",
                params: params,
                data:entity
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al insertar la entidad:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };
        RemoteService.prototype.update = function(id, entity, fnOK, fnError, expand) {
            var deferred = this.$q.defer();

            var params = {};
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'PUT',
                url: this.baseURL + '/' + this.entityName + "/" + id,
                params: params,
                data:entity
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al insertar la entidad:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };
        RemoteService.prototype.delete = function(id) {
            var deferred = this.$q.defer();

            var params = {};

            var config = {
                method: 'DELETE',
                url: this.baseURL + '/' + this.entityName + "/" + id,
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al borrar la entidad:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };
        RemoteService.prototype.search = function(filter, order, expand, pageNumber, pageSize) {
            var deferred = this.$q.defer();

            var params = {};
            if (filter) {
                angular.extend(params, filter);
            }
            if (order) {
                params.$orderby = "";
                for (var i = 0; i < order.length; i++) {
                    var simpleOrder = order[i];
                    if (params.$orderby !== "") {
                        params.$orderby = params.$orderby + ",";
                    }
                    params.$orderby = params.$orderby + simpleOrder.fieldName + " " + simpleOrder.orderDirection;
                }
            }

            if (expand) {
                params.$expand = expand;
            }
            if ((pageNumber >= 0) && (pageSize > 0)) {
                params.$pagenumber = pageNumber;
                params.$pagesize = pageSize;
            }

            var config = {
                method: 'GET',
                url: this.baseURL + '/' + this.entityName,
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al buscar los datos:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };

        RemoteService.prototype.getChild = function(id, child, expand) {
            var deferred = this.$q.defer();

            var params = {};
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'GET',
                url: this.baseURL + '/' + this.entityName + "/" + id + "/" + child,
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al obtener la entidad hija:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };

        RemoteService.prototype.metadata = function(expand) {
            var deferred = this.$q.defer();

            var params = {};
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'GET',
                url: this.baseURL + '/' + this.entityName + "/$metadata",
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al obtener los metadatos:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };

        this.$get = ['$http','$q',function($http,$q) {
                var baseURL=this.baseURL;
                return {
                    getRemoteService: function(entityName) {
                        var remoteService = new RemoteService(entityName,baseURL,$http,$q);
                        return remoteService;
                    }
                };

            }];

    }]);

<commit_msg>obtener la url del valor 'urlapi'  en vez de configurarlo como un método del provider. Ahora es un factory<commit_after>"use strict";

angular.module("es.logongas.ix3").factory("remoteServiceFactory", ['$http','$q','apiurl',function($http,$q,apiurl) {

        /**
         * Esta es la clase RemoteService verdadera que genera el Factory
         * @param {String} entityName Nombre de la entidad
         * @param {String} apiurl La url en la que se encuentran los servicios.
         */
        function RemoteService(entityName, apiurl, $http, $q) {
            this.entityName = entityName;
            this.apiurl = apiurl;
            this.$http = $http;
            this.$q = $q;
        }

        RemoteService.prototype.create = function(expand, parent) {
            var deferred = this.$q.defer();

            var params = {};
            if (parent) {
                angular.extend(params, parent);
            }
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'GET',
                url: this.apiurl + '/' + this.entityName + "/$create",
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al crear la entidad los datos:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };
        RemoteService.prototype.get = function(id, expand) {
            var deferred = this.$q.defer();

            var params = {};
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'GET',
                url: this.apiurl + '/' + this.entityName + "/" + id,
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al obtener la entidad:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };
        RemoteService.prototype.insert = function(entity, expand) {
            var deferred = this.$q.defer();

            var params = {};
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'POST',
                url: this.apiurl + '/' + this.entityName + "/",
                params: params,
                data: entity
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al insertar la entidad:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };
        RemoteService.prototype.update = function(id, entity, fnOK, fnError, expand) {
            var deferred = this.$q.defer();

            var params = {};
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'PUT',
                url: this.apiurl + '/' + this.entityName + "/" + id,
                params: params,
                data: entity
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al insertar la entidad:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };
        RemoteService.prototype.delete = function(id) {
            var deferred = this.$q.defer();

            var params = {};

            var config = {
                method: 'DELETE',
                url: this.apiurl + '/' + this.entityName + "/" + id,
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al borrar la entidad:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };
        RemoteService.prototype.search = function(filter, order, expand, pageNumber, pageSize) {
            var deferred = this.$q.defer();

            var params = {};
            if (filter) {
                angular.extend(params, filter);
            }
            if (order) {
                params.$orderby = "";
                for (var i = 0; i < order.length; i++) {
                    var simpleOrder = order[i];
                    if (params.$orderby !== "") {
                        params.$orderby = params.$orderby + ",";
                    }
                    params.$orderby = params.$orderby + simpleOrder.fieldName + " " + simpleOrder.orderDirection;
                }
            }

            if (expand) {
                params.$expand = expand;
            }
            if ((pageNumber >= 0) && (pageSize > 0)) {
                params.$pagenumber = pageNumber;
                params.$pagesize = pageSize;
            }

            var config = {
                method: 'GET',
                url: this.apiurl + '/' + this.entityName,
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al buscar los datos:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };

        RemoteService.prototype.getChild = function(id, child, expand) {
            var deferred = this.$q.defer();

            var params = {};
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'GET',
                url: this.apiurl + '/' + this.entityName + "/" + id + "/" + child,
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al obtener la entidad hija:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };

        RemoteService.prototype.metadata = function(expand) {
            var deferred = this.$q.defer();

            var params = {};
            if (expand) {
                params.$expand = expand;
            }

            var config = {
                method: 'GET',
                url: this.apiurl + '/' + this.entityName + "/$metadata",
                params: params
            };

            this.$http(config).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                if (status === 400) {
                    deferred.reject(data);
                } else {
                    throw new Error("Fallo al obtener los metadatos:" + status + "\n" + data);
                }
            });

            return deferred.promise;
        };

        return {
            getRemoteService: function(entityName) {
                var remoteService = new RemoteService(entityName, apiurl, $http, $q);
                return remoteService;
            }
        };

    }]);

<|endoftext|>