// window.fbAsyncInit = function() {
//     FB.init({appId: '103550023046716', status: true, cookie: true, xfbml: true});
// };

/* URL ROUTER */
var Router = function (route,params) {
    //parametre
    if (typeof(params) == 'object') {
        var p = '';
        $.each(params,function (name,value) {
            if (p != '') {
                p += '&';
            }
            p += escape(name)+'='+escape(value);
        });
        return Router(route)+'?'+p;
    }
    else {
        return '/' + route;
    }
};
Router.route = function (route,params) {
    var url = Router(route,params);
    location.href = url;
}

/* Plugin na input hint */
jQuery.fn.inputHint = function () {
    this.each(function () {
        var self = $(this);
        if (self.is('input[type=text]')) {
            jQuery.inputHintShow(self);
            self.focus(function () {
                jQuery.inputHintHide(this);
            }).blur(function () {
                jQuery.inputHintShow(this);
            }).closest('form').submit(function () {
                jQuery.inputHintHide(self);
                return true;
            });
        }
    });
    return this;
};
jQuery.inputHintShow = function (inpt) {
    inpt = jQuery(inpt);
    if (inpt.val() == inpt.attr('title') || inpt.val() == '') {
        inpt.addClass('hint').val(inpt.attr('title'));
    }
}
jQuery.inputHintHide = function (inpt) {
    inpt = jQuery(inpt);
    inpt.removeClass('hint');
    if (inpt.val() == inpt.attr('title')) {
        inpt.val('');
    }
}

//sila hesla
jQuery.passwordStrength = {
    calculate: function (H) {
        var D=(H.length);
        if(D>5){
            D=5;
        }
        var F=H.replace(/[0-9]/g,"");
        var G=(H.length-F.length);
        if(G>3){G=3}
        var A=H.replace(/\W/g,"");
        var C=(H.length-A.length);
        if(C>3){C=3}
        var B=H.replace(/[A-Z]/g,"");
        var I=(H.length-B.length);
        if(I>3){I=3}
        var E=((D*10)-20)+(G*10)+(C*15)+(I*10);
        if(E<0){E=0}
        if(E>100){E=100}
        return E;
    }
};
jQuery.fn.passwordStrength = function(params) {
    var p = $.extend({
        bar: null,
        pcn: null
    },params);
    //vytvorime elementy na zobrazenie progresu
    this.keyup(function () {
        var strength = jQuery.passwordStrength.calculate(jQuery(this).val());
        if (p.bar) {
            jQuery(p.bar).css('width',strength + '%');
        }
        if (p.pcn) {
            jQuery(p.pcn).text(strength + '%');
        }
    });
    return this;
};

//plugin na zebra tabulky a highlight tabulky
jQuery.fn.zebraTable = function () {
    this.each(function () {
        var self = $(this);
        if (self.is('table')) {
            $('tbody tr:even',self).removeClass('even').addClass('odd');
            $('tbody tr:odd',self).removeClass('odd').addClass('even');
        }
    });
    return this;
};
jQuery.fn.highlightTable = function () {
    this.each(function () {
        var self = $(this);
        if (self.is('table')) {
            $('tbody tr',self).unbind('mouseover.highlight').bind('mouseover.highlight',function () {
                $('>td',this).addClass('highlight');
            });
            $('tbody tr',self).unbind('mouseout.highlight').bind('mouseout.highlight',function () {
                $('>td',this).removeClass('highlight');
            });
        }
    });
    return this;
};

//plugin na cookies
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/* Plugin na formulare */
jQuery.fn.disableForm = function() {
    this.each(function () {
        var t = $(this);
        if (t.is('form')) {
            t.find('input,select,textarea,button').prop('disabled',true);
        } else if (t.is('input,select,textarea,button')) {
            t.prop('disabled',true);
        }
    });
    return this;
};
jQuery.fn.enableForm = function() {
    this.each(function () {
        var t = $(this);
        if (t.is('form')) {
            t.find('input,select,textarea,button').removeProp('disabled');
        } else if (t.is('input,select,textarea,button')) {
            t.removeProp('disabled');
        }
    });
    return this;
};

