var isIE;
var webKit;
var hoverMode = true;
var stylishSelectIndexCounter = 1000;

$(document).ready(function () {
    isIE = $.browser.msie;
    webKit = $.browser.webkit;

    $.fn.watermarks();
    $.fn.footerSlide();
    $.fn.news({
        container: '.news-carousel',
        slideTime: 5
    });

    $('select.customs').sSelect({ ddMaxHeight: '150px' })
                       .each(function (index, element) {
                           $(element).parent('span.select').css('z-index', stylishSelectIndexCounter -= index);
                       });

    if ($('.gallery').length > 0) {
        $.fn.gallery({
            speedSlide: 1000,
            speedShow: 500,
            container: '.photo'
        });
    }
    if ($('.tabs').length > 0) {
        $.fn.tabs();
    }

    if ($('.tdis').length > 0) {
        $.fn.disable();
    }

    bindDatepickes();

    arrowSelect();
});

function arrowSelect() {

    $('.newListSelected .right').live('mousedown', function () {
        $(this).next('.SSContainerDivWrapper').show();
    });

}

function bindDatepickes() {
    $('input.calendar-field').each(function(index, elemnt) {
        var field = $(elemnt);
        field.datepicker({
                showOn: "button",
                buttonImage: "/Content/img/ui/iconCalendar.gif",
                buttonImageOnly: true,
                dateFormat: field.data("dateformat"),
                minDate: field.data("mindate"),
                maxDate: field.data("maxdate")
            });
    });
}

$(function () {
    RegisterBasketPopUp();
});

function ShowBasketPopUp(count) {
    $.fn.basketPopup({
        action: true,
        count: count
    });
    hoverMode = false;
    setTimeout('HideBasketPopUp();', 2000);

}

function HideBasketPopUp() {
    $.fn.basketPopup({
        action: false,
        count: 0
    });
    hoverMode = true;
}

function RegisterBasketPopUp() {
    $('.basket .middle').hover(function () {
        if ($('.clearfix', '.basket-popup').length == 0) { return false; }
        if (!hoverMode) return false;
        $.fn.basketPopup({
            action: true,
            count: 3
        });
    }, function () {
        if ($('.clearfix', '.basket-popup').length == 0) { return false; }
        $.fn.basketPopup({
            action: false,
            count: 0
        });
    });
}
function MakeWatermarks(container) {
    $.fn.watermarks(container);
}
(function ($) {
    $.fn.watermarks = function (container) {
        if (typeof container == 'undefined' || !container) {
            container = document;
        }
        else {
            container = document.getElementById(container);
        }
        //:text replaced with input[type=text] bacouse of Permission denied in IE
        $('input[type=text], textarea', container).each(function (index, element) {
            var watermarkText = $(element).data('default');
            var field = $(element);
            if (field.val() != watermarkText) {
                field.parent('span').addClass('focus');
            }
            else {
                field.parent('span').removeClass('focus');
            }
            field.focus(function () {
                if (field.val() == watermarkText) {
                    field.val('').parent('span').addClass('focus');
                }
            }).blur(function () {
                if (field.val() == '') {
                    field.val(watermarkText).parent('span').removeClass('focus');
                }
            });
        });
    };
})(jQuery);

(function ($) {
    $.fn.basketPopup = function (options) {
        var opts = $.extend(options);
        var lines = $('.basket-popup li.basketPopUpLine');
        lines.slice(0, opts.count).show();
        var basketPopup = $('.basket-popup');

        if (opts.action) {
            basketPopup.stop(true, true).fadeIn();
            $("#basketPopupCheckout").focus();
        } else {
            basketPopup.stop(true, true).fadeOut();
        }
    };
})(jQuery);

(function ($) {
    $.fn.footerSlide = function () {
        var $link = $('.sitemap h3 a');
        var $links = $('.sitemap h3 a, .subscribe h3');
        var $container = $('.topfooter');
        var $containerH = $('.topfooter h3');
        var $hMarginBottom = parseInt($containerH.css('margin-bottom').replace('px',''));
        var $hHeight = $containerH.height() + $hMarginBottom;
        $links.click(function () {
            $link.toggleClass('open');
            $container.toggleClass('open');
            if ($container.hasClass('open')) {
                $container.stop(true, true).animate({
                    height: '100%'
                });
            } else {
                $container.stop(true, true).animate({
                    height: $hHeight + 'px'
                });
            }
            return false;
        });
    };
})(jQuery);

