$(document).ready (function (){	
    bind_path ();
    bind_submenu_extend ();
    bind_color_header ();
    bind_input_clear ();
	bind_menu ();
	bind_ifixpng ();
	bind_news ();
	bind_tabs ();
	bind_anims ();
    bind_autocomplete ();
    bind_product_tooltip ();
    bind_product_tooltip2 ();
	bind_product_tooltip3 ();
	bind_com_tooltip();
    bind_product_filter ();
    bind_product_short_cycle ();
    bind_gallery_eshop_shifter ();
    bind_homepage_menu ();
	bind_img_loader ();
});

function bind_path ()
{
    // if ($('.path li').length < 2) {
    //     $('.path').remove();
    // }
}

// rozsiruje vlastnosti .submenu
function bind_submenu_extend ()
{
    $('.submenu > ul').addClass('level1');
    $('.submenu > ul > li > ul').addClass('level2');
    $('.submenu > ul > li > ul > li > ul').addClass('level3');

    $('.submenu > ul.level1 > li.lifetime-serie, '+
      '.submenu > ul.level1 > li.auto-moto, ' +
      '.submenu > ul.level1 > li.outdoor, ' +
      '.submenu > ul.level1 > li.sport, ' +
      '.submenu > ul.level1 > li.more, ' +
      '.submenu > ul.level1 > li.mapy, ' +
      '.submenu > ul.level1 > li.ostatni').addClass('submenu-spec');

    $('li.lifetime-serie.active').addClass('lifetime-serie-active');
    $('li.auto-moto.active').addClass('auto-moto-active');
    $('li.outdoor.active').addClass('outdoor-active');
    $('li.sport.active').addClass('sport-active');
    $('li.more.active').addClass('more-active');
    $('li.mapy.active').addClass('mapy-active');
    $('li.ostatni.active').addClass('ostatni-active');

    // mezi spec polozky menu vlozi spec li
    $('li.submenu-spec.first').before('<li class="it-spec-li-bottom"></li>');
    $('li.submenu-spec').after('<li class="it-spec-li-right"></li>');

    // nastaveni ramecku kolem spec li
    $('li.submenu-spec.active').prev().attr('class', 'it-spec-li-top');
    $('li.submenu-spec.active').next().attr('class', 'it-spec-li-bottom');
    //if ($('li.submenu-spec.last').filter(':not(.active)')) $('li.submenu-spec.last').next().attr('class', 'it-spec-li-right');
    if ($('li.submenu-spec.first').hasClass('active')) $('li.submenu-spec.first').prev().attr('class', 'it-spec-li-left');
        else $('li.submenu-spec.first').prev().attr('class', 'it-spec-li-bottom');
    //if ($('.submenu > ul.level1 > li.last').filter(':not(.submenu-spec)')) $('.submenu > ul.level1 > li.last').after('<li class="it-spec-li-bottom"></li>');
    if (!$('.submenu > ul.level1 > li.last').hasClass('submenu-spec')) $('.submenu > ul.level1 > li.last').after('<li class="it-spec-li-bottom"></li>');

    $(".submenu > ul.level1 > li.lifetime-serie").hover(
        function() { $(this).addClass("lifetime-serie-sfhover"); },
        function() { $(this).removeClass("lifetime-serie-sfhover");
    } );
    $(".submenu > ul.level1 > li.auto-moto").hover(
        function() { $(this).addClass("auto-moto-sfhover"); },
        function() { $(this).removeClass("auto-moto-sfhover");
    } );
	$(".submenu > ul.level1 > li.outdoor").hover(
        function() { $(this).addClass("outdoor-sfhover"); },
        function() { $(this).removeClass("outdoor-sfhover");
    } );
	$(".submenu > ul.level1 > li.sport").hover(
        function() { $(this).addClass("sport-sfhover"); },
        function() { $(this).removeClass("sport-sfhover");
    } );
	$(".submenu > ul.level1 > li.more").hover(
        function() { $(this).addClass("more-sfhover"); },
        function() { $(this).removeClass("more-sfhover");
    } );
	$(".submenu > ul.level1 > li.mapy").hover(
        function() { $(this).addClass("mapy-sfhover"); },
        function() { $(this).removeClass("mapy-sfhover");
    } );
	$(".submenu > ul.level1 > li.ostatni").hover(
        function() { $(this).addClass("ostatni-sfhover"); },
        function() { $(this).removeClass("ostatni-sfhover");
    } );

    if ($('.submenu').length == 0) {
        $('.left-panel-search-device').append('<div class="submenu"><ul class="level1"><li class="it-spec-li-bottom"></li></ul></div>');
    }
    $('#submenu').slideDown(500);
}

