/**
 * use log() instead of console.log()
 */

window.console&&console.log||function(){for(var b=function(){},c="assert clear count debug dir dirxml error exception group groupCollapsed groupEnd info log markTimeline profile profileEnd markTimeline table time timeEnd timeStamp trace warn".split(" "),a=c.length,d=window.console={};a--;)d[c[a]]=b}();
window.log=function(){log.history=log.history||[];log.history.push(arguments);if(this.console){var b=arguments;b.callee=b.callee.caller;b=[].slice.call(b);"object"===typeof console.log?log.apply.call(console.log,console,b):console.log.apply(console,b)}};

;(function($, window, document, undefined) {

    var pluginName = "dimCalc",
        defaults = {
            localName: "js-dim-calc"
        };

    // The actual plugin constructor
    function DimCalc(element, options) {
        this.element = element;
        this.$form = $(this.element);
        this.$resultField = this.$form.find('.form-block--calc__result-row_finalr');
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend(DimCalc.prototype, {
        init: function() {
            this.$form.addClass( this.settings.localName );
            this.canCalculate = true;
            this.bindEvents();
        },
        getUserData: function() {
            this.pack = {};
            this.pack.width = Number( this.$form.find('input[name="width"]').val() );
            this.pack.height = Number( this.$form.find('input[name="height"]').val() );
            this.pack.long = Number( this.$form.find('input[name="long"]').val() );
        },
        round: function(number, X) {
            var X = (!X ? 2 : X);
            return Math.round(number * Math.pow(10, X)) / Math.pow(10, X);
        },
        appendError: function( msg ) {
            this.canCalculate = false;
            this.$resultField.html( msg ).addClass( 'js-error' );
        },
        checkErrors: function() {
            this.canCalculate = true;
            this.$resultField.removeClass( 'js-error' );

            if ( !this.pack.height || isNaN(this.pack.height) ) {
                this.appendError( 'Nie podano wysokości paczki');
                return false;
            }
            if ( !this.pack.width || isNaN(this.pack.width) ) {
                this.appendError( 'Nie podano szerokości paczki' );
                return false;
            }
            if ( !this.pack.long || isNaN(this.pack.long) ) {
                this.appendError( 'Nie podano długości paczki');
                return false;
            }
        },
        getPackDim: function() {
            this.$resultField.html( this.round((( this.pack.width * this.pack.height * this.pack.long) / 6000), 2 ) + ' kg');
        },
        calculateDim: function() {
            this.getUserData();
            this.checkErrors();
            if ( this.canCalculate ) {
                this.getPackDim();
            }
        },
        bindEvents: function() {
            var _this = this;
            this.$form.on('submit', function() {
                _this.calculateDim();
                return false;
            });
        }
    });

    $.fn[pluginName] = function(options) {
        this.each(function() {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new DimCalc(this, options));
            }
        });

        return this;
    };
})(jQuery, window, document);

function popUpDpd(chosen){
    var $this = chosen,
        $h = $('body').height(),
        $w = $('body').width(),
        $wp = $('.popup-content-container').width(),
        _wh = $(window).height(),
        _wwi = window.innerWidth,
        _wwo = window.outerWidth,
        marginesPrawy = ((_wwi-$w)/2+(_wwo-_wwi)/2),
        marginesLewy = (_wwi-$wp)/2,
        _tooltip = $('.'+$($this).attr('id')),
        $con = $(_tooltip).find('.popup-content-container');

    $(_tooltip).fadeIn(500).css('height',$h+5+'px');
    $($con).css('margin-top',( _wh - $($con).height() ) /2);
    $('body').css('overflow','hidden').css('margin-right',marginesPrawy+'px');
};

function validation() {
    $('form').find('.form-group').addClass('js-error').find('input, select').one('change', function( ) {
        $(this).parents('.form-group').removeClass('js-error');
    });
    $('.validation-info').show();
}

function setEqHeight($obj, maxHeightEm, maxHeightSpan) {
    $obj.find('em').css('height',maxHeightEm).end().find('.elips').css('height',maxHeightSpan);
}