(function ($) {
    $.fn.news = function (options) {
        var defaults = {
            container: '.news-carousel',
            slideTime: 5
        }, opts = $.extend(defaults, options);

        var $container = opts['container'];
        var $carousel = $('ul', $container);
        var $link = $('.next', $container);
        var countItem = $('li', $carousel).length;
        var withItem = $('li', $carousel).width();
        var activeItem = 1;
        var slideTime = opts['slideTime'];
        var rotateTimer;

        prepare();

        function prepare() {
            if (countItem > 1) {
                $('li:nth-child(' + countItem + ')', $carousel).clone().prependTo($carousel);
                $carousel.css('width', (withItem * (countItem + 1)));
                $carousel.css('left', -withItem);
                timer();
            }
        }

        function timer() {
            clearInterval(rotateTimer);
            rotateTimer = setInterval(function () {
                rotate();
            }, slideTime * 1000);
        }

        function rotate() {
            if ($carousel.is(':animated')) return false;
            clearInterval(rotateTimer);
            var leftPosition = $carousel.get(0).offsetLeft;
            activeItem++;

            if (activeItem > countItem) {
                activeItem = 1;
                $carousel.css('left', 0);
                $carousel.animate({
                    left: -withItem
                }, function () {
                    if (countItem > 1) timer();
                });
                return false;
            }
            $carousel.animate({
                left: leftPosition - withItem
            }, function () {
                if (countItem > 1) timer();
            });
        }

        $link.click(function () {
            rotate();
            return false;
        });
    };
})(jQuery);


$.easing.jswing = $.easing.swing;
$.extend($.easing,
{
    def: 'easeOutQuad',
    swing: function (x, t, b, c, d) {
        return $.easing[$.easing.def](x, t, b, c, d);
    },
    easeOutQuad: function (x, t, b, c, d) {
        if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b;
        return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
    }
});


(function ($) {
    $.fn.gallery = function (options) {
        var defaults = {
            container: '.news-carousel',
            speedShow: 500,
            speedSlide: 1000
        }, opts = $.extend(defaults, options);

        var $container = opts['container'];
        var $gallery = $('.gallery', $container);
        var $paging = $('.navigation-gallery', $container);
        var $prev = $('.prev', $container);
        var $next = $('.next', $container);
        var $zoom = $('.zoom');

        $('li', $gallery).hide();
        $('li', $paging).hide();
        $prev.addClass('disable');
        $next.addClass('disable');

        var countItem = $('li', $gallery).length;
        var widthItem = $($container).width();
        var widthPaging = $('li', $paging).width() + 25;
        var loaded = 0;
        var activeItem = 1;
        var speedSlide = opts['slideTime'];
        var speedShow = opts['speedShow'];

        var $preloader = $('.preloader', $container);

        prepare();

        function prepare() {
            if (countItem == 1) {
                $preloader.hide();
                if (isIE) {
                    $('li', $gallery).show(0);
                } else {
                    $('li', $gallery).fadeIn(speedShow);
                }
                return false;
            }
            $gallery.css('width', countItem * widthItem);
            $paging.css('width', countItem * widthPaging);

            $preloader.hide();
            if (isIE) {
                $('li', $gallery).show(0);

                $('li:nth-child(' + activeItem + ')', $paging).addClass('active');
                $('li', $paging).show(0);
            } else {
                $('li', $gallery).fadeIn(speedShow);

                $('li:nth-child(' + activeItem + ')', $paging).addClass('active');
                $('li', $paging).fadeIn(speedShow);
            }
            if (countItem > 1) {
                $next.removeClass('disable');
            }
        }

        var shiftGallery;
        var shiftPaging;

        function rotate(activeItem) {
            if ($('li', $gallery).is(':animated')) return false;

            if (activeItem >= countItem) { $next.addClass('disable'); }
            else { $next.removeClass('disable'); }

            if (activeItem <= 1) { $prev.addClass('disable'); }
            else { $prev.removeClass('disable'); }

            shiftGallery = widthItem * (activeItem - 1);
            shiftPaging = widthPaging * (activeItem - 1);

            $zoom.attr('href', $('li:nth-child(' + activeItem + ') a', $gallery).attr('href'));

            $gallery.stop(true, true).animate({
                left: -shiftGallery
            }, {
                duration: 1000,
                easing: 'easeOutQuad'
            });

            $('li.active', $paging).removeClass('active');
            $('li:nth-child(' + activeItem + ')', $paging).addClass('active');
            if (countItem <= 4) {return false}
            if (activeItem > 2 && activeItem < countItem - 1 && countItem > 1) {
                $paging.animate({
                    left: -widthPaging * (activeItem - 2)
                });
            }

            if (activeItem == countItem - 1) {
                $paging.animate({
                    left: -widthPaging * (activeItem - 3)
                });
            }

            if (activeItem == 2) {
                $paging.animate({
                    left: 0
                });
            }
        }

        $prev.live('click', function () {
            activeItem--;
            if (activeItem <= 0) { activeItem = 1; return false; }
            rotate(activeItem);
        });
        $next.live('click', function () {
            activeItem++;
            if (activeItem > countItem) { activeItem = countItem; return false; }
            rotate(activeItem);
        });
        $('img', $paging).click(function () {
            activeItem = $(this).parent('li').index() + 1;
            rotate(activeItem);
        });
    };
})(jQuery);