// "obarvi" napdisy podle kategorie
function bind_color_header ()
{
    if ($('.submenu li.lifetime-serie-active').length > 0) $('h1').addClass('lifetime-serie-header');
    if ($('.submenu li.auto-moto.active').length > 0) $('h1').addClass('auto-moto-header');
    if ($('.submenu li.outdoor-active').length > 0) $('h1').addClass('outdoor-header');
    if ($('.submenu li.sport-active').length > 0) $('h1').addClass('sport-header');
    if ($('.submenu li.more-active').length > 0) $('h1').addClass('more-header');
    if ($('.submenu li.mapy-active').length > 0) $('h1').addClass('mapy-header');
    if ($('.submenu li.ostatni-active').length > 0) $('h1').addClass('ostatni-header');
}

// pri fokusu inputu vymaze hodnotu
function bind_input_clear ()
{
    $('.input-clear').focus(function() {
        $(this).val('');
    });
}

function bind_menu ()
{
	$('.menu ul:first li:first').addClass('nobkg');
				
	$(".menu li, #service-right .search-button, button").hover(
		function() {
			$(this).addClass("sfhover");
		},
		function() {
			$(this).removeClass("sfhover");
		}
	);	
}

function bind_ifixpng ()
{
	$('#title-cover').ifixpng();
}

function bind_news ()
{
	/* half news */
	var i=0;
	$(".content .article5").each(function(){
		if(i==1) {
			$(this).addClass("second");
			i=0;
		}
		else
			i++;
	});	
}

function bind_anims ()
{
	/* animace na strance s prodejci*/
	if ($(".prodejci p:first").length > 0) {
		$(".prodejci p:first").addClass("tmp").cycle();
	}
}

function bind_tabs ()
{
    if ($('#tabs').length > 0) {
    	// skryje prazdne zalozky
    	$('#tabs>div:empty').remove();
    	$('#tabs>ul a').each(function(){
    		o = $(this).attr('href');
    		if ($(o).length == 0) {
    			$(this).parent().remove();
    		}
    	});
    	// produktove zalozky
    	$('#tabs').tabs({ fx: { opacity: 'toggle' } });
    }
    
    if ($('#tab_produkty').length > 0) {
        // $('#tab_produkty h4:first-child').hide();
        $('#tab_produkty ul').hide();
        $('#tab_produkty > div').hide();

        $('#tab_produkty h4').prepend('<span>+ </span>');
        $('#tab_produkty h4').css('cursor', 'pointer');
        $('#tab_produkty h4').toggle(function(){
            $(this).find('span').text('- ');
            $(this).next().fadeIn();
        }, function(){
            $(this).find('span').text('+ ');
            $(this).next().fadeOut();
        });
    }
}

function stripslashes (str) {
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':
                return '\0';
            case '':
                return '';
            default:
                return n1;
        }
    });
}