/* Produktovy karusel */
jQuery.fn.productCarousel = function (userParams) {
    var params = $.extend({
        itemMargin: 0,
        animationDuration: 750,
        moveBy: 4
    }, userParams);
    this.each(function () {
        var $panel = $(this);
        var container = $panel.find('div.product-carousel');
        var content = $panel.find('div.product-carousel-content');
        var items = $panel.find('div.product-carousel-item');
        if (items.length) {
            var itemw = items.eq(0).outerWidth() + params.itemMargin; //+margin
            var itemh = items.eq(0).outerHeight();
            items.each(function () {
                var h = $(this).outerHeight();
                if (h > itemh) {
                    itemh = h;
                }
            });
            var containerw = container.width();
            var contentw = items.length * itemw;
            //o kolko sa ma animacia posuvat
            var posun = itemw * params.moveBy;
            //nastavime vysku kontaineru (kazdy item ma rovnaku sirku)
            container.height(itemh);
            content.width(contentw).height(itemh).css({
                position: 'absolute',
                top: '0px',
                left: '0px'
            });
            //nastavime triggre
            //zapocitame aj paddingy
            contentw -= params.itemMargin;
            $panel.find('.arrow-right').click(function () {
                var curleft = parseInt(content.css('left'));
                if (Math.abs(curleft) + containerw < contentw) {
                    content.animate({
                        left: Math.max(curleft - posun, -contentw + containerw) + 'px'
                    },{
                        duration: params.animationDuration
                    });
                }
                return false;
            });
            $panel.find('.arrow-left').click(function () {
                var curleft = parseInt(content.css('left'));
                if (curleft < 0) {
                    content.animate({
                        left: Math.min(curleft + posun, 0) + 'px'
                    },{
                        duration: params.animationDuration
                    });
                }
                return false;
            });
        }
    });
    return this;
};

/* Produktovy automaticky karusel */
jQuery.fn.productAutoCarousel = function (userParams) {
    var params = $.extend({
        itemMargin: 0,
        animationDuration: 500,
        moveBy: 1,
        stopTimeout: 5000
    }, userParams);
    this.each(function () {
        var $panel = $(this);
        var container = $panel.find('div.product-carousel');
        var content = $panel.find('div.product-carousel-content');
        var items = $panel.find('div.product-carousel-item');
        if (items.length) {
            var itemw = items.eq(0).outerWidth() + params.itemMargin; //+margin
            var itemh = items.eq(0).outerHeight();
            items.each(function () {
                var h = $(this).outerHeight();
                if (h > itemh) {
                    itemh = h;
                }
            });
            var containerw = container.width();
            var contentw = items.length * itemw;
            //o kolko sa ma animacia posuvat
            var posun = itemw * params.moveBy;
            //nastavime vysku kontaineru (kazdy item ma rovnaku sirku)
            container.height(itemh);
            content.width(contentw).height(itemh).css({
                position: 'absolute',
                top: '0px',
                left: '0px'
            });
            //zapocitame aj paddingy
            contentw -= params.itemMargin;
            //spustime automaticky posun
            function productAutoCarouselMove() {
                var curleft = parseInt(content.css('left'));
                if (Math.abs(curleft) + containerw < contentw) {
                    content.animate({
                        left: Math.max(curleft - posun, -contentw + containerw) + 'px'
                    },{
                        duration: params.animationDuration,
                        complete: function () {
                            var item1 = $panel.find('div.product-carousel-item:eq(0)');
                            item1.appendTo(item1.parent());
                            content.css('left', 0);
                            window.setTimeout(productAutoCarouselMove, params.stopTimeout);
                        }
                    });
                }
            }
            window.setTimeout(productAutoCarouselMove, params.stopTimeout);
        }
    });
    return this;
};