(function ($) {
    $.fn.tabs = function () {
        var $container = $('.tabs');
        var $navigation = $('.tabs-nav', $container);
        var $content = $('.tabs-content', $container);
        var activeTab;

        $('li', $navigation).click(function () {
            activeTab = $(this).index();
            change(activeTab);
        });

        function change(activeTab) {
            $('li.active', $navigation).removeClass('active');
            $('li:eq(' + activeTab + ')', $navigation).addClass('active');
            $('.tabs-content > li.active').removeClass('active');
            $('.tabs-content > li:eq(' + activeTab + ')').addClass('active');
        }
    };
})(jQuery);

(function ($) {
    $.fn.popup = function (options) {
        var defaults = {
            popup: '.popup',
            overlay: '.overlay',
            close: '.close',
            action: 'show',
            speedOverlay: 500,
            speedPopup: 300,
            scrollTop: true
        };
        var ie9OrHigher = parseInt($.browser.version) >= 9;
        var opts = $.extend(defaults, options);
        if (opts.action == 'show') {

            show(opts.popup);
            if (!ie9OrHigher && opts.scrollTop) {
                $("html,body").scrollTop(10);
            }
        } else {
            hide(opts.popup);
        }

        function show() {
            opts.speedOverlay = 0;
            opts.speedPopup = 0;
            var documentH = getDocHeight();
            $(opts.overlay).css('height', documentH);
            if (ie9OrHigher) {
                $(opts.overlay).fadeIn(opts.speedOverlay);
            }
            else {
                $(opts.overlay).show();
            }

            var popupH = $(opts.popup).outerHeight();
            $(opts.popup).css('margin-top', -(popupH / 2))
                         .insertBefore(opts.overlay);
            if (ie9OrHigher) {
                $(opts.popup).fadeIn(opts.speedPopup);
            }
            else {
                $(opts.popup).show();
            }
        }

        function hide() {
            if (ie9OrHigher) {
                $(opts.overlay).fadeOut(opts.speedOverlay);
                $(opts.popup).fadeOut(opts.speedPopup);
            }
            else {
                $(opts.overlay).hide();
                $(opts.popup).hide();
            }
        }
        
        function getDocHeight() {
            return Math.max(
                Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
                Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
                Math.max(document.body.clientHeight, document.documentElement.clientHeight)
            );
        }

        $(opts.close, opts.popup).live('click', function () {
            hide(opts.popup);
        });
    };
})(jQuery);

(function ($) {
    $.fn.disable = function () {
        var toggleRelatedElementFor = function (elem, disable) {
            var relElems = $(elem).data('class');
            $(relElems).each(function (index, relElem) {
                $(relElem).toggleClass('disable', disable);
                var select = $('select', relElem);
                if (select.length > 0) {
                    var validator = $('.errormessage[validatable][ddltovalidate=' + select.attr('id') + ']');
                    if (validator.length > 0) {
                        validator.attr('validatable', !disable);
                        if (disable) {
                            validator.hide();
                        }
                    }
                }
            });
        };

        $('.tdis:radio').change(function () {
            toggleRelatedElementFor(this, false);
        }).filter(':checked').each(function (index, radio) {
            toggleRelatedElementFor(radio, false);
        });

        $('.todis:radio').change(function () {
            toggleRelatedElementFor(this, true);
        });
    };
})(jQuery);
//Product
$(function () {
    calc();
    //calcAll();
});
function Calculate() {
    var input = $('.sizeContainer .item input');
    var value = input.val();
    
    if (value == "" || !IsNumeric(value))
        value = 0;
    var parent = input.parent().parent();
    var priceVal = parent.find('#price').val();
    var price = parseFloat(priceVal.replace(",", "."));
    var totalPrice = parent.find('.totalPrice');
    //console.debug("TotalPrice: " + totalPrice);
    var hidden = parent.find('#totalprice');
    var valTo = ((parseFloat(price) * value).toFixed(2)).replace(".", ",");
    totalPrice.text(valTo);
    hidden.val(valTo);
    //calcAll();
}
function calc() {
    $('.sizeContainer .item input').keyup(function () {
        Calculate();
    });
}
function calcAll() {
    var totalPrice = 0.0;
    $("span.sizeContainer input[id^='totalprice']").each(function () {
        totalPrice += parseFloat($(this).val().replace(",", "."));
    });
    $("span.priceValue").html(totalPrice.toFixed(2).toString().replace(".", ","));
}
function IsNumeric(sText) {
    var validChars = "0123456789";
    var isNumber = true;
    var char;

    if (sText.length > 0) {
        for (i = 0; i < sText.length && isNumber == true; i++) {
            char = sText.charAt(i);
            if (validChars.indexOf(char) == -1) {
                isNumber = false;
            }
        }
        return isNumber;
    }
    else {
        return false;
    }
}

function ReadReviews() {
    // get target link to navigate to
    var trgt = jQuery("li[name='reviews']");
    var trgtHeader = jQuery("li[name='reviewsTabHeader']");

    var activeTab = jQuery("li[class='active']");
    if (activeTab)
        activeTab.removeClass('active');

    if (trgt.is(":hidden")) {
        trgtHeader.addClass('active');
        trgt.addClass('active');
    }

    var targetOffset = trgt.offset().top + trgt.height();
    $('html').animate({ scrollTop: targetOffset }, 500);
}
