/**
 * Created by Benny on 12.10.2014.
 */
"use strict";

var TB = TB || {};
TB.GUI = {
    currentPage : { id: null },   // @todo new Page404
    fadeTimeout : null,

    init : function() {

        if ( window.Pace ) {
            // Hide Pace cover
            Pace.on("done", function(){
                setTimeout( function() {
                    $( "#pace-cover" ).hide();
                }, 250 );
            });

            $( '#pace-cover' ).after( tmpl( 'tpl_layout' ) );
        } else {
            $( 'body').prepend( tmpl( 'tpl_layout' ) );
        }

        // Off Canvas Menu
        $( '#sidenavtoggle').click( function() {
            $( this ).addClass( 'on' );
            $('#offcanvasmenu').offcanvas('toggle');
            if ( TB.Client.profile ) {
                $( '#offcanvasmenu span[data-id="username"]').first().html( TB.Client.profile.first_name + ' ' + TB.Client.profile.last_name );
                $( '#offcanvasmenu img[data-id="userpic"]').first().attr( 'src', TB.GUI.getProfilePicUrl() );
            }
            if ( TB.Client.profiles ) {
                $( '#offcanvasmenu span[data-id="offcanvas-num_profiles"]' ).html( TB.Client.profiles.length );
            }
        });

        TB.GUI.setTeamName();

        $( '#offcanvasmenu').on( 'hide.bs.offcanvas', function(e) {
            $( '#sidenavtoggle').removeClass( 'on' );
        });
        $( '#offcanvasmenu').find( 'li button').click( function() {
            var action = $( this).attr( 'data-action');
            $('#offcanvasmenu').offcanvas('toggle');
            switch( action ) {

                case 'settings':
                    TB.Controller.do( 'Settings', 'account' );
                break;

                case 'profiles':
                    TB.Controller.do( 'Profiles' );
                break;

                case 'about':
                    TB.Controller.do( 'Content', 'about' );
                break;

                case 'pricing':
                    TB.Controller.do( 'Content', 'pricing' );
                    break;

                case 'support':
                    TB.Controller.do( 'Content', 'support' );
                break;

                case 'help':
                    TB.Controller.do( 'Content', 'help' );
                break;

                case 'logout':
                    TB.Ext.Alert.modal({
                        title: 'Wirklich ausloggen?'
                    }, function() {
                        TB.Client.logout();
                        TB.Controller.do('Auth', 'login');
                    });
                break;
            }
        });

        // Hide browser information of mobiles
        if ( TB.Env.isNativeMobile() ) {
            $( 'body').attr( 'id', 'native' );
        }

        // Set default timezone
        moment && moment.tz && moment.tz.setDefault && moment.tz.setDefault( "Europe/Berlin" );

    },

    setTeamName : function() {
        if ( TB.Client.isLoggedIn() ) {
            var teamName = "";
            $( TB.Client.teams).each( function( i, v ) {
                if ( TB.Client.teams[i].id === TB.Client.profile.team_id ) {
                    teamName = TB.Client.teams[i].display_name;
                    return false;
                }
            });
            $( '#team-select>a' ).html( teamName );
        }
    },


    formatHugeNumber : function( n ) {
        var no = parseInt( n );

        if ( no > 1000 && no < 1000000 ) {
            no = (no/1000).toFixed( 1 ) + "k";
        } else if ( no > 1000000 ) {
            no = ( no / 1000000 ).toFiex( 2 ) + "m";
        }


        return no;
    },

    rgbToHex : function ( rgb ) {
        rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
        return (rgb && rgb.length === 4) ? "#" +
            ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
            ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
            ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : null;
    },

    hexToRgb : function( hex ) {
        // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function(m, r, g, b) {
            return r + r + g + g + b + b;
        });

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
                r: parseInt(result[1], 16),
                g: parseInt(result[2], 16),
                b: parseInt(result[3], 16)
            } : null;
    },

    getGradientHex : function( hex1, hex2, percentage ) {
        var color1 = this.hexToRgb( hex1 ),
            color2 = this.hexToRgb( hex2 ),
            p = percentage,
            w = p * 2 - 1,
            w1 = (w/1+1) / 2,
            w2 = 1 - w1,
            rgb,
            hex = null;
        if ( color1 && color2 ) {
            rgb = [ Math.round(color1.r * w1 + color2.r * w2),
                    Math.round(color1.g * w1 + color2.g * w2),
                    Math.round(color1.b * w1 + color2.b * w2) ];
            hex = this.rgbToHex( 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')' );
        }
        return hex ? hex : hex1;
    },

    removeTeamName : function() {
        $( '#team-select>a' ).html( "" );
    },

    playerName : function( playerEntity ) {
        if ( playerEntity && playerEntity.first_name && playerEntity.last_name ) {
            return playerEntity.first_name + ' ' + playerEntity.last_name;
        } else {
            return 'Unbekannt';
        }
    },

    getRole : function( role ) {
        var r = 'Buddy';
        switch ( role ) {
            case 'trainer':
                r = 'Coach';
            break;
            case 'cotrainer':
                r = 'Co-Coach';
            break;
            case 'fan':
                r = 'Fan';
            break;
        }
        return r;
    },

    getProfilePicUrl : function( profile ) {
        var picUrl = 'img/profile-pic-none-male.png',
            prfl = profile || TB.Client.profile;
        if ( prfl && prfl.pic_url ) {
            picUrl = prfl.pic_url.replace( 'http://', 'https://' );
        } else if ( prfl && 'female' == prfl.gender ) {
            picUrl = 'img/profile-pic-none-female.png';
        }
        return picUrl;
    },

    updateMainNavigation : function( ctrl ) {
        $( '#main_navigation').find( 'li.tab-current').removeClass( 'tab-current' );
        $( '#main_navigation').find( 'a[data-nav-id="' + ctrl.toLowerCase() + '"]').parent( 'li' ).addClass( 'tab-current' );
    },

    updateNewsBadge : function( numNews ) {

        +numNews;
        if( 'news' == TB.GUI.getActiveMainNavigationId() ) {
            //numNews = 0;
            if ( numNews > 0 ) {
                $( 'div[data-id="new-news-alert"]' ).removeClass( "hide" );
                if ( $( 'div[data-id="new-news-alert"]').length ) {
                    $("html, body").animate({ scrollTop: $(document).height() }, "slow");
                }
            } else {
                $( 'div[data-id="new-news-alert"]' ).addClass( "hide" );
            }
        }
        if ( 0 == numNews ) {
            $( '#main_navigation').find( '#news_badge').remove();
        } else {
            if ( numNews > 9 ) {
                numNews = '9+';
            }
            if ( $( '#main_navigation').find( '#news_badge').exists() ) {
                $( '#news_badge').html( numNews );
            } else {
                $( '#main_navigation' ).find( 'li:first a:first' ).append( '<span id="news_badge" class="badge badge-danger">' + numNews + '</span>' );
            }
        }
    },

    getActiveMainNavigationId : function() {
        return $('#main_navigation li.tab-current > a').attr("data-nav-id" );
    },

    show : function( page, params, scrollBottom ) {
        if ( null == page ) {
            // @todo Add 404 page
            this.currentPage = { id: null };
        } else {
            this.currentPage.onLeave && this.currentPage.onLeave();
            this.currentPage = page;
            this.currentPage.onEnter && this.currentPage.onEnter( params );
            if ( scrollBottom ) {
                $("html, body").animate({ scrollTop: $(document).height() }, "slow");
            } else {
                $("html, body").animate({ scrollTop: 0 }, "slow");
            }
            this.currentPage.$container.find( 'input[data-datetimepicker="true"]').datetimepicker( {
                lang:'de',
                    i18n:{
                    de:{
                        months:[
                            'Januar','Februar','März','April',
                            'Mai','Juni','Juli','August',
                            'September','Oktober','November','Dezember',
                        ],
                            dayOfWeek:[
                            "So.", "Mo", "Di", "Mi",
                            "Do", "Fr", "Sa.",
                        ]
                    }
                },
                format:'DD.MM.YYYY H:mm',
                formatTime:'H:mm',
                formatDate:'DD.MM.YYYY',
                step : 30,
                minDate: 0
            });
            this.currentPage.$container.find( 'input[data-datepicker="true"]').datetimepicker( {
                lang:'de',
                i18n:{
                    de:{
                        months:[
                            'Januar','Februar','März','April',
                            'Mai','Juni','Juli','August',
                            'September','Oktober','November','Dezember',
                        ],
                        dayOfWeek:[
                            "So.", "Mo", "Di", "Mi",
                            "Do", "Fr", "Sa.",
                        ]
                    }
                },
                format:'DD.MM.YYYY',
                timepicker : false
            });
        }
    },

    showLoader : function() {
        clearTimeout( this.fadeTimeout );
        $( '#page-loader').removeClass( 'page-fade-animation' );
        $( '#page-loader').css( 'opacity', '1' );
        $( '#page-loader' ).css( 'display', 'inline-block' );
        $( '#content').css( 'left', '5%' );
    },

    hideLoader : function() {
        $( '#page-loader').addClass( 'page-fade-animation' );
        $( '#page-loader').css( 'opacity', '0' );
        $( '#content').css( 'left', '0%' );

        this.fadeTimeout = setTimeout( function() {
            $( '#page-loader').css( 'display', 'none' );
            $( '#page-loader').css( 'opacity', '1' );
        }, 1000 );
    },

    initFormValidator : function() {
        $( '#main').on( 'blur', "form input", function() {
            TB.GUI.performInputValidation( $( this ) );
        });
    },

    performFormValidation : function( $form ) {
        var isValid = true;
        $form.find( 'input').each( function( i, v ) {
            if ( false == TB.GUI.performInputValidation( $( v )  ) ) {
                isValid = false;
            }
        });
        return isValid;
    },

    performInputValidation : function( $input ) {

        var validators = {
            'email': function ($input) {
                var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
                return re.test($input.val());
            },
            'required': function ($input) {
                if ( $input.attr( 'type' ) == "checkbox" ) {
                    return $input.prop( 'checked' );
                } else {
                    var minChars = $input.is( "[data-validate-minchars]" ) ? (parseInt( $input.attr( "data-validate-minchars" ), 10 )-1) : 0;
                    return ( minChars < $input.val().trim().length );
                }
            },
            'requiredNumber' : function( $input ) {
                var minVal = $input.is( "[data-minvalue]" ) ? parseInt( $input.attr( 'data-minvalue'), 10 ) : null,
                    currentVal = parseInt( $input.val(), 10 );
                if ( isNaN( currentVal ) ) {
                    return false;
                } else if ( null === minVal ){
                    return true;
                } else {
                    return ( minVal <= currentVal );
                }
            },
            'requiredDatetime' : function ($input) {
                var p = $input.val().split(/[: .]/), isValid = false, minTime, dt;
                dt = new Date( p[2], p[1]-1, p[0], p[3], p[4] );
                isValid = TB.Utils.isValidDate( dt );
                if ( isValid && $input.is( "[data-validate-mintime]" ) ) {
                    minTime = new Date( parseInt( $input.attr( "data-validate-mintime"), 10 ) );
                    isValid = ( dt.getTime() > minTime.getTime() );
                }
                return isValid;
            },
            'requiredDate' : function( $input ) {
                var p = $input.val().split(/[: .]/);
                return TB.Utils.isValidDate( new Date( p[2], p[1]-1, p[0] ) );
            },
            'identical' : function( $input ) {
                var $identicalInput = $( '#' + $input.attr( 'data-identical-field-id' ) );
                return ( $identicalInput.exists() && $input.val() == $identicalInput.val() );
            }
        },
        isValid;

        // If validator isset and valid
        if ( $input.is( "[data-validate]" ) && validators[ $input.attr( "data-validate" ) ] ) {

            // Validate
            if ( validators[ $input.attr( "data-validate" ) ]( $input ) ) {
                // Success
                if ( $input.attr( 'type' ) == "checkbox" ) {
                    // Do nothing
                } else {

                    // Normal form group input field
                    if ( $input.parent( 'div').hasClass( 'form-group') ) {

                        $input.parent('div').removeClass('has-error').addClass('has-success').addClass('has-feedback');
                        if ($input.next('span.glyphicon ').exists()) {
                            $input.next('span.glyphicon ').removeClass('glyphicon-remove').addClass('glyphicon-ok');
                        } else {
                            $('<span class="glyphicon glyphicon-ok form-control-feedback"></span>').insertAfter($input);
                        }
                        if ($input.nextAll('small.help-block').exists()) {
                            $input.nextAll('small.help-block').remove();
                        }
                    } else if ( $input.parent( 'div').hasClass( 'input-group') ) {
                        // Input field with addon
                        $input.parent('div.input-group').removeClass('has-error').addClass('has-success');
                        $input.parent('div.input-group').parent('div.form-group').removeClass('has-error').addClass('has-success');
                        if ( $input.parent( 'div.input-group' ).nextAll('small.help-block').exists() ) {
                            $input.parent( 'div.input-group' ).nextAll('small.help-block').remove();
                        }

                    }
                }

                isValid = true;
            } else {
                // Error
                if ( $input.attr( 'type' ) == "checkbox" ) {
                    TB.Ext.Notification.show( $input.attr( 'data-validate-errormsg' ), TB.Ext.Notification.TYPE_DANGER );
                } else {

                    // Normal form group input field
                    if ( $input.parent( 'div').hasClass( 'form-group') ) {
                        $input.parent('div.form-group').removeClass('has-success').addClass('has-error').addClass('has-feedback');
                        if ($input.next('span.glyphicon ').exists()) {
                            $input.next('span.glyphicon ').removeClass('glyphicon-ok').addClass('glyphicon-remove');
                        } else {
                            $('<span class="glyphicon glyphicon-remove form-control-feedback"></span>').insertAfter($input);
                        }
                        if ($input.is("[data-validate-errormsg]") && !$input.nextAll('small.help-block').exists()) {
                            $('<small class="help-block">' + $input.attr('data-validate-errormsg') + '</small>').insertAfter($input.next('span.glyphicon '));
                        }
                    } else if ( $input.parent( 'div').hasClass( 'input-group') ) {
                        // Input Fields with addons
                        $input.parent('div.input-group').removeClass('has-success').addClass('has-error');
                        $input.parent('div.input-group').parent('div.form-group').removeClass('has-success').addClass('has-error');
                        if ($input.is("[data-validate-errormsg]") && !$input.parent( 'div.input-group' ).nextAll('small.help-block').exists()) {
                            $('<small class="help-block">' + $input.attr('data-validate-errormsg') + '</small>').insertAfter($input.parent( 'div.input-group' )) ;
                        }
                    }
                }

                isValid = false;
            }
        } else {
            isValid = true;
        }

        return isValid;
    },

    isTrainer : function( profile ) {
        var profileToCheck = profile || TB.Client.profile;
        return ( profileToCheck &&
                 profileToCheck.role == 'trainer' );
    },

    isCoTrainer : function( profile ) {
        var profileToCheck = profile || TB.Client.profile;
        return ( profileToCheck &&
        profileToCheck.role == 'cotrainer' );
    },

    isPlayer : function( profile ) {
        var profileToCheck = profile || TB.Client.profile;
        return ( profileToCheck &&
        profileToCheck.role == 'player' );
    },

    isFan : function( profile ) {
        var profileToCheck = profile || TB.Client.profile;
        return ( profileToCheck &&
        profileToCheck.role == 'fan' );
    },

    isOwnProfile : function( profile ) {
        return ( TB.Client.profile.id == profile.id );
    },

    getPhoneNo : function( profile ) {
        var pn = '---';

        if ( profile.mobile ) {
            pn = profile.mobile;
        } else if ( profile.phone ) {
            pn = profile.phone;
        }

        return pn;
    },

    getProfileStatusHtml : function ( status, addCssClass ) {
        var cssClass, statusTxt,
            addCss = addCssClass || '';
        switch( status ) {
            case 'fit':
                statusTxt = 'fit';
                cssClass = 'success';
                break;

            case 'injured':
                statusTxt = 'verletzt';
                cssClass = 'warning';
                break;

            case 'barred':
                statusTxt = 'gesperrt';
                cssClass = 'danger';
                break;

            case 'inactive':
                statusTxt = 'inaktiv';
                cssClass = 'default';
                break;
        }

        return '<span class="label label-' + cssClass + ' ' + addCss + '">' + statusTxt + '</span>';
    },

    getValue : function( prop, defValue ) {
        var dv = defValue || '&nbsp;';
        return ( prop && $.trim( prop ) != '' ) ? prop : dv;
    },
    
    showModal : function( headline, content, onConfirm, confirmTxt, onClose, closeTxt ) {
        var h = headline || "", c = content || "", onCfrm = onConfirm, onCls = onClose,
            cfrmTxt = confirmTxt || 'Bestätigen', clsTxt = closeTxt || 'Schließen',
            $modal = $( '#tbmodal');
        
        if ( !$modal.length ) return;
        
        $modal.find( '#gridSystemModalLabel' ).html( h );
        $modal.find( '#modal-content' ).html( c );
        if ( !onCfrm ) {
            $modal.find( '#modal-btn-confirm' ).hide();
        } else {
            $modal.find( '#modal-btn-confirm' ).html( cfrmTxt ).show().click( function() {
                onCfrm && onCfrm();
            });
        }
        if ( clsTxt ) {
            $modal.find( '#modal-btn-close' ).html( clsTxt ).click( function() {
                onCls && onCls();
            });
        }

        $modal.modal( 'show' );
        
    }
};