(function($){
    
    
    $(function() {   

        $('input, button').each(function() {
            $(this).addClass($(this).attr('type'));
        });
        
        $.prettyLoader();
        
		
        //target blank
        $('a.external').click(function(){
                window.open($(this).attr('href')); 

                return false;
        });
		
        //confirm class
        $('a.confirm, .reset').click(function() {
            return confirm('Opravdu provést operaci?');
        });
		    
		    
        $('a.collapsibleSwitcher').click(function(){
            $('.collapsibleArticle').slideToggle();
            $('.stranka-uvod #content').animate({
                paddingBottom: '+=1455'    
            });
            $(this).fadeOut();
            return false;
        });
			
        // Lightbox
        if ($.fn.lightBox) {
            $('a.lightbox').lightBox();
        }

        //block UI defaults
        $.blockUI.defaults.css = {
            padding:        0,
            margin:         0,
            width:          '30%',
            top:            '40%',
            left:           '35%',
            textAlign:      'left',
            color:          '#000',
            border:         '3px solid #aaa',
            backgroundColor:'#fff',
            cursor:         'pointer'
        }
        
        /* Items descriptions */
        $('.zbozi .nahled-zbozi').mouseenter(function(){
            $(this).parents('.zbozi').find('p.popis').addClass('mustsee').fadeIn();
        }).mouseleave(function(){
            var item = $(this).parents('.zbozi').find('p.popis');
            item.removeClass('mustsee');
            setTimeout(function(){
                if(!item.hasClass('mustsee'))
                {
                    item.fadeOut();
                }
            }, 500);
        });
        $('.zbozi p.popis').mouseenter(function(){
            $(this).addClass('mustsee');
        }).mouseleave(function(){
            var item =  $(this);
            item.removeClass('mustsee');
            setTimeout(function(){
                if(!(item.hasClass('mustsee')))
                {
                    item.fadeOut();
                }
            }, 500);
        });
        
        // Search autocomplete
//        $( "#search input.text" ).autocomplete({
//                source: "search/autocomplete",
//                minLength: 2,
//                select: function( event, ui ) {
//                    if(ui.item){
//                        this.value = ui.item.id;
//                        $( "#search").submit();
//                    }
//                }
//        });

        //Scroll top
        $('#moveToTopButton').click(function(){
            $('html,body').animate({scrollTop: $("#main").offset().top},'fast');
        });

        
        /* Persistent collapsible menu */
          var cookieValue = $.cookie('menuCookie') || '';
          $('#sidebar-left-menu > li span.prepinac').each(function(index) {
            var $this = $(this), $checkElement = $this.next('ul:first');
            if (cookieValue.indexOf(bigIndex(index)) > -1) {
              if($this.parent().hasClass('path') || $this.parent().hasClass('active')){
                cookieValue = cookieValue.replace(bigIndex(index),'');
                $.cookie('menuCookie', cookieValue, {path: '/'});
              }else{
                  $checkElement.hide();
                  $checkElement.addClass('schovane');
              }
            }
            $this.click(function() {   
              if ($checkElement.is(':hidden')) {
                $checkElement.slideDown();
                $checkElement.removeClass('schovane');
                cookieValue = cookieValue.replace(bigIndex(index),'');
                $.cookie('menuCookie', cookieValue, {path: '/'});
              } else {
                $checkElement.slideUp();
                $checkElement.addClass('schovane');
                cookieValue = cookieValue + bigIndex(index);
                $.cookie('menuCookie', cookieValue, {path: '/'});
              }
              return false;
            });
          });
          
        function showCookie() {
          if (!$('#jar').length) {
            $('<div id="jar"><div></div><button>Delete Cookie</button></div>').appendTo('body');
          }
          $('#jar div').text($.cookie('menuCookie'));
        }
          
        function bigIndex(inival) {
          return inival < 10 ? '0' + inival + '-' : '' + inival + '-';
        }
			
        /* tabulky velikosti */
        if($('.tabulka_vypis').size())
        {
                $('.tabulka_vypis table tr:odd').addClass('odd');
                $('.tabulka_vypis table tr:even').addClass('even');

        }
        
        //oprava breadcrumbu
        $('#drobeckova-navigace li').removeClass('active');
        $('#drobeckova-navigace li:last').addClass('active');
	
        //message
        if ($.fn.message) {
                $.extend($.message.defaults, {
                        opacity: 0.9,
                        displayDurationPerCharacter: 100
                });
                if ($('#flash_message').size()) {
                        $().message($('#flash_message').html(), $('#flash_message').attr('class'));
                }
        }
			
        if($.fn.prettyPhoto) {
        $("a[rel^='prettyPhoto']").prettyPhoto({
                animation_speed:'normal',
                theme:'facebook',
                slideshow:false
        });
        }
			
        var dummy = "";
        if ( $.browser.msie && parseInt($.browser.version, 10) == 7 ) 
        {
                dummy = "/dummy/" + new Date().getTime();
        }

        //validator
        if($.fn.validate) {
                $.extend($.validator.messages, {
                        required: "Tento údaj je povinný.",
                        remote: "Opravte tento údaj.",
                        email: "Zadejte platný e-mail.",
                        url: "Prosím, zadejte platné URL.",
                        date: "Prosím, zadejte platné datum.",
                        dateISO: "Prosím, zadejte platné datum (ISO).",
                        number: "Zadejte číslo.",
                        digits: "Zadávejte pouze číslice.",
                        creditcard: "Prosím, zadejte číslo kreditní karty.",
                        equalTo: "Zadejte stejnou hodnotu",
                        accept: "Prosím, zadejte soubor se správnou příponou.",
                        maxlength: jQuery.validator.format("Zadejte nejvíce {0} znaků."),
                        minlength: jQuery.validator.format("Zadejte nejméně {0} znaků."),
                        rangelength: jQuery.validator.format("Zadejte od {0} do {1} znaků."),
                        range: jQuery.validator.format("Prosím, zadejte hodnotu od {0} do {1}."),
                        max: jQuery.validator.format("Zadejte hodnotu menší nebo rovnu {0}."),
                        min: jQuery.validator.format("Zadejte hodnotu větší nebo rovnu {0}.")
                });
        }
			

        //sitemap
        if($('.sitemap').size())
        {
                $('.sitemap .menu').treeview({
                        collapsed: false,
                        animated: "medium",
                        persist: "cookie"
        });
        }

        function intval(mixed_var, base) {
            // Get the integer value of a variable using the optional base for the conversion  
            // 
            // version: 1103.1210
            // discuss at: http://phpjs.org/functions/intval    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: stensi
            // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   input by: Matteo
            // +   bugfixed by: Brett Zamir (http://brett-zamir.me)    // *     example 1: intval('Kevin van Zonneveld');
            // *     returns 1: 0
            // *     example 2: intval(4.2);
            // *     returns 2: 4
            // *     example 3: intval(42, 8);    // *     returns 3: 42
            // *     example 4: intval('09');
            // *     returns 4: 9
            // *     example 5: intval('1e', 16);
            // *     returns 5: 30    var tmp;

            var type = typeof(mixed_var);

            if (type === 'boolean') {return (mixed_var) ? 1 : 0;
            } else if (type === 'string') {
                tmp = parseInt(mixed_var, base || 10);
                return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
            } else if (type === 'number' && isFinite(mixed_var)) {return Math.floor(mixed_var);
            } else {
                return 0;
            }
        }

        function print_r(theObj){
                var ret = "";
                  if(theObj.constructor == Array ||
                     theObj.constructor == Object){
                    ret += "<ul>";
                    for(var p in theObj){
                      if(theObj[p].constructor == Array||
                         theObj[p].constructor == Object){
                ret += "<li>["+p+"] => "+typeof(theObj)+"</li>";
                ret += "<ul>";
                        print_r(theObj[p]);
                        ret += "</ul>";
                      } else {
                          ret += "<li>["+p+"] => "+theObj[p]+"</li>";
                      }
                    }
                    ret +="</ul>";
                  }
                  alert(ret);
                }


            function validateNumChange(item, kolik)
            {
                    max = intval(item.attr('maxvalue'));
                    kolik = intval(kolik);
                    if(max)
                    {
                            if(kolik > max)
                            {
                                    //na pozadi se pokusim pridat vyrobek do kosiku a reloadnout ho
                                    //$('#shoppingcontainer').block({ message: null });
                                            $.ajax({
                                                      url: "/item/addToCart" + dummy,
                                                      dataType: 'json',
                                                      data: {'add_shop_item': item.attr('add_id')},
                                                      success: function(data){
                                                            if(data.success)
                                                            {
                                                              $('#shoppingcontainer').html(data.html);
                                                              prepareShoppingCart();
                                                              //autoSubmitTrigger(item.parents('form'), 10);
                                                            }else{
                                                                    $().message(data.msg, data.status);
                                                                    autoSubmitTrigger(item.parents('form'));
                                                            }
                                                            if(data.success && data.top_basket)
                                                            {
                                                                    $('#nakupni-kosik dd').html(data.top_basket);
                                                            }
                                                             //$('#partc').unblock();
                                                      }
                                            });
                                            kolik = max;
                            }else{
                                    autoSubmitTrigger(item.parents('form'));
                            }
                    }
                    return kolik;
            }

            var t;
            function prepareShoppingCart()
            {
            // plus minus znaminka u tabulkovyho vypisu
                    if($('#shoppingcontainer').size())
                    {
                            $('#shoppingcontainer .kosik-zbozi').find('input').css('textAlign', 'center').attr('readonly', 'readonly').change(function(){
                                    $(this).val(validateNumChange($(this), $(this).val()));
                            });
                            $('.pridat').each(function(){
                                    $(this).click(function(){
                                            input = $(this).parent().parent().find('input');
                                            kolik = input.val();
                                            kolik++;
                                            input.val(validateNumChange(input, kolik));
                                    });
                            }).css('cursor', 'pointer');
                            $('.ubrat').each(function(){
                                    $(this).click(function(){
                                            input = $(this).parent().parent().find('input');
                                            kolik = input.val()-1;
                                            if(kolik < 0) {kolik = 0;}
                                            input.val(validateNumChange(input, kolik));
                                    });
                            }).css('cursor', 'pointer');

                            //odebirani ajaxem
                            $('#shoppingcontainer a.smazat').click(function(){
                                    $('#shoppingcontainer').block({message: null});
                                    $.ajax({
                                              url: $(this).attr('href')+dummy,
                                              dataType: 'json',
                                              success: function(data){
                                                    if(data.success)
                                                    {
                                                      $('#shoppingcontainer').html(data.html);
                                                      prepareShoppingCart();
                                                    }
                                                    if(data.success && data.top_basket)
                                                    {
                                                            $('#nakupni-kosik dd').html(data.top_basket);
                                                    }
                                                     $('#shoppingcontainer').unblock();
                                              }
                                    });
                                    return false;
                            });

                            //obnovovani ajaxem
                            $('a.cart_restore_item').click(function(){
                                    $('#shoppingcontainer').block({message: null});
                                    $.ajax({
                                              url: $(this).attr('href')+dummy,
                                              dataType: 'json',
                                              success: function(data){
                                                    if(data.success)
                                                    {
                                                      $('#shoppingcontainer').html(data.html);
                                                      prepareShoppingCart();
                                                    }
                                                    if(data.success && data.top_basket)
                                                    {
                                                            $('#nakupni-kosik dd').html(data.top_basket);
                                                    }
                                                     $('#shoppingcontainer').unblock();
                                              }
                                    });
                                    return false;
                            });

                            //aplikovani slevoveho kuponu
                            $('#voucherSubmit').click(function(){
                                    $('#shoppingcontainer').block({message: null});
                                    $.ajax({
                                              url: '/cart/addVoucher'+dummy,
                                              dataType: 'json',
                                              data: {'voucher_no': $('#voucher_no').val()},
                                              success: function(data){
                                                    $().message(data.msg, data.status);
                                                    if(data.success)
                                                    {
                                                      $('#shoppingcontainer').html(data.html);
                                                      prepareShoppingCart();
                                                    }
                                                    if(data.success && data.top_basket)
                                                    {
                                                            $('#nakupni-kosik dd').html(data.top_basket);
                                                    }
                                                     $('#shoppingcontainer').unblock();
                                              }
                                    });
                                    return false;
                            });

                            $('#userVoucherSubmit').click(function(){
                                    $('#shoppingcontainer').block({message: null});
                                    $.ajax({
                                              url: '/cart/addVoucher'+dummy,
                                              dataType: 'json',
                                              data: {'voucher_no': $('#user_voucher').val()},
                                              success: function(data){
                                                    $().message(data.msg, data.status);
                                                    if(data.success)
                                                    {
                                                      $('#shoppingcontainer').html(data.html);
                                                      prepareShoppingCart();
                                                    }
                                                    if(data.success && data.top_basket)
                                                    {
                                                            $('#nakupni-kosik dd').html(data.top_basket);
                                                    }
                                                     $('#shoppingcontainer').unblock();
                                              }
                                    });
                                    return false;
                            });

                            //odebrani kuponu
                            $('.removeVoucher').click(function(){
                                    $('#shoppingcontainer').block({message: null});
                                    $.ajax({
                                              url: $(this).attr('href')+dummy,
                                              dataType: 'json',
                                              success: function(data){
                                                    $().message(data.msg, data.status);
                                                    if(data.success)
                                                    {
                                                      $('#shoppingcontainer').html(data.html);
                                                      prepareShoppingCart();
                                                    }
                                                    if(data.success && data.top_basket)
                                                    {
                                                            $('#nakupni-kosik dd').html(data.top_basket);
                                                    }
                                                     $('#shoppingcontainer').unblock();
                                              }
                                    });
                                    return false;
                            });

                            prepareTooltip();
                    }
            }
            prepareShoppingCart();
			
            function autoSubmitTrigger(form, timeleft)
            {
                    timeleft = typeof(timeleft) != 'undefined' ? timeleft : 2000;
                    clearTimeout(t);

                    t = setTimeout(function(){
                            //nechame si poslat updatlou verzi
                            $('#shoppingcontainer').block({message: null});
                            $.ajax({
                                      url: "/cart/updateCart"+dummy,
                                      dataType: 'json',
                                      data: form.serializeArray(),
                                      success: function(data){
                                            if(data.success){
                                              $('#shoppingcontainer').html(data.html);
                                              prepareShoppingCart();
                                            }
                                            if(data.success && data.top_basket)
                                            {
                                                    $('#nakupni-kosik dd').html(data.top_basket);
                                            }
                                            $('#shoppingcontainer').unblock();
                                      }
                                    });
                    }, timeleft);
            }

             //newsletter
            $error = $('<span/>').addClass('newsletter_msg').hide().appendTo('#newsletterinnerwrapper');
            $('#newsletterSubscribe').click(function(){
                    var cont = $('#newsletterform');
                    cont.block({message: null});
                    $.ajax({
                              url: "/newsletter/subscribe"+dummy,
                              dataType: 'json',
                              data: {
                            email: cont.find('input').val()
                              },
                              success: function(data){
                                      if(data.success)
                                      {
                                              $error.removeClass('error').text(data.msg).fadeIn(30);
                                      }else{
                                                    $error.addClass('error').text(data.msg).fadeIn(30);
                                      }
                                            setTimeout(function(){
                                                    $error.fadeOut(1000)
                                            }, 2000);
                                      cont.unblock();
                              }
                    });
                    return false;
            });

             var pos = 0; 

            var offer_nastaveni = {
                    message:		'',
                    cas: {
                    padding:        0,
                    margin:         0,
                    width:          '30%',
                    top:            '40%',
                    left:           '35%',
                    textAlign:      'left',
                    color:          '#000',
                    border:         'none',
                    backgroundColor:'transparent',
                    cursor:         'pointer'
                    }

        }

        if ($.fn.tabs) {
            $("#tabs").tabs();

            $('#tabs_customer').tabs({
                create: function(event, ui) {
                    $(this).removeClass('ui-widget ui-widget-content ui-corner-all');
                    $('*', $(this)).removeClass('ui-widget ui-widget-content ui-corner-all ui-corner-bottom ui-state-active ui-state-default ui-corner-top ui-helper-reset ui-helper-clearfix ui-widget-header');
                    //zvolit selection
                    if($('#tabs_customer .tab.selected').size())
                    {
                        $(this).tabs( "option", "selected", $('#tabs_customer .tab.selected').attr('id') );
                    }
                }
            });
            if($('#tabs_customer .moznosti-prihlaseni ul li a.disabled').size())
            {
                $('#tabs_customer').tabs({
                        selected: 0,
                        disabled: [1, 2],
                        create: function(event, ui) {
                            $(this).removeClass('ui-widget ui-widget-content ui-corner-all');
                            $('*', $(this)).removeClass('ui-widget ui-widget-content ui-corner-all ui-corner-bottom ui-state-active ui-state-default ui-corner-top ui-helper-reset ui-helper-clearfix ui-widget-header');
                        }
                });
            }
        }
        
        //toggle next
        if($('a.toggle_next').size())
        {
                $('a.toggle_next').each(function(){
                        $(this).click(function(){
                                $(this).parent().next().slideToggle();
                                return false;
                        });
                });
        }
        if ($.fn.infiniteCarousel) {
                $('#banner1').infiniteCarousel({
                        displayThumbnails: false,
                        imagePath: '/images/',
                        showControls: false,
                        displayProgressBar: false,
                        displayTime: 5000
                });
        }
		    

          function prepareTooltip()
          {
            $("[title]").tooltip({ 
                delay: 0, 
                showURL: false
            });
          }
          prepareTooltip();
          
          if($('#sidebar-right .box ul li a').size()){
              $("#sidebar-right .box ul li a").tooltip({
                 delay: 0,
                 bodyHandler: function() { 
                    return $($(this).next('p')).html(); 
                },
                showURL: false
              });
          }

    });
	
	
})(jQuery)
