/* AJAX ERROR */
$(document).ajaxError(function (request,settings,e) {
    alert('Error requesting URL: '+e.url);
});
/* 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 popup okno
jQuery.fn.homepopup = function () {
    var popup = this.eq(0);
    //overlay
    var overlay = $('<div id="homepopupOverlay"></div>');
    var bodyW = $(document).width();
    var bodyH = $(document).height();
    overlay.width(bodyW);
    overlay.height(bodyH);
    popup.before(overlay);
    //animacia na popup
    var desiredHeight = popup.height();
    popup.find('> *').hide();
    popup.height(1).show();
    popup.css({
        top: (($(window).height() - desiredHeight) / 2 + $(document).scrollTop()) + 'px',
        left: (($(window).width() - popup.width()) / 2 + $(document).scrollLeft()) + 'px'
    });
    popup.animate({
        height: desiredHeight + 'px'
    },{
        duration: 500,
        complete: function () {
            $(this).find('> *').show();
        }
    });
    popup.find('.close').click(function () {
        popup.hide();
        overlay.remove();
        //nastavime cookies
        if ($('#homepopupNomore').is(':checked')) {
            $.get(Router('system/current-time/'),function (curtime) {
                jQuery.cookie('popup1', curtime, {
                    expires: 100,
                    path: '/'
                });
            })
        }
    });
    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;
    }
};

var brandsAnimationOnoff = 1;
$(function(){
	//hinty vo formularoch
	$('input.hint').inputHint();
	//vypnut autocomplete vo formularoch
	$('input.autocompleteoff').attr('autocomplete','off');
	//zebra tabulky + highlight
    $('table.zebra').zebraTable();
    $('table.highlight').highlightTable();
	//brands menu
	//animacne obrazky znaciek
    eval('var brandImagesJson = '+$('#brandImagesJson').val()+';');
    $('#supertopBanner2').append('<div id="supertopBanner2Image"></div>');
	$('#brands li').hover(function () {
        var a = $(this).find('>a');
        var brand = a.attr('rel');
        $(this).addClass(brand + '-hover');
        var brandImageUrl = brandImagesJson['brand_'+a.attr('id').substring(10)];
        if (brandImageUrl) {
            $('#supertopBanner2Image').empty().append('<img src="'+brandImageUrl+'" alt="'+a.attr('rel')+'" />');
        }
    },function () {
        var brand = $(this).find('>a').attr('rel');
        $(this).removeClass(brand + '-hover');
        $('#supertopBanner2Image').empty()
    });
    //rychle vyhladavanie - vysunutie rozsireneho
    
    
    
    //rychle vyhladavanie - vysunutie rozsireneho
    var form = $('#quickSearchForm');
    var formNew = $('<form></form>');
    formNew.attr({
            method: form.attr('method'),
            action: form.attr('action'),
            id: 'quickSearchFormAdvanced'
    });
    $('#quickSearchOptions').appendTo($('body')).wrap(formNew);
    var quickSearchOptions_protect = false;
    var quickSearchOptions_visible = false;
    quickSearchOptions_updatePosition();
    $(window).resize(quickSearchOptions_updatePosition);
    
    $('#quickSearchQueryInput').mouseover(function () {
        var qsb = $('#quickSearchOptions');
        if (!quickSearchOptions_visible) {
            quickSearchOptions_visible = true;
            qsb.slideDown('fast');
        }
    });
    $('#quickSearchOptions').mouseleave(function () {
        if (!quickSearchOptions_protect) {
            quickSearchOptions_visible = false;
            quickSearchOptions_protect = false;
            $('#quickSearchOptions').slideUp('fast');
        }
    });
    $('#quickSearchOptions').click(function (e) {
        if (!$(e.target).is('#quickSearchOptionsClose')) {
            quickSearchOptions_protect = true;
        }
    });
    $('#quickSearchQuery').focus(function () {
        var qsb = $('#quickSearchOptions');
        if (!quickSearchOptions_visible) {
            quickSearchOptions_visible = true;
            qsb.slideDown('fast');
        }
    });
    $('#quickSearchOptionsClose').click(function () {
        quickSearchOptions_visible = false;
        quickSearchOptions_protect = false;
        $('#quickSearchOptions').slideUp('fast');
    });
    
    // var form = $('#quickSearchForm');
    // var formNew = $('<form></form>');
    // formNew.attr({
    //         method: form.attr('method'),
    //         action: form.attr('action'),
    //         id: 'quickSearchFormAdvanced'
    // });
    // $('#quickSearchOptions').appendTo($('body')).wrap(formNew);
    // quickSearchOptions_updatePosition();
    // $('#quickSearchQueryInput').bind('mouseenter',function () {
    //     var qsb = $('#quickSearchOptions');
    //     if (qsb.is(':hidden')) {
    //         qsb.slideDown('fast');
    //     }
    // });
    // $('#quickSearchQuery').bind('focus',function () {
    //     var qsb = $('#quickSearchOptions');
    //     if (qsb.is(':hidden')) {
    //         qsb.slideDown('fast');
    //     }
    // });
    // $('#quickSearchForm').bind('mouseleave',function (e) {
    //     alert($(e.currentTarget).attr('id'));
    //     if (!$(e.currentTarget).is('#quickSearchOptions')) {
    //         var qsb = $('#quickSearchOptions');
    //         if (qsb.is(':visible')) {
    //             qsb.slideUp('fast');
    //         }
    //     }
    // });
    
    $('#quickSearchForm').submit(function () {
        $('#quickSearchFormAdvanced').submit();
        return false;
    });
    $('#quickSearchFormAdvanced').submit(function () {
        $('#quickSearchQueryAdvanced').val($('#quickSearchQuery').val());
        return true;
    });
    $('#quickSearchQueryInput').one('click',function () {
        this.select();
    });
    $('#quickSearchOptionsClose').click(function () {
        $('#quickSearchOptions').slideUp('fast');
    });
    
    //homepopup
    $('#homepopup').homepopup();
    
    //animacia znaciek
    //prisposobenie sirky znaciek
    $('#brands').each(function () {
        var sirka = 0;
        $(this).find('li').each(function () {
            var w = $(this).width();
            sirka += w;
            $(this).attr('width', w);
        });
        $(this).width(sirka);
    });
    window.setTimeout(function () {
        brandsAnimation();
    },2000);
});

function quickSearchOptions_updatePosition() {
    var qsb = $('#quickSearchOptions');
    var qsi = $('#quickSearchQueryInput');
    var formOffset = qsi.offset();
    qsb.css({
            top: (formOffset.top + qsi.height() - 1) + 'px',
            left: formOffset.left + 'px'
    });
}

function brandsAnimation(curLeft) {
    if (typeof(curLeft) == 'undefined') {
        var curLeft = parseInt($('#brands').css('left'));
    }
    var firstW = parseInt($('#brands li:eq(0)').attr('width')); //atribut sa nastavuje pri inicializacii animacie
    var newLeft = curLeft - firstW;
    // $('#brands').css('left',newLeft + 'px');
    $('#brands').animate({
        left: newLeft + 'px'
    },1500, function () {
        newLeft += firstW;
        $('#brands li:eq(0)').appendTo($('#brands'));
        $('#brands').css('left',newLeft + 'px');
        window.setTimeout(function () {
            brandsAnimation(newLeft)
        },3000);
    });
}