$(function() {

    /*
    * Color plates resize by Row
    */
    $(window).resize(function() {
        var currentRowStart = 0;
        var topPostion = 0;
        var maxHeightEm = 0;
        var maxHeightSpan = 0;
        var row = 0;
        var $panels = $('.color-plate');
        var ile = $panels.length;

        $panels.attr('data-row','null').find('em').css('height', 'auto').end().find('.elips').css('height','auto');

        $panels.each(function(i) {
            var $el = $(this);
            var heightEm = $el.find('em').height();
            var heightSpan = $el.find('.elips').height();

            currentRowStart = $el.position().top;

            if (currentRowStart != topPostion) {
                if(row > 0) {
                    setEqHeight($el.prevAll('[data-row="' + row + '"]'),maxHeightEm,maxHeightSpan);
                }
                currentRowStart = $el.position().top;
                topPostion = currentRowStart;
                maxHeightEm = 0;
                maxHeightSpan = 0;
                row++;
            }

            maxHeightEm = (heightEm > maxHeightEm) ? heightEm : maxHeightEm;
            maxHeightSpan = (heightSpan > maxHeightSpan) ? heightSpan : maxHeightSpan;

            $el.attr('data-row',row);

            if(i+1 === ile) {
                setEqHeight($el.prevAll('[data-row="' + row + '"]').andSelf(),maxHeightEm,maxHeightSpan);
            }

        });
    }).triggerHandler('resize');

    /**
     * Build resonsive navigation
     */
    // var nav = responsiveNav(".nav-collapse");

    /*
    * Closing popup by click in overly
    */
    $('.popup').on('click',function (e){
        var w = $('.header-wrapper__logo-search-wrapper').width();
        var cont = $('.popup-content-container');
        var aaa = $('.popup-content-container').children();
        if ( !cont.is(e.target) && !aaa.is(e.target) ){
            $('.popup-content-container').parent().fadeOut(500);//RESPONSIVE .css('width',w-59).css('margin-left','auto').css('margin-right','auto')
            $('body').css('overflow','auto').css('margin-right','auto');
        }
    });
    // Closing popup by click in close button
    $('.close-popup').on('click',function(){
            $('.popup').fadeOut(500);
            $('body').css('overflow','auto').css('margin-right','auto');
    });
    // Carouusel configuration
    $('.owl-carousel').owlCarousel({
        loop:true,
        responsiveClass:true,
        lazyLoad:true,
        slideBy: 1,
        items:1,
        dots:true,
        autoplay:true,
        smartSpeed:450,
        autoplayHoverPause:true,
        fluidSpeed:300,
        responsiveRefreshRate:100
    });
    // Custom input decoration
    $('input').iCheck({
        checkboxClass: 'icheckbox_square-grey',
        radioClass: 'iradio_square-grey',
        increaseArea: '20%'
    });
    /*
    * START - For QA
    */
    var currentURL = window.location.search.substring(1).split('=')[1];
    if(currentURL == 'open'){
        popUpDpd('#popup-1');
    }
    else if(currentURL == 'error'){
        validation();
    }
    /*
    * END - For QA
    */
    // Input Focus and blur action
    $('input[type="text"]').on('focus', function() {
        if (!$(this).data('defaultText')) $(this).data('defaultText', $(this).val());
        if ($(this).val()==$(this).data('defaultText')) $(this).val('');
    });
    $('input[type="text"]').on('blur', function() {
        if ($(this).val()=='') $(this).val($(this).data('defaultText'));
    });

    $('#form-dim-calc').dimCalc();

    $( '.menu-bar li' ).eq( $('header').data('page') - 1 ).addClass('selected');

    var $tabs = $('.tabs');
    $tabs.each(function() {
        var $localTabs = $(this);
        $localTabs.on('click', '.tab', function() {
            var $this = $(this),
                $tab = $this.attr('data-tab')-1;
                _selected = 'tab--selected'
            $localTabs.find( '.tab' ).removeClass(_selected);
            $this.addClass(_selected);
            $localTabs.find('.tabs__content').hide().eq($tab).show();
            return false;
        });
    });

    $('.left-split__menu li a').on('click',function( event ) {
        var $this = $(this);
        var $ul = $this.parent().find( 'ul' );
        if ( $ul.length ) {
            $ul.first().stop(true, true).animate({
                height:'toggle'
            });
            $this.toggleClass( 'selected-left-split' );
            if (!$this.hasClass( 'selected-left-split' )) {
                $ul.hide().find( 'a' ).removeClass( 'selected-left-split');
            }
            return false;
        }
    });
    $('.accordian h3').click(function(){
        var $this = $(this);
        var $akordeon = $('.accordian');
        $akordeon.find('h3').removeClass('open');
        $('.accordian ul ul').slideUp();
        if(!$(this).next().is(':visible'))
        {
            $(this).next().slideDown();
            $this.addClass('open');
        }
    });

    $('.fancybox').fancybox({
        padding: 0,
        autoPlay: false,
        wrapCSS: 'fancybox',
        helpers: {
            title : {
                position: 'top',
                type : 'inside' // 'float', 'inside', 'outside' or 'over'
            }
        }
    });

    // $('select').selectForm({
    //     additionalWidth: 0
    // });
});