function urldecode (str) {
   
    var hash_map = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
    
    var replacer = function (search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The hash_map is identical to the one in urlencode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';
    hash_map['%20'] = '+';
    hash_map['\u00DC'] = '%DC';
    hash_map['\u00FC'] = '%FC';
    hash_map['\u00C4'] = '%D4';
    hash_map['\u00E4'] = '%E4';
    hash_map['\u00D6'] = '%D6';
    hash_map['\u00F6'] = '%F6';
    hash_map['\u00DF'] = '%DF';
    hash_map['\u20AC'] = '%80';
    hash_map['\u0081'] = '%81';
    hash_map['\u201A'] = '%82';
    hash_map['\u0192'] = '%83';
    hash_map['\u201E'] = '%84';
    hash_map['\u2026'] = '%85';
    hash_map['\u2020'] = '%86';
    hash_map['\u2021'] = '%87';
    hash_map['\u02C6'] = '%88';
    hash_map['\u2030'] = '%89';
    hash_map['\u0160'] = '%8A';
    hash_map['\u2039'] = '%8B';
    hash_map['\u0152'] = '%8C';
    hash_map['\u008D'] = '%8D';
    hash_map['\u017D'] = '%8E';
    hash_map['\u008F'] = '%8F';
    hash_map['\u0090'] = '%90';
    hash_map['\u2018'] = '%91';
    hash_map['\u2019'] = '%92';
    hash_map['\u201C'] = '%93';
    hash_map['\u201D'] = '%94';
    hash_map['\u2022'] = '%95';
    hash_map['\u2013'] = '%96';
    hash_map['\u2014'] = '%97';
    hash_map['\u02DC'] = '%98';
    hash_map['\u2122'] = '%99';
    hash_map['\u0161'] = '%9A';
    hash_map['\u203A'] = '%9B';
    hash_map['\u0153'] = '%9C';
    hash_map['\u009D'] = '%9D';
    hash_map['\u017E'] = '%9E';
    hash_map['\u0178'] = '%9F';
    hash_map['\u00C6'] = '%C3%86';
    hash_map['\u00D8'] = '%C3%98';
    hash_map['\u00C5'] = '%C3%85';
 
    for (unicodeStr in hash_map) {
        hexEscStr = hash_map[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}

// autocomplete naseptavac
function bind_autocomplete ()
{

    $.getJSON('http://'+location.host+'/static/ajaxgenerator.json', function(data) {
        myJSONdata = data;

        $("#left-panel-search-device-input").autocomplete(myJSONdata, {
            minChars: 1,
            width: 237,
            max: 10,
            //dataType: "json",
            scrollHeight: 500,
            parse: function(data) {
    			return $.map(data, function(row) {
    				return {
    					data: row,
    					value: unescape(row.name),
    					result: unescape(row.name)
    				}
    			});
    		},
            formatItem: function(row, i, max) {
    			return "<span>" + row.name.replace("ü", "u") + "</span>" ;
    		},
            matchContains: "word"
        }).result(function(e, item) {
    		window.location = item.url;
    		$("#left-panel-search-device-input").val("");
    	});
    });
}

// zobrazuje a skryva tooltip produktu
function bind_product_tooltip ()
{
    $('.product-short').hoverIntent(
        function() {
            $(this).find('.product-tooltip').stop(true, true).fadeIn(200);
        },
        function() {
            $(this).find('.product-tooltip').stop(true, true).fadeOut(200);
        }
    );
}

function bind_product_tooltip2 ()
{
    $('.product-full-marks img').hover(
        function() {
            if ($(this).prev().is('span')) $(this).prev().show();
                else $(this).parent().prev().show();
        },
        function() {
            if ($(this).prev().is('span')) $(this).prev().hide();
                else $(this).parent().prev().hide();
        }
    );
}

function bind_product_tooltip3 ()
{
	$('.other-categories .eshop-category-image').each(function(i) {
		if ($(this).next().hasClass('product-tooltip')) {
			var shiftMargin = (i + 1) * 125;
			$(this).next().css('margin-left', shiftMargin);
		}
	});
	$('.eshop-category-image').hoverIntent(
		function() {
			if ($(this).next().hasClass('product-tooltip')) {
            	$(this).next().stop(true, true).fadeIn(200);
			}
        },
        function() {
			if ($(this).next().hasClass('product-tooltip')) {
            	$(this).next().stop(true, true).fadeOut(200);
			}
        }
    );
}

/**
 * Obecny tooltip
 */
function bind_com_tooltip() {
	$('.com-tooltip-link').hover(function() {
		$(this).prev().fadeIn('fast');
	}, function() {
		$(this).prev().fadeOut('fast');
	});
}

// zobrazuje dalsi moznosti u filtru pri vyhledavani produktu
function bind_product_filter ()
{
    $('.filter-button.more').click(function(e) {
        e.preventDefault();
        $(this).hide();
        $('.product-filter-group.subgroup').slideDown(300);
    });
}

function bind_product_short_cycle ()
{
    if ($('.product-short-cycler').length > 0) {
        $('.product-short-cycler').cycle();
    }
}

function bind_gallery_eshop_shifter ()
{
    var imgWidth = 82; // sirka obrazku
    var imgSum = $('.gallery-eshop-shifter .eshop-gallery-image').size(); // pocet obr v galerii
    
    // pokud je v galerii 4 a mene fotek nezobrazi posunovaci sipky
    if (imgSum <= 4) {
        $('.gallery-eshop-right').hide();
        $('.gallery-eshop-left').hide();
        $('.gallery-eshop-shifter').css('left', '23px');
    } else {
        $('.gallery-eshop-shifter .gallery').width(imgWidth*imgSum);
        $('.gallery-eshop-shifter .gallery').css('marginLeft', '0');
        var counter = imgSum; // pomocna prom pro posun
        var galMargin = 0; // velikost posunu galerie

        // posun doprava
        $('.gallery-eshop-right').click(function() {
            if (counter > 4) {
                counter--;
                galMargin = galMargin - imgWidth;
                $('.gallery-eshop-shifter .gallery').stop(true, true).animate({marginLeft: galMargin}, 200);
            } else { // kdyz je na konci, tak se vrati na zacatek
                counter = imgSum;
                galMargin = 0;
                $('.gallery-eshop-shifter .gallery').stop(true, true).animate({marginLeft: galMargin}, 300);
            }
        });

        // posun doleva
        $('.gallery-eshop-left').click(function() {
            if (counter < imgSum) {
                counter++;
                galMargin = galMargin + imgWidth;
                $('.gallery-eshop-shifter .gallery').stop(true, true).animate({marginLeft: galMargin}, 200);
            }
        });
    }
}

// "zivot" na HP
function bind_homepage_menu ()
{
    $('.home-active-cont-benefits>div').hover(
        function() {
            $(this).addClass('sfhover');
        },
        function() {
            $(this).removeClass('sfhover');
        }
    );

    // prvni produkt z kategorie oznaci za top-product
    $('.home-active-cont-product.lifetime-serie:first').addClass('top-product');
    $('.home-active-cont-product.auto-moto:first').addClass('top-product');
    $('.home-active-cont-product.outdoor:first').addClass('top-product');
    $('.home-active-cont-product.sport:first').addClass('top-product');
    $('.home-active-cont-product.more:first').addClass('top-product');
    $('.home-active-cont-product.mapy:first').addClass('top-product');
    $('.home-active-cont-product.ostatni:first').addClass('top-product');

    var shadeSpeed = 300; // rychlost provadeni animace
    var shadeStepConst = 49; // konstanta o kterou se bude posouvat pozadi
    var shadeTop; // horni pozice stinu
    var shadeTopConst = -329;
    var itemIndex = -1; // index polozky menu
    var obj; // pomocna promenna pro aktualni element
    
    // nastavi cycle pro pozadi
    homeCycle();

    // nastavi prni polozku na aktivni
//     $('.home-menu li').eq(itemIndex).find('a').addClass('hm-active');

    // zobrazi akce
    if ($('.home-bkg-cycle').length > 0) {
        $('.home-bkg-cycle').cycle($('.home-bkg-cycle img:last').index());
    }
    $('.home-active-cont').children(':first-child').show();

    
    // pri zmene rozmeru znovu inicializuje cycle
    $(window).resize(function() {
        var tmpIndex = $('.home-menu li a.hm-active').parent().index();
//         homeCycle();
        $('.home-bkg-cycle img').width($('.home-bkg-cycle').width());
        if ($('.home-bkg-cycle').length) {
            $('.home-bkg-cycle').cycle({
                startingSlide: tmpIndex,
                timeout: 0,
                speed: 300
            });
        }
    });
    
    $('.home-menu li a').hoverIntent(function() {
        obj = $(this);
        if (itemIndex != obj.index(obj.index('.home-menu li a'))) {
            // zrusi class aktivnich prvku
            $('.home-menu li').eq(itemIndex).find('a').removeClass('hm-active');
            
            // schova elementy v osahove casti
            $('.home-active-cont').children().clearQueue().hide();

            // zjisti index polozky menu
            itemIndex = $('.home-menu li a').index(this);

            // prida class aktivni polozce
            $(this).addClass('hm-active');

            // nastavi horni pozici stinu
            shadeTop = (itemIndex * shadeStepConst) + shadeTopConst;
            shadeTop = shadeTop + 'px';
            
            // provede animaci posunu stinu a pote zmeni pozadi
            $('.home-menu-shade').stop().animate({
                top: shadeTop
            }, shadeSpeed, 'backout',
                function() {
                    if ($('.home-bkg-cycle').length > 0) {
                        $('.home-bkg-cycle').cycle(itemIndex);
                    }
                });
            
            // lifetime
            if (itemIndex == 0) showLifetime();
            
            // urci, ktery obsah se vypise
            switch (itemIndex) {
                case 1:
                    showProducts($('.home-active-cont-product.auto-moto'), $('.home-active-cont-benefits-auto-moto'));
                    break;
                case 2:
                    showProducts($('.home-active-cont-product.outdoor'), $('.home-active-cont-benefits-outdoor'));
                    break;
                case 3:
                    showProducts($('.home-active-cont-product.sport'), $('.home-active-cont-benefits-sport'));
                    break;
                case 4:
                    showProducts($('.home-active-cont-product.more'), $('.home-active-cont-benefits-more'));
                    break;
                case 5:
                    showProducts($('.home-active-cont-product.mapy'), $('.home-active-cont-benefits-mapy'));
                    break;
                case 6:
                    showProducts($('.home-active-cont-product.ostatni'), $('.home-active-cont-benefits-ostatni'));
                    break;
            }
        }
    }, function() {}
    );
}

// nastavi cycle pro pozadi
function homeCycle() {
    if ($('.home-bkg-cycle').length > 0) {
        $('.home-bkg-cycle').cycle({
    //         startingSlide: index,
            timeout: 0,
            speed: 300
        });
    }
}

// funkce pro vykresleni obsahu lifetime na HP
function showLifetime() {
//     $('.home-lifetime-header').fadeIn(100);
//     $('.home-lifetime-subscribe').fadeIn(170);
//     $('.home-lifetime-item').each(function(i) {
//         $(this).delay(i*50).fadeIn(60);
//     });
    
    $('.home-lifetime-header').show();
    $('.home-lifetime-subscribe').show();
    $('.home-active-cont-product.lifetime').show();
}
// funkce pro vykresleni obecneho obsahu na HP
function showProducts(elm, elm2) {
//     elm.each(function(i) {
//         $(this).delay(i*90).fadeIn(100);
//     });
//     elm2.delay(200).fadeIn(100);

    elm.each(function(i) {
        $(this).show();
    });
    elm2.show();
}

function bind_img_loader () {
	$(window).load(function(){
		$('.eshop-prev span.prev-loader').fadeOut('fast', function() {$(this).remove();});
	});
}

