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('');
    }
}

//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;
    }
};

$(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();
    //znacky
	$('#brands li').hover(function () {
        var a = $(this).find('>a');
        var brand = a.attr('rel');
        $(this).addClass(brand + '-hover');
    },function () {
        var brand = $(this).find('>a').attr('rel');
        $(this).removeClass(brand + '-hover');
    });
	
    //rozbalovanie modulov
    $('div.plus span').click(function(){
        var more = $(this).closest('div.module').find('ul.more');
        if(more.length && more.is(":hidden")){
            more.slideDown("slow");
            var title = $(this).html();
            $(this).html($(this).siblings('span.less').html());
            $(this).siblings('span.less').html(title);
        }
        else if(more.length && more.is(":visible")){
            more.slideUp("slow");
            var title = $(this).html();
            $(this).html($(this).siblings('span.less').html());
            $(this).siblings('span.less').html(title);
        }
        
    });
    
    //podkategorie menu
    $('#categories li.main').mouseenter(function(e){
        //e.preventDefault();
        //pre istotu sa skryjeme vsetky submenu
        $('#categories .submenu').stop(true, true).hide();
        //nastavime si elementy
        var wrapper = $(this).find('div.submenu');
        var submenu = $(this).find('ul.subsub:first');
        var wrapperContent = $(this).find('div.submenuContent');
        submenu.show();
        
        wrapper.stop(true,true);
        $(this).addClass("hover");
        wrapper.fadeIn(300);
        menuPlaceWrapper(wrapper);
        // menuHideSubsubs(this);
        
        //zaktivnenie a vysunutie prvej polozky
        var active = submenu.find('>li.active');
        if (!active.length) {
            // active = submenu.find('>li.sub:first');
        }
        if(active.length) {
            subsubmenu = active.find('ul');
            if(subsubmenu.size()) {
                active.addClass('active');
                active.find('a.asub:first').addClass('active');
                //sirka submenu
                var w = subsubmenu.width() + submenu.width();
                wrapper.width(w);
                //vyska submenu
                wrapperContent.animate({
                    height: Math.max(submenu.height(), subsubmenu.height())
                },300, function () {
                    subsubmenu.show();
                });
            }
        }
        $(this).one('mouseleave',function() {
            wrapper.hide();
            $(this).removeClass("hover");
        });
    });
    // //zobrazime submenu pre tie, kde sa ma implicitne zobrazit
    // $('#categories li.displaysub').each(function () {
    //     //nastavime si elementy
    //     var wrapper = $(this).find('div.submenu');
    //     var submenu = $(this).find('ul.subsub:first');
    //     var wrapperContent = $(this).find('div.submenuContent');
    //     submenu.show();
    //     
    //     wrapper.stop(true,true);
    //     $(this).addClass("hover");
    //     wrapper.fadeIn(300);
    //     
    //     menuPlaceWrapper(wrapper);
    //     menuHideSubsubs(this);
    // });
    //kliknutie na podkategoriu - vylistovanie submenu
    $('#categories a.asub').click(function(e){
        if (!$(this).is('.active')) {
            //skryjeme ostatne otvorene submenu
            menuHideSubsubs($(this).closest('li.main')[0]);
            
            var submenu = $(this).closest('ul');
            var subsubmenu = $(this).closest('li').find('ul.subsub:first');
            var wrapper = $(this).closest('div.submenu');
            var wrapperContent = $(this).closest('div.submenuContent');
            
            //skryjeme zobrazene submenu a zrusime aktivnu polozku
            submenu.find('ul.subsub:visible').hide();
            submenu.find('.active').removeClass('active');
            
            //zaktivnime polozku
            $(this).addClass('active');
            $(this).closest('li').addClass('active');
            //zobrazime submenu
            //sirka submenu
            var w = subsubmenu.width() + submenu.width();
            wrapper.width(w);
            menuPlaceWrapper(wrapper);
            //vyska submenu
            wrapperContent.animate({
                height: Math.max(submenu.height(), subsubmenu.height())
            },300, function () {
                subsubmenu.show();
            });
        }
        return false;
    });
    function menuPlaceWrapper(wrapper) {
        var wrw = wrapper.width() + 7;
        var vw = $(window).width() + $(document).scrollLeft(); //visible width
        //napozicujeme wrapper tam kde by mal byt vzdy a testneme ci nie je mimo obrazovky
        wrapper.css('left', -9);
        var rightpoint = wrapper.offset().left + wrw;
        if (rightpoint > vw) {
            var newOffsetLeft = vw - wrw;
            var parentOffsetLeft = wrapper.closest('li.main').offset().left;
            wrapper.css('left', newOffsetLeft - parentOffsetLeft);
        }
    }
    //skryt vsetky ostatne
    function menuHideSubsubs(exclude) {
        $('#categories li.main').each(function () {
            if (this == exclude) {
                //s tymto nerobime nic...
            } else {
                var submenu = $(this).find('ul');
                submenu.find('ul.subsub').hide();
                submenu.find('.active').removeClass('active');
                //wrapper w/h
                $(this).find('div.submenu').width(170);
                $(this).find('div.submenuContent').height('auto');
            }
        });
    }
    //animacia bannerov
    var banners1Enabled = true;
    var banners1Timeout = null;
    $('#banners1').each(function () {
        displayNextBanner.call(this, true);
    }).hover(function () {
        $(this).find('.bannerMovePrev, .bannerMoveNext').stop(true,true).fadeTo(500, 0.6);
        banners1Enabled = false;
        window.clearTimeout(banners1Timeout);
    }, function () {
        $(this).find('.bannerMovePrev, .bannerMoveNext').stop(true,true).fadeOut();
        banners1Enabled = true;
        var banners1 = this;
        banners1Timeout = window.setTimeout(function () {
            displayNextBanner.call(banners1);
        },5000);
    });
    $('#banners1 .bannerMovePrev').click(function () {
        displayNextBanner.call($('#banners1')[0], false, true, true);
    });
    $('#banners1 .bannerMoveNext').click(function () {
        displayNextBanner.call($('#banners1')[0], false, true);
    });
    function displayNextBanner(init, forceEnabled, prev) {
        var $banners = $(this);
        if ($banners.find('div.banner').length > 1) {
            if (banners1Enabled || forceEnabled) {
                //prave zobrazeny chip
                var bannerItemCur = $banners.find('div.banner-show');
                var duration = 0;
                if (init) {
                    duration = parseInt(bannerItemCur.find('input[name=duration]').val());
                    //nastavime absolutnu poziciu na chipsy
                    $banners.css('position', 'relative').find('div.banner').css('position', 'absolute');
                    var curH = bannerItemCur.height();
                    $banners.height(curH);
                    $banners.find('.bannerMovePrev, .bannerMoveNext').height(curH);
                } else {
                    if (prev) {
                        var nextItem = bannerItemCur.next('div.banner-hide');
                        if (nextItem.length == 0) {
                            nextItem = $banners.find('div.banner:eq(0)');
                        }
                    } else {
                        var nextItem = bannerItemCur.prev('div.banner-hide');
                        if (nextItem.length == 0) {
                            nextItem = $banners.find('div.banner:last');
                        }
                    }
                    
                    //animacia
                    var h = nextItem.height();
                    h = h < 50 ? 50 : h;
                    $banners.add().animate({
                        height: h
                    },500);
                    $banners.find('.bannerMovePrev, .bannerMoveNext').height(h);
                    
                    bannerItemCur.removeClass('banner-show').addClass('banner-hide').fadeOut(300);
                    nextItem.removeClass('banner-hide').addClass('banner-show').fadeIn(500);
                    duration = parseInt(nextItem.find('input[name=duration]').val());
                }
                if (!duration) {
                    duration = 5000;
                }
                if (banners1Enabled) {
                    banners1Timeout = window.setTimeout(function () {
                        displayNextBanner.call($banners[0]);
                    },duration + 500);
                }
            }
        }
    }
    
    //vyhladavanie podla definovaneho searchtype
    $('form.searchtypeForm').each(function () {
        var f = $(this);
        var selects = f.find('select');
        selects.each(function () {
            this.onchange = function () {
                f.find('.progress').show();
                f.submit();
                selects.attr('disabled','disabled');
            }
        });
    });
    
    //vyhladavanie podla aut
    $('form.carSearchForm').each(function () {
        var f = $(this);
        f.submit(function () {
            try {
                f.find('input[type=checkbox]:checked').each(function () {
                    var h = $('<input type="hidden" />');
                    h.attr('name', this.name);
                    h.val(this.value);
                    f.append(h);
                });
                f.find('input[type=checkbox]').attr('disabled', 'disabled');
                return true;
            } catch (e) {
                alert(e);
            }
            return false;
        });
        f.find('div.carSearch input').click(function () {
            if (this.checked) {
                f.find('div.carSearchSub-'+this.value).show();
            } else {
                f.find('div.carSearchSub-'+this.value).hide().find('input').removeAttr('checked');
            }
        }).each(function () {
            if (this.checked) {
                f.find('div.carSearchSub-'+this.value).show();
            }
        });
        f.find('input').click(function () {
            f.submit();
        });
    });
    
    //rychle vyhladavanie - prepinac len v danej kategorii
    var quickSearchDefaultAction = $('#quickSearchForm').attr('action');
    $('#quickSearchCategoryOpt').click(function () {
        if (this.checked) {
            $('#quickSearchForm').attr('action', $('#quickSearchCategoryLink').attr('href'));
        } else {
            $('#quickSearchForm').attr('action', quickSearchDefaultAction);
        }
    }).each(function () {
        if (this.checked) {
            $('#quickSearchForm').attr('action', $('#quickSearchCategoryLink').attr('href'));
        }
    });
    
    //znackovy formular v sidebare
    $('#sidebarBrandForm input[type=checkbox]').bind('click.brandchange',function () {
        var url = this.form.action;
        $(this.form).find('input:checked:not(:disabled)').each(function () {
            url += this.name + '=' + this.value + '&';
        });
        window.location = url;
    });
    $('#sidebarBrandForm a').bind('click.brandchange',function () {
        var chbx = $(this).closest('li').find('input');
        if (chbx.length) {
            if (chbx[0].checked) {
                chbx[0].checked = false;
            } else {
                chbx[0].checked = true;
            }
            chbx.trigger('click.brandchange');
            return false;
        } else {
            return true;
        }
    });
    
    //anketa
    $('a.AnketaHlasuj').click(function () {
        var rel = this.rel.split('|');
        var divko = $(this).closest('div.anketa');
        var loader = $('<div class="loader"></div>');
        loader.css({
                position: 'absolute',
                top: '0px',
                left: '0px',
                opacity: 0.8
        }).width(divko.width()).height(divko.height());
        divko.css({
            position: 'relative'
        }).append(loader);
        $.post('/anketa/hlasuj/',{
            anketaId: rel[0],
            odpoved: rel[1]
        },function (responseText) {
            divko.html(responseText);
        });
        return false;
    });
    
    //FACEBOOK applikacia
	$.getScript(document.location.protocol + '//connect.facebook.net/sk_SK/all.js');
});