$(function() {
    //AJAX ERROR
    // $(document).ajaxError(function (request,settings,e) {
    //     alert('Error requesting URL: '+e.url);
    // });
	//hinty vo formularoch
	$('input.hint').inputHint();
	//vypnut autocomplete vo formularoch
	$('input.autocompleteoff').attr('autocomplete','off');
	//zebra tabulky + highlight
    $('table.zebra').zebraTable();
    $('table.highlight').highlightTable();
    
    var countdown = $('#countdown');
    var timeleft = countdown.data('time');
    var digits = $('#countdown-h, #countdown-m, #countdown-s');
    function displayCountdown(timeleft) {
        if (timeleft < 0) {
            timeleft = 0;
            digits.text(0);
            return;
        }
        var parsetime = {
            h: 0,
            m: 0,
            s: 0
        };
        parsetime.h = Math.floor(timeleft / 3600);
        parsetime.m = Math.floor((timeleft - (parsetime.h * 3600)) / 60);
        parsetime.s = timeleft - (parsetime.h * 3600) - (parsetime.m * 60);
        digits.eq(0).text(parsetime.h);
        digits.eq(1).text(parsetime.m);
        digits.eq(2).text(parsetime.s);
        //rekurzia
        window.setTimeout(function () {
            timeleft -= 1;
            displayCountdown(timeleft);
        }, 1000);
    }
    displayCountdown(timeleft);
    
    //hlavne menu - floatpanely s kategoriami
    $('#categorytabs a').click(function () {
        var floatpanel = $('#category-floatpanel-' + $(this).data('category'));
        var li = $(this).closest('li');
        //skryt floatpanely a odvyraznit zalozky
        $('#topmenu-panel .category-floatpanel').not(floatpanel).hide();
        li.siblings().not(li).removeClass('active');
        //zobrazit prislusny panel
        if (floatpanel.length) {
            var floatpanelContent = floatpanel.find('div.category-floatpanel-content');
            if (floatpanel.is(':visible')) {
                floatpanelContent.slideUp('fast', function () {
                    floatpanel.hide();
                    li.removeClass('active');
                });
            } else {
                floatpanelContent.hide();
                li.addClass('active');
                floatpanel.show();
                floatpanelContent.slideDown('fast');
                //nastavime akciu na zrusenie floatpanelu
                $('body').bind('click.hidefloatpanel', function (event) {
                    var target = $(event.target);
                    var isFloatpanelClicked = (target == floatpanel) || (target.closest(floatpanel).length ? true : false);
                    if (!isFloatpanelClicked) {
                        floatpanelContent.slideUp('fast', function () {
                            floatpanel.hide();
                            li.removeClass('active');
                        });
                        $('body').unbind('click.hidefloatpanel');
                    }
                });
            }
            return false;
        }
        return true;
    });
    //hlavne menu - podkategorie - druha uroven
    $('#topmenu-panel ul.subpanels-list a').click(function () {
        var subpanel = $('#subpanel-items-' + $(this).data('category'));
        var li = $(this).closest('li');
        var floatpanel = $(this).closest('div.category-floatpanel-content');
        //skryt subpanely a odvyraznit zalozky
        floatpanel.find('div.subpanel-items').hide();
        li.siblings().not(li).removeClass('active');
        if (subpanel.length) {
            if (subpanel.is(':visible')) {
                subpanel.slideUp('fast', function () {
                    li.removeClass('active');
                });
            } else {
                subpanel.slideDown('slow');
                li.addClass('active');
            }
            return false;
        }
        return true;
    });
    
    //pridavanie do kosika
    if (false) {
        $('form.addToCart').submit(function (event) {
            var f = $(this);
            //vycistime obsah
            $('#cartUpdaterDynamic').empty();
            //progress
            var p = $('#cartUpdater-progress');
            p.show();
            //zobrazime panel
            var cup = $('#cartUpdaterPanel');
            //zascrolujeme na vrch
            $('html,body').animate({
                scrollTop: 0
            }, {
                duration: 500
            });
            //animacia panelu
            //panel je zapoziciovany k #topcart elementu
            var topcart = $('#topcart');
            var topcartPos = $('#topcart').offset();
            cup.css('left', topcartPos.left + topcart.outerWidth() - cup.width());
            cup.css('top', topcartPos.top + topcart.outerHeight() + 5);
            cup.slideDown();
            //ajax request na pridanie do kosika
            $.ajax({
                url: f.attr('action'),
                type: 'POST',
                data: f.serialize(),
                dataType: 'json',
                success: function (a) {
                    $('#cartInfoItemsCount').text(a.itemsCount);
                    $('#cartInfoTpriceAmount').text(a.totalPrice);
                    $('#cartUpdaterDynamic').html(a.cartUpdaterHtml);
                    $('#topcart div.topcart').html(a.cartInfoHtml);
                    p.hide();
                    window.setTimeout(function () {
                        cup.fadeOut();
                    }, 3000);
                }
            });
            return false;
        });
        
        //zobrazenie info o kosiku po prejdeni mysou po kosiku
        var topcartTimeout = null;
        var topcartTimeoutHide = null;
        $('#topcart').mouseover(function () {
            if (!topcartTimeout) {
                topcartTimeout = window.setTimeout(displayQuickCartInfo, 400);
            }
        }).mouseout(function () {
            window.clearTimeout(topcartTimeout);
            topcartTimeout = null;
        });
        
        function displayQuickCartInfo() {
            if (topcartTimeoutHide) {
                window.clearTimeout(topcartTimeoutHide);
                topcartTimeoutHide = null;
            }
            //vycistime obsah
            $('#cartUpdaterDynamic').empty();
            //progress
            var p = $('#cartUpdater-progress');
            p.show();
            //zobrazime panel
            var cup = $('#cartUpdaterPanel');
            //animacia panelu
            //panel je zapoziciovany k #topcart elementu
            var topcart = $('#topcart');
            var topcartPos = $('#topcart').offset();
            cup.css('left', topcartPos.left + topcart.outerWidth() - cup.width());
            cup.css('top', topcartPos.top + topcart.outerHeight() + 5);
            cup.slideDown();
            //ajax request na zobrazenie stavu kosika
            $.ajax({
                url: LANGROOT + '/eshop/cart/info/',
                type: 'POST',
                dataType: 'json',
                success: function (a) {
                    $('#cartInfoItemsCount').text(a.itemsCount);
                    $('#cartInfoTpriceAmount').text(a.totalPrice);
                    $('#cartUpdaterDynamic').html(a.cartUpdaterHtml);
                    $('#topcart div.topcart').html(a.cartInfoHtml);
                    p.hide();
                    topcartTimeoutHide = window.setTimeout(function () {
                        cup.fadeOut();
                        topcartTimeoutHide = null;
                    }, 5000);
                    cup.one('mouseenter', function () {
                        if (topcartTimeoutHide) {
                            window.clearTimeout(topcartTimeoutHide);
                            topcartTimeoutHide = null;
                        }
                    });
                    cup.one('mouseleave', function () {
                        if (topcartTimeoutHide) {
                            window.clearTimeout(topcartTimeoutHide);
                            topcartTimeoutHide = null;
                        }
                        cup.fadeOut();
                    });
                }
            });
            //nastavime akciu na zrusenie kosikoveho panelu
            $('body').bind('click.hidecartupdater', function (event) {
                var target = $(event.target);
                var isCupClicked = (target == cup) || (target.closest(cup).length ? true : false);
                if (!isCupClicked) {
                    cup.fadeOut();
                    $('body').unbind('click.hidecartupdater');
                    if (topcartTimeoutHide) {
                        window.clearTimeout(topcartTimeoutHide);
                        topcartTimeoutHide = null;
                    }
                }
            });
        }
    }
    
    //popup info s atributmi pri zozname produktov
    $('#contentpanel').on({
        'mouseenter.popuinfo': function () {
            var self = $(this);
            var popupinfo = self.find('div.textAttribs-panel');
            if (popupinfo.length) {
                if (!popupinfo.data('popup.pos.bottom')) {
                    var title = self.find('div.title');
                    var bottom = self.height() - title.position().top;
                    popupinfo.css('bottom', bottom);
                    popupinfo.data('popup.pos.bottom', bottom);
                }
                popupinfo.fadeIn('fast');
            }
        },
        'mouseleave.popuinfo': function () {
            var self = $(this);
            var popupinfo = self.find('div.textAttribs-panel');
            if (popupinfo.length) {
                popupinfo.fadeOut('fast');
            }
        }
    }, 'div.list-item-product-default');
    
    $('div.rating-container').hover(function () {
        $(this).addClass('rating-container-hover');
    }, function () {
        $(this).removeClass('rating-container-hover');
    });
    $('div.rating-container a.rate').click(function () {
        var rating = $(this).closest('div.rating-container').find('div.rating');
        var progress = $(this).closest('div.rating-container').find('div.rating-progress');
        progress.css('opacity',0.7);
        progress.show();
        $.getJSON(this.href, function (result) {
            progress.fadeOut();
            if (result.rating) {
                rating.css('width', (result.rating * 100) + '%');
            }
        })
        return false;
    });
});

