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

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

$(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');
    if (countdown.length) {
        var timeleft = parseInt(countdown.find('input[name=time]').val());
        var digits = countdown.find('span');
        function displayCountdown(timeleft) {
            if (timeleft < 0) {
                timeleft = 0;
                digits.removeClass().addClass('digit-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);
            if (parsetime.h <= 9) {
                digits.eq(0).removeClass().addClass('digit-0');
                digits.eq(1).removeClass().addClass('digit-' + parsetime.h);
            } else {
                digits.eq(0).removeClass().addClass('digit-' + Math.min(Math.floor(parsetime.h / 10),9));
                digits.eq(1).removeClass().addClass('digit-' + (parsetime.h % 10));
            }
            if (parsetime.m <= 9) {
                digits.eq(2).removeClass().addClass('digit-0');
                digits.eq(3).removeClass().addClass('digit-' + parsetime.m);
            } else {
                digits.eq(2).removeClass().addClass('digit-' + Math.floor(parsetime.m / 10));
                digits.eq(3).removeClass().addClass('digit-' + (parsetime.m % 10));
            }
            if (parsetime.s <= 9) {
                digits.eq(4).removeClass().addClass('digit-0');
                digits.eq(5).removeClass().addClass('digit-' + parsetime.s);
            } else {
                digits.eq(4).removeClass().addClass('digit-' + Math.floor(parsetime.s / 10));
                digits.eq(5).removeClass().addClass('digit-' + (parsetime.s % 10));
            }
            //rekurzia
            window.setTimeout(function () {
                timeleft -= 1;
                displayCountdown(timeleft);
            }, 1000);
        }
        displayCountdown(timeleft);
    }
    
    var saleproductscount = $('#saleproductscount');
    if (saleproductscount.length) {
        var total = parseInt(saleproductscount.find('input[name=total]').val());
        var digits = saleproductscount.find('span');
        function displaySaleproductscount(total, currentcount, step) {
            if (total > 999) {
                total = 999;
            }
            if (!currentcount) {
                currentcount = 0;
            }
            if (currentcount > total) {
                currentcount = total;
            }
            digits.eq(0).removeClass().addClass('digit-' + Math.floor(currentcount / 100));
            digits.eq(1).removeClass().addClass('digit-' + Math.floor((currentcount % 100) / 10));
            digits.eq(2).removeClass().addClass('digit-' + Math.floor((currentcount % 10)));
            if (currentcount < total) {
                //rekurzia
                window.setTimeout(function () {
                    // displaySaleproductscount(total, currentcount + 1);
                    // aby nebolo vela cyklov, tak to aproxymujeme na XX cyklov
                    displaySaleproductscount(total, currentcount + step, step);
                }, 100);
            } else {
                //este raz napocitame produkty
                window.setTimeout(function () {
                    displaySaleproductscount(total, 0, step);
                }, 20000);
            }
        }
        displaySaleproductscount(total, 0, Math.ceil(total / 20));
    }
    
    // //hover na znacky
    // $('#sidepanel-brands li.brand a').hover(function () {
    //     var li = $(this);
    //     var himg = li.find('img.hoverimage');
    //     var img = li.find('img.image');
    //     var himgsrc = himg.attr('src');
    //     var imgsrc = img.attr('src');
    //     img.attr('src', himgsrc);
    //     himg.attr('src', imgsrc);
    // }, function () {
    //     var li = $(this);
    //     var himg = li.find('img.hoverimage');
    //     var img = li.find('img.image');
    //     var himgsrc = himg.attr('src');
    //     var imgsrc = img.attr('src');
    //     img.attr('src', himgsrc);
    //     himg.attr('src', imgsrc);
    // });
    
    //sidepanely
    var sidebarContentHeight = Math.min($('#contentpanel').outerHeight() + $('#footerpanel').outerHeight(), 800);
    (function () {
        //znacky
        var brands = $('#sidepanel-brands div.sidepanel-content');
        brands.height(sidebarContentHeight - 14);
        //vyska vnutornej animacie
        var brandsAnim = $('#sidepanel-brands-animation');
        var brandsAnimContent = brandsAnim.find('ul');
        var brandsAnimHeight = sidebarContentHeight - 14 - brands.find('div.title').outerHeight() - brands.find('div.allbrands').outerHeight() - 28;
        brandsAnim.height(brandsAnimHeight).css({
            overflow: 'hidden',
            position: 'relative'
        });
        //spustime animaciu znaciek
        var brandsAnimContentHeight = brandsAnimContent.height();
        if (brandsAnimHeight < brandsAnimContentHeight) {
            brandsAnimContent.css({
                position: 'absolute',
                top: '0px',
                left: '0px',
                height: brandsAnimContentHeight,
                width: brandsAnimContent.width(),
            });
            var brandsAnimItemHeight = brandsAnimContent.find('li:eq(0)').outerHeight();
            var brandsAnimTop = 0;
            var brandsAnimEnabled = true;
            function brandsAnimMove() {
                if (brandsAnimEnabled) {
                    brandsAnimTop -= 1;
                    brandsAnimContent.css('top', brandsAnimTop + 'px');
                    //presun znaciek na koniec - otocime kolecko
                    if (brandsAnimContentHeight + brandsAnimTop < brandsAnimHeight) {
                        var item1 = brandsAnimContent.find('li:eq(0)');
                        brandsAnimContent.append(item1);
                        brandsAnimTop += item1.outerHeight();
                        brandsAnimContent.css('top', brandsAnimTop + 'px');
                    }
                }
                window.setTimeout(brandsAnimMove, 50);
            }
            brandsAnim.hover(function () {
                brandsAnimEnabled = false;
            }, function () {
                brandsAnimEnabled = true;
            });
            //zaciname animovat znacky az po 2 sekundach
            window.setTimeout(brandsAnimMove, 2000);
            
            //brands draggable
            brandsAnimContent.draggable({
                axis: 'y',
                create: function (event, ui) {
                    brandsAnimContent.data('containerh', brandsAnimHeight);
                    brandsAnimContent.data('contenth', brandsAnimContent.width());
                },
                stop: function (event, ui) {
                    brandsAnimTop = ui.position.top;
                    // //vratenie na kraj
                    // if (ui.position.top > 0) {
                    //     brandsAnimContent.animate({
                    //         top: '0px'
                    //     },{
                    //         duration: 300
                    //     });
                    // } else {
                    //     var containerh = brandsAnimContent.data('containerh');
                    //     var contenth = brandsAnimContent.data('contenth');
                    //     if (Math.abs(ui.position.top) > contenth - containerh) {
                    //         brandsAnimContent.animate({
                    //             top: -(contenth - containerh) + 'px'
                    //         },{
                    //             duration: 300
                    //         });
                    //     }
                    // }
                }
            });
        }
        
        //facebook
        function placeFbFrame(container, w, h) {
            var fbframe = $('<iframe></iframe>');
            fbframe.attr('src', 'http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fcapricornkosice&width='+(w+2)+'&colorscheme=light&show_faces=true&stream=false&header=false&height='+(h+2));
            fbframe.attr('scrolling', 'no');
            fbframe.attr('frameborder', 0);
            fbframe.attr('allowTransparency', 'true');
            fbframe.css({
                width: w + 'px',
                height: h + 'px',
                position: 'relative',
                top: '-1px',
                left: '-1px',
                overflow:'hidden'
            });
            container.height(h).width(w).empty().append(fbframe);
        }
        
        var spfb = $('#sidepanel-fb');
        var ww = $(window).width();
        var fbw_side = 190;
        var fbh_side = sidebarContentHeight - 10;
        var fbw_bottom = 970;
        var fbh_bottom = 255;
        var bodzlomu = 1340;
        spfb.show();
        if (ww >= bodzlomu) {
            spfb.addClass('side');
            placeFbFrame(spfb.find('div.sidepanel-content'), fbw_side, fbh_side);
            $('#pagepanel, #toppanel').width(1340);
        } else {
            placeFbFrame(spfb.find('div.sidepanel-content'), fbw_bottom, fbh_bottom);
            $('#pagepanel, #toppanel').width(1140);
        }
        $(window).resize(function () {
            //place fb frame
            var ww = $(window).width();
            if (ww >= bodzlomu && !spfb.is('.side')) {
                spfb.addClass('side');
                placeFbFrame(spfb.find('div.sidepanel-content'), fbw_side, fbh_side);
                $('#pagepanel, #toppanel').width(1340);
            } else if (ww < bodzlomu && spfb.is('.side')) {
                spfb.removeClass('side');
                placeFbFrame(spfb.find('div.sidepanel-content'), fbw_bottom, fbh_bottom);
                $('#pagepanel, #toppanel').width(1140);
            }
        });
    })()
});

