/*------------------------------------------------------------------
 * Project	 :  Aptdeco
 * Version	 :  1.1
 * Last change: 22.01.14
 * Changed by : @ElmahdiMahmoud
 -------------------------------------------------------------------*/

$(document).ready(function() {

    /* [ custom scrollbar ] */
    var dragging = false;
    var clientY = 0;

    $(document).ready(function(event) {

        var catSidebar = $('.cat-sidebar.hide-mid');
            catSidebar.removeClass('hide-mid');

        $(".scrollable").each(function() {
            var viewportHeight = $(this).outerHeight();
            var totalHeight = $(this).prop("scrollHeight");
            var scrollUnitHeight = (viewportHeight / totalHeight) * viewportHeight;
            if (viewportHeight == totalHeight) {
                $(this).parent('.scrollable-holder').addClass('no-scroll');
            }
            $(this).find(".scroll span").height(scrollUnitHeight);
        });
        catSidebar.addClass('hide-mid');

        $(document).on('mousewheel', '.scrollable', function(event) {
            var scrollLocation = $(this).find(".scroll span").position().top;
            moveScrollTo($(this), scrollLocation - (event.deltaY * 10));

            event.preventDefault();
            return false;
        });

        $(window).on("mouseup", function(event) {
            if (dragging) {
                dragging = false;
                $(".scrolling").removeClass("scrolling");

                event.preventDefault();
                return false;
            }
        });

        $(".scrollable .scroll span").on("mousedown", function(event) {
            clientY = event.clientY - $(this).position().top;
            dragging = true;
            $(this).parents(".scrollable").addClass("scrolling");

            event.preventDefault();
            return false;
        });

        $(document).on("click", ".scroll", function(event) {
            if ($(event.target).is("span")) {
                return;
            }

            var scrollPosition = event.clientY - 15;
            moveScrollTo($(this).parents(".scrollable"), scrollPosition);
        });

        $(window).on("mousemove", function(event) {
            if (dragging) {
                var scrollPosition = event.clientY - clientY;
                moveScrollTo($(".scrolling"), scrollPosition);

                event.preventDefault();
            }
        });
    });

    function moveScrollTo(parent, scrollPosition) {
        if (parent.length > 0) {
            var viewportHeight = parent.outerHeight();
            var limitedViewportHeight = viewportHeight - parent.find(".scroll span").height();

            var totalHeight = parent.prop("scrollHeight");

            if (scrollPosition < 0) {
                scrollPosition = 0;
            }

            var scrollSpanPosition = scrollPosition;

            if (scrollSpanPosition > viewportHeight - parent.find(".scroll span").height()) {
                scrollSpanPosition = viewportHeight - parent.find(".scroll span").height();
            }

            if (scrollPosition > viewportHeight) {
                scrollPosition = viewportHeight;
            }

            parent.find(".scroll span").css("top", scrollSpanPosition);

            parent.find(".scroll").css("top", (scrollSpanPosition / viewportHeight) * totalHeight);

            parent.scrollTop((scrollSpanPosition / viewportHeight) * totalHeight);
        }
    }

    $('.menu-mid').on('click', function(e) {
        e.stopPropagation();
        var $this = $(this),
                _href = $this.attr('href');

        $(_href).toggleClass('hide-mid');
        return false;
    });


    $('.form-field').blur(function() {
        if ($(this).val()) {
            $(this).addClass('filled');
        }
    });

    $('.form-field').on('click', function() {
        $(this).removeClass('filled');
    });


    $(window).resize(function() {
        if ($("html").hasClass("ie8") && $(window).width() >= 1170) {
            $('html > body').addClass('large-screen');
            $('html > body').removeClass('desktop');
        } else {
            $('html > body').addClass('desktop');
            $('html > body').removeClass('large-screen');
        }
    });
    $(window).resize();

    /* floatedScroll ======================================== */
    /* $(function() {
     
     var $sidebar   = $(".stick-sidebar"), 
     $window    = $(window),
     offset     = $sidebar.offset(),
     topPadding = 15;
     
     $window.scroll(function() {
     $sidebar.css('margin-top', 
     ($window.scrollTop() > offset.top && $window.width() > 998) ? ($window.scrollTop() - offset.top + topPadding) : 0
     );
     });
     
     });*/


    /* / Show target / */
    $('.show-targets .show-targ').on('click', function() {
        $('.to-guest,.to-register,.to-account').addClass('hidden');
        $('.' + $(this).attr('data-targ')).removeClass('hidden');
        return false;
    });

    /*Qty*/
    $(function() {

        set_($('#three-max'), 3);  //return 3 maximum digites
        function set_(_this, max) {
            var block = _this.parent();

            block.find(".increase").click(function() {
                var currentVal = parseInt(_this.val());
                if (currentVal != NaN && (currentVal + 1) <= max) {
                    _this.val(currentVal + 1);
                }
            });

            block.find(".decrease").click(function() {
                var currentVal = parseInt(_this.val());
                if (currentVal != NaN && currentVal != 0) {
                    _this.val(currentVal - 1);
                }
            });
        }
    });

    $(".item-available").on('click', function() {
        $('#order-item-params').show('slow');
    });
    $(".item-not-available").on('click', function() {
        $('#order-item-params').hide('slow');
    });




    //shop-by-category
    //shop-by-brand

    $('.shop-by-brand').on('click', function() {
        var
                featBrands = $('.feat-brands'),
                featProdus = $('.feat-produs');
        featBrands.show('slow');
        featProdus.hide();

        $('html,body').animate({
            scrollTop: $(this.hash).offset().top
        }, 1000);

        return false;
    });

    $('.shop-by-category').on('click', function() {
        var
                featBrands = $('.feat-brands'),
                featProdus = $('.feat-produs');
        featBrands.hide();
        featProdus.show('slow');

        $('html,body').animate({
            scrollTop: $(this.hash).offset().top
        }, 1000);

        return false;
    });

    /* Responsive sidebar ======================================== */
    $(".filter-by").on('click', function(fby) {
        var sideBar = $("#sideWrapper,#sidebar,#sidebar-user"),
                innerSide = $("#sidebar,#sidebar-user");

        sideBar.animate({
            left: '0'
        }, 600, 'easeInOutCirc');
        $('.mainContent').animate({
            left: '275px'
        }, 300, 'easeInOutCirc');

        fby.stopPropagation();
    });

    /* Close the sidebar ========================================= */
    $(".closeSidebar, html").on('click', function() {
        var browver = $.browser.version;
        if (window.innerWidth > 1000) {
            return;
        }
        if (browver == '8.0') {
            return;
        }
        var sideBar = $("#sideWrapper,#sidebar,#sidebar-user"),
                innerSide = $("#sidebar,#sidebar-user");
        sideBar.animate({
            left: '-500px'
        }, 300, 'easeInOutCirc');
        $('.mainContent').animate({
            left: '0'
        }, 600, 'easeInOutCirc');

        //cs.stopPropagation();
    });


    $("#sidebar, .mainContent .control-label").on('click', function(ssc) {
        ssc.stopPropagation();
    });

    /* increase gallery thumbnail ================================ */
    $(function() {

        $('#category').on("mouseover", ".gallery-images div", function() {
            var ww = $(window).width();
            if (ww < 1024)
                return;
            $(this).stop().animate({
                marginTop: '-10px',
                marginLeft: '-10px',
                width: '335px',
                height: '260px'
            }, 1000, 'easeOutElastic').css('z-index', '10');
        });

        $('#category').on("mouseout", ".gallery-images div", function() {
            var ww = $(window).width();
            if (ww < 1024)
                return;
            $(this).stop().animate({
                marginTop: '0px',
                marginLeft: '0px',
                width: '294px',
                height: '245px'
            }, 900, 'easeOutElastic').css('z-index', '0');
        });

        /*$('.gallery-images div').hover(
         //increate on hover only for desktop    
         function() {
         var ww = $(window).width();
         if (ww < 1024) return;
         $(this).stop().animate({
         marginTop: '-10px',
         marginLeft: '-10px',
         width: '335px', 
         height: '260px'
         }, 1000, 'easeOutElastic').css('z-index', '10');
         },
         //return false for responsive        
         function() {
         var ww = $(window).width();
         if (ww < 1024) return;
         $(this).stop().animate({
         marginTop: '0px',
         marginLeft: '0px',
         width: '294px',
         height: '245px'
         }, 900, 'easeOutElastic').css('z-index', '0');
         });*/
    });


    /* Smooth scroll to the video player ========================= */
    $("#getvideo").click(function(event) {
        event.preventDefault();
        $('html,body').animate({
            scrollTop: $(this.hash).offset().top
        }, 1500);
        return false;
    });

    /* Smooth scroll to join us field ============================ */
    var bubble = $(".bubble img");
    $("#join-us").click(function(join) {
        join.preventDefault();
        $('html,body').animate({
            scrollTop: $(this.hash).offset().top
        }, 1500);
        bubble.hide('slow');
        $(".bubble img").show(1400).delay(20000);
        return false;
    });

    /* color picker ============================================== */
    $(".picolors").click(function() {
        if ($(this).find(':checkbox').prop('disabled')) {
            return;
        }
        var checkbox = $(this).find(':checkbox'),
                isChecked = checkbox.is(':checked');
        checkbox.attr('checked', !isChecked);
        if (!isChecked) {
            $(this).addClass("pickedColors")
        } else {
            $(this).removeClass("pickedColors");
        }
        checkbox.trigger("change");
    });
    $(".picolors, .picolor").hover(function() {
        if ($(this).find(':checkbox').prop('disabled')) {
            return;
        }
        $(this).css('z-index', '5').stop().animate({
            marginLeft: '-2px',
            marginTop: '-3px',
            width: '28px',
            height: '28px'
        }, 200);
    }, function() {
        $(this).stop().animate({
            marginLeft: '0px',
            marginTop: '0px',
            width: '22px',
            height: '22px'
        }, 200).css('z-index', '0');
    });

    $(".picolor").on('click touchstart',function() {
        var _this = $(this),
                block = _this.parent().parent();

        block.find(':radio').attr('checked', false);
        block.find(".picolor").removeClass('pickedColor');
        block.find(".picolor").stop().animate({
            marginLeft: '0px',
            marginTop: '0px',
            width: '22px',
            height: '22px'
        }, 200).css('z-index', '0');
        _this.addClass('pickedColor');
        _this.css('z-index', '5').stop().animate({
            marginLeft: '-2px',
            marginTop: '-3px',
            width: '28px',
            height: '28px'
        }, 200);
        _this.find(':radio').attr('checked', true);
    });

    /* getSignup ================================================= */
    $("#signup").click(function() {
        getSignup();
        return false;
    });

    function getSignup() {
        $('#sign-in').animate({
            top: '-400px',
            opacity: '0'
        }, 1000, "easeOutExpo");
        $('#sign-in').css('position', 'absolute');
        $("#sign-up").animate({
            opacity: '1'
        }, 400);
        $("#sign-up").css('display', 'block');
    }

    /* Checkout ================================================== */
    $("#billing-address .check-box").click(function() {
        if ($("#billing-address .check-box").hasClass('checkedBox')) {
            $(".new-shipping-address").fadeIn();
            $(".use-shipping-address").css('display', 'none');
        } else {
            $(".new-shipping-address").css('display', 'none');
            $(".use-shipping-address").fadeIn();
        }
        return false;
    });
    $(".getallCategories div").hide();
    $('.getallCategories div:first').slideDown('slow');
    $(".showall-categories").click(function() {
        $('.getallCategories div').slideDown('slow');
        return false;
    });

    /* getSignin ================================================= */
    $("#signin").click(function() {
        getSignin();
        return false;
    });

    function getSignin() {
        $('#sign-in').animate({
            top: '0',
            opacity: '1'
        }, 1000, "easeOutExpo");
        $('#sign-in').css('position', 'relative');
        $("#sign-up").animate({
            opacity: '0'
        }, 400);
        $("#sign-up").css('display', 'none');
    }

    /* getSuccess ==================================================== */
    $("#sig-nup").click(function() {
        getSuccess();
        return false;
    });

    function getSuccess() {
        $('#sign-up').css('display', 'none');
        $('#success-sign').show("clip", {
            direction: "vertical"
        }, 600);
    }

    /* shop-menu ================================================= */
    $(".secondary-menu li:not(.apt-support) a").hover(function() {
        var menuIndex  = jQuery(this).parent().index();
        var ulWidth    = jQuery(".list-cols ul").outerWidth(true);
        var ulPadLeft  = parseInt(jQuery(".list-cols ul").css("padding-left"));
        var menuOffset = parseInt(jQuery(this).offset().left);
        var padLeft    = parseInt(jQuery(".list-cols").css("padding-left"));
        var newMarLeft = menuOffset - padLeft - ulPadLeft - ulWidth * menuIndex;

        jQuery(".list-cols").css("margin-left", newMarLeft);

        $(".sub-cats").show();
    }, function() {
        $(".sub-cats").hide();
    });

    $(".sub-cats").hover(function() {
        $(".sub-cats").show();
    }, function() {
        $(".sub-cats").hide();
    });

    $('.shop-menu').click(function(et) {
        et.stopPropagation();
    });

    var
            shopMenu = $('.sub-cats'),
            listCols = shopMenu.find('.list-cols'),
            catColomn = listCols.find('ul'),
            colWidth = catColomn.outerWidth() + 35,
            totalCols = catColomn.length,
            listColsWidth = colWidth * totalCols,
            speed = 300,
            contentNum = 0,
            max_left = shopMenu.outerWidth() - listColsWidth;

    listCols.css('width', listColsWidth);

    var carouselMenu = function() {
        var $this = $(this);

        if ($this.hasClass('next')) {

            var mLeft = parseInt(listCols.css('margin-left')) - colWidth;

            if (contentNum < totalCols && mLeft > max_left) {
                listCols.stop().animate({
                    marginLeft: mLeft
                }, 300, 'easeOutBack');
                contentNum = contentNum + 1;
            } else {
                listCols.stop().animate({
                    marginLeft: max_left
                }, 300, 'easeOutBack');
                contentNum = contentNum / contentNum;
            }
        }

        else if ($this.hasClass('prev')) {
            if (contentNum > 1) {
                listCols.stop().animate({
                    marginLeft: '+=' + colWidth
                }, 300, 'easeOutBack');
                contentNum = contentNum - 1;
            } else {
                listCols.stop().animate({
                    marginLeft: '0'
                }, 300, 'easeOutBack');
                contentNum = 0;
            }
        }

        return false;
    };

    $('.shop-menu .control-btn').on('click', carouselMenu);



    /* RotateCarousel ============================================ */
    function RotateCarousel() {
        $("ul li:first-child").animate({
            marginLeft: -200
        }, 800, 'easeOutBack', function() {
            $("ul li:first-child").appendTo('ul');
            $("ul li:last-child").css('margin-Left', 0);
            RotateCarousel();
        });
    }
    /* accordion ================================================= */
    $(function() {
        $('#accordion .content').hide();
        $('#accordion h2, #accordion h3').click(function(tre) {
            var wh = $(window).height();
            if (wh < 950) {
                if ($(this).next().is(':hidden')) {
                    $('#accordion h2, #accordion h3').removeClass('activepenl').next('.content').slideUp();
                    $(this).toggleClass('activepenl').next('.content').slideDown();
                }
            } else {
                if ($(this).next().is(':hidden')) {
                    $(this).addClass('activepenl').next('.content').slideDown();
                } else if ($(this).next().is(':visible')) {
                    $(this).removeClass('activepenl').next('.content').slideUp();
                }
            }
            tre.stopPropagation();
        });
    });

    /* radio-btn ================================================= */
    $(".radio-btn").on("click", function() {
        var _this = $(this),
                block = _this.parent().parent();
        block.find('input:radio').attr('checked', false);//.change();
        block.find(".radio-btn").removeClass('checkedRadio');
        _this.addClass('checkedRadio');
        _this.find('input:radio').attr('checked', true).change();
    });

    /* Replacement =============================================== */
    $(".dropdown-menu li a").click(function() {
        var text = $(this).html();
        $(this).parent().parent().parent().find(".replacment").html(text);
    });

    /* pick-color ================================================ */
    $(".pick-color button").click(function() {
        var colorisSelected = $(this).hasClass("selectedColor");
        $(".pick-color button").removeClass("selectedColor");
        if (!colorisSelected) {
            $(this).addClass("selectedColor");
            $(this).find(".pick-color button").addClass("selectedColor");
        }
        return false;
    });

    /* datepicker ================================================ */
    $("#datepicker,#datepicker2,#datepicker3").datepicker({
        showOtherMonths: true,
        selectOtherMonths: true,
        showOn: "both",
        buttonImage: "images/calendar.png",
        buttonImageOnly: true,
        prevText: "",
        nextText: "",
        constrainInput: false
    });

    /* (Un)Select all checkbox =================================== */
    /*$("#setsel").on('click', function() {
     var text = $('.selct').text();
     $('.selct').text(text == "Select all" ? "Unselect all" : "Select all");
     $(".check-box").toggleClass("checkedBox");
     $('input[type=checkbox]').prop('checked', !($('.check-box input[type=checkbox]').is(':checked')));
     });*/

    /* Custom TimePicker ========================================= */
    $(window).load(function() {
        $('<table><tr><th colspan="5">Hours</th><th colspan="4">Minutes</th></tr><tr><td class="timaFormat brdr-btm" rowspan="3" >AM</td><td class="hrs am" data-time="AM" >01</td><td class="hrs am" data-time="AM" >02</td><td class="hrs am" data-time="AM" >03</td><td class="hrs am brdr-rit" data-time="AM" >04</td><td class="minutes" rowspan="2" >00</td><td class="minutes" rowspan="2" >05</td><td class="minutes" rowspan="2" >10</td><td class="minutes" rowspan="2" >15</td></tr><tr><td class="hrs am" data-time="AM" >05</td><td class="hrs am" data-time="AM" >06</td><td class="hrs am" data-time="AM" >07</td><td class="hrs am brdr-rit" data-time="AM" >08</td></tr><tr><td class="hrs am brdr-btm" data-time="AM" >09</td><td class="hrs am brdr-btm" data-time="AM" >10</td><td class="hrs am brdr-btm" data-time="AM" >11</td><td class="hrs am brdr-rit brdr-btm" data-time="AM" >12</td><td class="minutes" rowspan="2" >20</td><td class="minutes" rowspan="2" >25</td><td class="minutes" rowspan="2" >30</td><td class="minutes" rowspan="2" >35</td></tr><tr><td class="timaFormat" rowspan="3"  >PM</td><td class="hrs pm" data-time="PM" >01</td><td class="hrs pm" data-time="PM" >02</td><td class="hrs pm" data-time="PM" >03</td><td class="hrs pm brdr-rit" data-time="PM" >04</td></tr><tr><td class="hrs pm" data-time="PM" >05</td><td class="hrs pm" data-time="PM" >06</td><td class="hrs pm" data-time="PM" >07</td><td class="hrs pm brdr-rit" data-time="PM" >08</td><td class="minutes" rowspan="2" >40</td><td class="minutes" rowspan="2" >45</td><td class="minutes" rowspan="2" >50</td><td class="minutes" rowspan="2" >55</td></tr><tr><td class="hrs pm" data-time="PM" >09</td><td class="hrs pm" data-time="PM" >10</td><td class="hrs pm" data-time="PM" >11</td><td class="hrs pm" data-time="PM" >12</td></tr></table>').appendTo('#tpick,#tpick2,#tpick3,#tpick4,#tpick5,#tpick6');
    });
    //Get Hours
    $("#tpick").on("click", ".hrs", function() {
        var hours = $(this).html();
        $("#forh").html(hours);
    });
    $("#tpick2").on("click", ".hrs", function() {
        var hours = $(this).html();
        $("#forh2").html(hours);
    });
    //Get Minutes
    $("#tpick").on("click", ".minutes", function(f) {
        f.stopPropagation();
        var min = $(this).html();
        $("#minutes").html(min);
        $("#tpick").fadeOut();
    });
    $("#tpick2").on("click", ".minutes", function(f) {
        f.stopPropagation();
        var min = $(this).html();
        $("#minutes2").html(min);
        $("#tpick2").fadeOut();
    });
    //Get AM Format
    $("#tpick").on("click", ".am", function() {
        var dayTime = $(this).attr('data-time');
        $("#timeformat").html(dayTime);
    });
    $("#tpick2").on("click", ".am", function() {
        var dayTime = $(this).attr('data-time');
        $("#timeformat2").html(dayTime);
    });
    $("#tpick").on("click", ".pm", function() {
        var nightTime = $(this).attr('data-time');
        $("#timeformat").html(nightTime);
    });
    $("#tpick2").on("click", ".pm", function() {
        var nightTime = $(this).attr('data-time');
        $("#timeformat2").html(nightTime);
    });
    $("#tpick3").on("click", ".hrs", function() {
        var hours = $(this).html();
        $("#forh3").html(hours);
    });
    $("#tpick3").on("click", ".minutes", function(f) {
        f.stopPropagation();
        var min = $(this).html();
        $("#minutes3").html(min);
        $("#tpick3").fadeOut();
    });
    $("#tpick3").on("click", ".am", function() {
        var dayTime = $(this).attr('data-time');
        $("#timeformat3").html(dayTime);
    });
    $("#tpick3").on("click", ".pm", function() {
        var nightTime = $(this).attr('data-time');
        $("#timeformat3").html(nightTime);
    });

    $("#tpick4").on("click", ".hrs", function() {
        var hours = $(this).html();
        $("#forh4").html(hours);
    });
    $("#tpick4").on("click", ".minutes", function(f) {
        f.stopPropagation();
        var min = $(this).html();
        $("#minutes4").html(min);
        $("#tpick4").fadeOut();
    });
    $("#tpick4").on("click", ".am", function() {
        var dayTime = $(this).attr('data-time');
        $("#timeformat4").html(dayTime);
    });
    $("#tpick4").on("click", ".pm", function() {
        var nightTime = $(this).attr('data-time');
        $("#timeformat4").html(nightTime);
    });

    $("#tpick5").on("click", ".hrs", function() {
        var hours = $(this).html();
        $("#forh5").html(hours);
    });
    $("#tpick5").on("click", ".minutes", function(f) {
        f.stopPropagation();
        var min = $(this).html();
        $("#minutes5").html(min);
        $("#tpick5").fadeOut();
    });
    $("#tpick5").on("click", ".am", function() {
        var dayTime = $(this).attr('data-time');
        $("#timeformat5").html(dayTime);
    });
    $("#tpick5").on("click", ".pm", function() {
        var nightTime = $(this).attr('data-time');
        $("#timeformat5").html(nightTime);
    });
    $("#tpick6").on("click", ".hrs", function() {
        var hours = $(this).html();
        $("#forh6").html(hours);
    });
    $("#tpick6").on("click", ".minutes", function(f) {
        f.stopPropagation();
        var min = $(this).html();
        $("#minutes6").html(min);
        $("#tpick6").fadeOut();
    });
    $("#tpick6").on("click", ".am", function() {
        var dayTime = $(this).attr('data-time');
        $("#timeformat6").html(dayTime);
    });
    $("#tpick6").on("click", ".pm", function() {
        var nightTime = $(this).attr('data-time');
        $("#timeformat6").html(nightTime);
    });

    function getSelectedValue(beam) {
        return $("#" + beam).find("timeformat,timeformat2,timeformat3,timeformat4,timeformat5,timeformat6").html();
    }
    function getSelectedValue(id) {
        return $("#" + id).find("forh,forh2,forh3,forh4,forh5,forh6").html();
    }
    function getSelectedValue(minuti) {
        return $("#" + minuti).find("minutes,minutes2,minutes3,minutes4,minutes5,minutes6").html();
    }
    //Hidding TimePicker by Clikcing any where!
    $("#getTime").click(function(e) {
        e.stopPropagation();
        $("#tpick").fadeIn();
        $("#tpick2,#tpick3,#tpick4,#tpick5,#tpick6").fadeOut();
    });
    $("#getTime2").click(function(e) {
        e.stopPropagation();
        $("#tpick2").fadeIn();
        $("#tpick,#tpick3,#tpick4,#tpick5,#tpick6").fadeOut();
    });
    $("#getTime3").click(function(e) {
        e.stopPropagation();
        $("#tpick3").fadeIn();
        $("#tpick,#tpick2,#tpick4,#tpick5,#tpick6").fadeOut();
    });
    $("#getTime4").click(function(e) {
        e.stopPropagation();
        $("#tpick4").fadeIn();
        $("#tpick,#tpick2,#tpick3,#tpick5,#tpick6").fadeOut();
    });
    $("#getTime5").click(function(e) {
        e.stopPropagation();
        $("#tpick5").fadeIn();
        $("#tpick,#tpick2,#tpick3,#tpick4,#tpick6").fadeOut();
    });
    $("#getTime6").click(function(e) {
        e.stopPropagation();
        $("#tpick6").fadeIn();
        $("#tpick,#tpick2,#tpick3,#tpick4,#tpick5").fadeOut();
    });

    var $body = $(document.body),
            ser = false,
            $timp = $("#tpick,#tpick2,#tpick3,#tpick4,#tpick5,#tpick6,#search-suggestions,.items-to-filter");

    //stopPropagation 
    $('html').click(function() {
        $("#cities").animate({
            top: '-100px'
        }, 300, 'easeInOutBack');
        if (ser) {
            setTimeout(function() {
                $("#search-bar").css({
                    position: 'relative'
                });
            }, 650);
            $("#search-bar input").stop().animate({
                width: '130px'
            }, 800, 'easeInOutBack');
            ser = false;
        }
    });



    $body.on('click', function() {
        $timp.fadeOut();
        //$("#search-bar input").removeClass("focuedField");
        //$("#search-bar .add-on").removeClass("addOnfocus");
        //$('.shop-menu').slideUp();
        $('.popup-msg').hide();
    });

    /* expand searchbar ========================================== */
    /*$("#search-bar").bind('click', function(e) {
     e.stopPropagation();
     $(this).css({
     position: 'absolute',
     right: '0'
     });
     $("#search-bar input").stop().animate({
     width: '655px'
     }, 800, 'easeOutBack', function() {
     ser = true;
     });
     });*/

    /*$("#search-bar input").keyup(function() {
        $("#search-suggestions").slideDown();
    });*/
    $("#search-bar").click(function() {
        $("#search-bar input").addClass("focuedField");
        $("#search-bar .add-on").addClass("addOnfocus");
    });

    /* tooltip    ================================================ */

    var windiTh = $(window).width(),
            $popMsg = $('.popup-msg');

    if (windiTh < 768) {
        //Less than 768
        $(".aperiod").on('click', function(evt) {
            $(this).parent().find($popMsg).toggle();
            evt.preventDefault();
        });
    }
    else {
        //More than 768
        $(".aperiod").mouseenter(function() {
            $(this).parent().find($popMsg).show().stop();
        }).mouseleave(function() {
            $(this).parent().find($popMsg).hide().stop();
        });
    }


    /* checkbox   ================================================ */
    /*$('.check-box').click(function() {
     $(this).find(':checkbox').prop('checked', !$(this).find(':checkbox').prop('checked')).trigger('change');
     });
     
     $(".check-box,#selectAll").click(function() {
     $(this).toggleClass('checkedBox');
     });
     $("#checkall .check-box").click(function() {
     $(this).toggleClass('checkedBox');
     });*/

    /* overlay    ================================================ */
    jQuery('#images-preview').on("mouseenter", ".overlay", function() {
        //if (!$(this).parent().hasClass('default')) {
        $(this).animate({
            opacity: '1'
        })
        //}
    });
    jQuery('#images-preview').on("mouseleave", ".overlay", function() {
        //if (!$(this).parent().hasClass('default')) {
        $(this).animate({
            opacity: '0'
        })
        //}
    });


    /* rotate     ================================================ */
    function getRotationDegrees(obj) {
        var matrix = obj.css("-webkit-transform") || obj.css("-moz-transform") || obj.css("-ms-transform") || obj.css("-o-transform") || obj.css("transform");
        if (matrix !== 'none') {
            var values = matrix.split('(')[1].split(')')[0].split(',');
            var a = values[0];
            var b = values[1];
            var angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
        } else {
            var angle = 0;
        }
        return angle;
    }

    /* floated block ============================================= */
    $(function() {
        var msie6 = $.browser == 'msie' && $.browser.version < 7;
        var respo = $(window).width();
        if (respo > 1024) {
            if ($('.floatedSide').get(0)) {
                //large screen
                if (!msie6) {
                    var top = $('.floatedSide').offset().top - parseFloat($('.floatedSide').css('margin-top').replace(/auto/, 0));
                    $(window).scroll(function() {
                        var y = $(this).scrollTop();
                        if (y > top) {
                            $('.floatedSide').addClass('fixed');
                            $("#secondary-menu").css('position', 'fixed');
                            $("#secondary-menu").addClass('secondMenu');
                            $('.sub-cats').css('visibility', 'hidden');
                            var marginLeft,
                                    browserV = $.browser.version;

                            if (respo < 1280) {
                                marginLeft = 31
                            } else {
                                if ($('#container').get(0))
                                    marginLeft = $('#container').offset().left
                            }
                            ;
                            if (browserV == '8.0') {
                                marginLeft = 0
                            }

                            $("#sidebar").css({
                                top: '60px',
                                marginLeft: marginLeft
                            });
                            $("#scrollsearch").css('visibility', 'visible');
                        } else {
                            $('.floatedSide').removeClass('fixed');
                            $("#secondary-menu").removeClass('secondMenu');
                            $('.sub-cats').css('visibility', 'visible');
                            $("#secondary-menu").css('position', 'absolute');
                            $("#sidebar").css({
                                top: '45px',
                                marginLeft: '0'
                            });
                        }
                    });
                }
            }
        }
        //small screen
        if (respo < 1000) {
            if (!msie6) {
                var top = $('.floatedSide').offset().top - parseFloat($('.floatedSide').css('margin-top').replace(/auto/, 0));
                $(window).scroll(function() {
                    var y = $(this).scrollTop();
                    if (y > top) {
                        $("#sidebar, #sidebar-user").css('top', '0');
                    } else {
                        $("#sidebar, #sidebar-user").css('top', '53px');
                    }
                });
            }
        }
    });

    /* load more ================================================= */
    //$('.gallery-images').slice(0, 8).fadeIn();
    //$('.gallery-images').slice(12, 100000).css('display', 'none');
    //var loadMore = 6;
    /*$(window).scroll(function() {
     if ($(window).scrollTop() + $(window).height() == $(document).height()) {
     $('.gallery-images').slice(loadMore, loadMore + 9).fadeIn(3000);
     loadMore += 6;
     return false;
     }
     });*/

    /* back to top =============================================== */
    $('a[href=#top]').click(function() {
        $('body,html,document').animate({
            scrollTop: 0
        }, 800); //1000
        return false;
    });

    $(window).scroll(function() {
        if ($(this).scrollTop() > 50) {
            $('.totop a').fadeIn();
        } else {
            $('.totop a').fadeOut();
        }
    });

    /* scrollbar ================================================= */
    if ($('[id*="scrollbar-"]').get(0)) {
        $('[id*="scrollbar-"]').tinyscrollbar();
        $('#scrollbar-2').tinyscrollbar({
            size: 99
        });
        $('#scrollbar-5').tinyscrollbar({
            size: 99
        });
        $('#scrollbar-3').tinyscrollbar({
            size: 10
        });
    }

    //hide scrollbar if less than 9
    var count = $(".scrollable li").children().length;
    if (count < 9) {
        $('.wrappa').hide();
    } else {
        $('.wrappa').show();
    }

    $("#scrollParent,.cityParent").css('display', 'none');

    $(".sidebar-menu").click(function() {
        $("#scrollParent").slideToggle();
        $(".upper-arr").toggle();
        return false;
    });
    $("#mobile-change, .mob-replace").bind('click', function() {
        $("#mobile-cities").stop().animate({
            left: '20px'
        }, 300);
        return false;
    });

    var statPa = $('.locations-to-filter').outerHeight(true),
            citState = $('#mycities-states').outerHeight(true),
            locaCity = statPa / (citState / statPa);

    function drago() {
        var patio = -1 * (citState - statPa) / (statPa - $('#locationScroll').outerHeight(true) - 7);
        var posiT = $('#locationScroll').position().top - 3;
        $('#mycities-states').css({
            top: posiT * patio
        });
    }

    $('#locationScroll').height(locaCity);
    $('#locationScroll').draggable({
        axis: 'y',
        containment: 'parent',
        drag: function() {
            drago()
        }
    });
    $("#mobile-cities").keyup(function(tos) {
        tos.stopPropagation();
        $(".locations-to-filter").fadeIn();
        var filter = $(this).val(),
                count = 0;
        $("#mycities-states ul li").each(function() {
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).fadeOut();
            } else {
                $(this).show();
                count++;
            }
        });
        //hide scrollbar if less than 9
        if (count < 4) {
            $('#scrollbar-3 .track').fadeOut();
            $('#scrollbar-3').css("max-height", 35 * count);
        } else {
            $('#scrollbar-3 .track').fadeIn();
            $('#scrollbar-3').css("max-height", 150);
        }
    });
    $("#mycities-states ul li a").on('click', function() {
        var text = $(this).html();
        $("#mobile-cities").val(text);
        $(".mob-replace").html(text);
        $(".locations-to-filter").hide();
        $("#mobile-cities").animate({
            left: '-100%'
        }, 300);
        return false;
    });
    $("#mobile-cities").click(function(ts) {
        ts.stopPropagation();
        $("#mobile-cities").select();
    });

    /* sidebar-accordion ========================================= */
    $(".sidelink").click(function() {
        if ($(this).next().is(':hidden')) {
            $(this).next('.cont').slideDown();
            $(this).addClass('opendPanel');
        } else if ($(this).next().is(':visible')) {
            $(this).next('.cont').slideUp();
            $(this).removeClass('opendPanel');
        }
        return false;
    });
    $(".dp-details:first").slideDown();
    $('#shipping-details h3').click(function() {
        if ($(this).next().is(':hidden')) {
            $('#shipping-details h3').removeClass('detailsPanel').next().slideUp('slow');
            $(this).toggleClass('detailsPanel').next().slideDown('slow');
        }
    });

    /* confirm-delivery ========================================== */
    $("#confirm-delivery").click(function() {
        if ($(".datepicker").val() == '') {
            $("#delv-head").addClass('detailHead');
        } else {
            $("#delv-head").removeClass('detailHead');
        }
    });
    /* slide  ==================================================== */
    $("#next-slida").click(function() {
        activeElem = $("#target .active");
        if (!activeElem.is(':last-child')) {
            activeElem.removeClass('active').next().addClass('active');
        }
    });
    $("#prev-slida").click(function() {
        activeElem = $("#target .active");
        if (!activeElem.is(':first-child')) {
            activeElem.removeClass('active').prev().addClass('active');
        }
    });

    /* get-info ================================================== */
    $(".toshowd").show();
    $(".get-info").click(function() {
        if ($(this).next().is(':hidden')) {
            $(this).next('.productInfo').slideDown();
            $(this).find('.togg-icon').addClass('opned');
        } else if ($(this).next().is(':visible')) {
            $(this).next('.productInfo').slideUp();
            $(this).find('.togg-icon').removeClass('opned');
        }
        return false;
    });

    /* jCarouselLite ============================================= */
    $(".widget img").click(function() {
        $(".widget .midSlid img").attr("src", $(this).attr("src"));
        return false;
    });

    /* zoom plugin =============================================== */
    $('#ex1').zoom({
    });
    /*maxHeight: '50%',
     maxWidth: '50%'
     maxHeight: '500px',
     maxWidth: '500px'*/

    /*$('.jqzoom').jqzoom({
     zoomType: 'reverse',
     lens:true,
     zoomWidth: 500,
     zoomHeight: 500,
     xOffset: 18,
     yOffset: -10,
     position: 'right',
     preloadImages: false,
     alwaysOn:false,
     title: false,
     showEffect: 'show'
     });*/

    /* input mask ================================================ */
    $(".numb-format").mask("(999) 999 9999"); //telephone format
    $(".datepicker").mask("99/99/9999");  //date format

    /* sorting =================================================== */
    $('.defPrices, .highPrices, .lowPrices').click(function() {
        this.className = {
            lowPrices: 'defPrices',
            defPrices: 'highPrices',
            highPrices: 'lowPrices'
        }
        [this.className];
    });

    $('.defRating, .highRating, .lowRating').click(function() {
        this.className = {
            lowRating: 'defRating',
            defRating: 'highRating',
            highRating: 'lowRating'
        }
        [this.className];
    });

    $('.defDate, .newestDate, .oldestDate').click(function() {
        this.className = {
            newestDate: 'defDate',
            defDate: 'oldestDate',
            oldestDate: 'newestDate'
        }
        [this.className];
    });

    /* getmobile menu ============================================ */
    $("#header-container").on('click', '#get-mobile-menu', function() { console.log('#get-mobile-menu CLICK');
        $(".mobile-menu").slideToggle();
        return false;
    });

    /* user account profile edit ================================= */
    $("#editBasicInfo").click(function() {
        $(this).fadeOut();
        $(".account-block .profile-image a").fadeIn();
        $(".def-account-info").hide();
        $(".edit-basic-account-info, .edit-veriations, .saveValue-basic-info").slideDown();
        return false;
    });

    /* editBdInfo ================================================ */
    $("#editBdInfo").click(function() {
        $(this).fadeOut();
        $(this).parent().addClass("opendEdit-block");
        $(".def-bd-field").hide();
        $(".save-bd-info").show('slow');
        $(".edit-birthday-info").fadeIn('slow');
        return false;
    });
    /* editEmailInfo ============================================= */
    $("#editEmailInfo").click(function() {
        $(this).fadeOut();
        $(this).parent().addClass("opendEdit-block");
        $(".def-bd-field, .def-email-field").hide();
        $(".edit-email-field, .saveValue-email-info").slideDown('slow');
        return false;
    });
    /* add-email-field ========================================== */
    $(".add-email-field").click(function() {
        $(this).hide();
        $(".new-email-field").css('display', 'block');
        return false;
    });
    /* editPhoneInfo ============================================ */
    $("#editPhoneInfo").click(function() {
        $(this).fadeOut();
        $(".def-phone-field").hide();
        $(this).parent().addClass("opendEdit-block");
        $(".edit-phone-field, .saveValue-phone-info").show('slow');
        return false;
    });
    /* add-phone-field =========================================== */
    $(".add-phone-field").click(function() {
        $(this).hide();
        $(".new-phone-field").css('display', 'block');
        return false;
    });
    /* editAddressInfo ======================================== */
    $("#editAddressInfo").click(function() {
        $(this).fadeOut();
        $(".def-address-field").hide();
        $(this).parent().addClass("opendEdit-block");
        $(".edit-address-field, .save-address-info").show('slow');
        return false;
    });
    /* editAccountDetails ======================================== */
    $("#editAccountDetails").click(function() {
        $(this).fadeOut();
        $(".def-account-field").hide();
        $(".edit-account-details, .saveValue-account-details").show('slow');
        $(this).parent().addClass("opendEdit-block");
        return false;
    });
    /* editLoginDetails ========================================= */
    $("#editLoginDetails").click(function() {
        $(this).fadeOut();
        $(".def-login-details").hide();
        $(".edit-login-details, .saveValue-login-details").slideDown();
        $(this).parent().addClass("opendEdit-block");
        return false;
    });
    /* cities ==================================================== */
    $("#cities").keyup(function(sot) {
        sot.stopPropagation();
        $("#scrollbar-2").slideDown();
    });

    $("#cities").click(function(st) {
        st.stopPropagation();
        $("#cities").select();
    });
    $("#choose-a-city ul li").click(function() {
        var text = $(this).text();
        $("#cities").val(text);
        $(".replTxt").html(text);
        $(".cityParent").slideUp();
        $("#cities").animate({
            top: '-100px'
        }, 300, 'easeInOutBack');
        return false;
    });

    $(".change, .replTxt").click(function(sopt) {
        $("#cities").animate({
            top: '-34px'
        }, 300, 'easeInOutBack');
        sopt.stopPropagation();
    });

    /* slidWrap ================================================== */

    (function() {

        var selectedItemsCount = 0,
                $sbmButton = $('#confirm-delivery'),
                $selectedBlock = $('.get-wat-selected');


        $(".slidWrap .check-box").each(function(e) {

            if ($(this).hasClass("checkedBox")) {
                console.log(123123);
                var elems = $(this).parents().find('.get-text'),
                        getxt = $(elems).html();
                $(this).parent().css('background', '#fefcf5');
                var tdtime = $(this).parent().data('time'),
                        timeText = "",
                        ddtimeElems = $(".time"),
                        keyt = $(this).parent().data('key');
                $.each(ddtimeElems, function(i, val) {
                    var elem = $(val);
                    if (elem.data("time") === tdtime) {
                        timeText = elem.html();
                    }
                });
                var rmvbtn = " <button class='remove-selected' data-time=" + tdtime + " data-key=" + keyt + "></button> ",
                        getFinal = getxt + "<span class='scdt'> " + timeText + "</span>" + rmvbtn;
                $('.get-wat-selected').append("<p>" + getFinal + "</p>");
                selectedItemsCount++;
                if (selectedItemsCount > 2)
                {
                    $('.check-box:not(".checkedBox")').hide();
                }
            }
        });

        if (selectedItemsCount > 0) {
            $sbmButton.prop('disabled', false);
            $selectedBlock.show('slow');
        }


        $(".slidWrap .check-box").on('click', function(e) {
            if ($(this).hasClass("checkedBox")) {
                var elems = $(this).parents().find('.get-text'),
                        getxt = $(elems).html();
                $(this).parent().css('background', '#fefcf5');
                var tdtime = $(this).parent().data('time'),
                        timeText = "",
                        ddtimeElems = $(".time"),
                        keyt = $(this).parent().data('key');
                $.each(ddtimeElems, function(i, val) {
                    var elem = $(val);
                    if (elem.data("time") === tdtime) {
                        timeText = elem.html();
                    }
                });
                var rmvbtn = " <button class='remove-selected' data-time=" + tdtime + " data-key=" + keyt + "></button> ",
                        getFinal = getxt + "<span class='scdt'> " + timeText + "</span>" + rmvbtn;
                $('.get-wat-selected').append("<p>" + getFinal + "</p>");
                selectedItemsCount++;
                if (selectedItemsCount > 2)
                {
                    $('.check-box:not(".checkedBox")').hide();
                }
            } else {
                selectedItemsCount--;
                $('.remove-selected[data-key="' + $(this).parent().data('key') + '"][data-time="' + $(this).parent().data('time') + '"]').parent().remove();

                if (selectedItemsCount < 3)
                {
                    $('.check-box:not(".checkedBox")').show();
                }
            }
            if (selectedItemsCount < 1)
            {
                $sbmButton.prop('disabled', true);
                $selectedBlock.hide('slow');

            } else
            {
                $sbmButton.prop('disabled', false);
            }
        });


        $(".remove-selected").live('click', function() {
            $(this).parent().remove();
            $('div[data-key="' + $(this).data('key') + '"][data-time="' + $(this).data('time') + '"]').find('.check-box').click();
            /*	var ttg = $(this).data("key"),
             smth = $(".slidWrap table").find('td[data-key=' + ttg + ']').find('input:checkbox');
             $(smth).parent().removeClass("checkedBox");
             $(smth).parent().parent().css('background', '#fff');
             $(smth).attr('checked', false); */
            if (!$('.get-wat-selected p')[0]) {
                $('.get-wat-selected').hide('slow');
                return false;
            }
        });

        $('.slidWrap .check-box').on('change', 'input', function(event) {
            if ($('#slidWrap .check-box input:checked').length > 3) {
                event.preventDefault();
                $(this).prop('checked', false).trigger('change');
                return false;
            }
        });

        $(".slidWrap .check-box").on('click', function() {
            if (selectedItemsCount > 0)
                $selectedBlock.show('slow');
            return false;
        });
    })()

    /* Delivery Date table ======================================= */
    $(function() {
        var height = 246,
                slides = $(".slidWrap").length,
                contentNum = 1;

        $("#slidsContainer").css({
            height: slides * height
        });

        /* slideBottom */
        $('#slideBottom').click(function() {
            if (contentNum < slides) {
                $('#slidsContainer').animate({
                    marginTop: '-' + (height * contentNum)
                }, 300).clearQueue();
                contentNum = contentNum + 1;
            } else {
                return false;
                contentNum = contentNum / contentNum;
            }
            return false;
        });

        /* slideTop */
        $('#slideTop').click(function() {
            if (contentNum > 1) {
                $('#slidsContainer').animate({
                    marginTop: '+=246'
                }, 300).clearQueue();
                contentNum = contentNum - 1;
            } else {
                return false;
                contentNum = 0;
            }
            return false;
        });
    });

    /* myCarousel ================================================ */
    $('#myCarousel').carousel({
        interval: 5000
    });

    /* available dates =========================================== */

    $(function() {
        var heigh = 673,
                slids = $("#table-slider2 ul").length,
                contentNm = 1,
                $contenRow = $("#table-slider2 .slidWrapper");

        $contenRow.css({
            height: slids * heigh
        });

        /* slideBottom */
        $('#slideBottom2').click(function() {
            if (contentNm < slids) {
                $contenRow.animate({
                    marginTop: '-' + (heigh * contentNm)
                }, 300).clearQueue();
                contentNm = contentNm + 1;
            } else {
                return false;
                contentNm = contentNm / contentNm;
            }
            return false;
        });

        /* slideTop */
        $('#slideTop2').click(function() {
            if (contentNm > 1) {
                $contenRow.animate({
                    marginTop: '+=673'
                }, 300).clearQueue();
                contentNm = contentNm - 1;
            } else {
                return false;
                contentNm = 0;
            }
            return false;
        });
    });

    /* items-to-filter =========================================== */
    var itparN = $('.items-to-filter').outerHeight(true),
            ariteM = $('#mysales-items').outerHeight(true),
            siteMs = itparN / (ariteM / itparN);

    function draing() {
        var ratio = -1 * (ariteM - itparN) / (itparN - $('#scrollitems').outerHeight(true) - 7),
                scrPos = $('#scrollitems').position().top - 3;
        $('#mysales-items').css({
            top: scrPos * ratio
        });
    }

    $('#scrollitems').height(siteMs);
    $('#scrollitems').draggable({
        axis: 'y',
        containment: 'parent',
        drag: function() {
            draing()
        }
    });
    /* filter-items ============================================== */
    $("#filter-items").keyup(function(tos) {
        tos.stopPropagation();
        $("#scrollbar-5").slideDown();
    });
    $('.items-to-filter, #scrollbar-5').hide();
    $("#mysales-items ul li a").on('click', function() {
        var text = $(this).html();
        $(this).parents().find("#filter-items").val(text);
        $("#scrollbar-5").slideUp();
        return false;
    });
    $("#filter-items").click(function(st) {
        st.stopPropagation();

        $("#filter-items").select();
    });
    /* maxTitle ================================================== */
    function maxTitle() {
        $('.item-price-n-name a').each(function() {
            var maxchars = 30;
            var seperator = '...';
            if ($(this).text().length > (maxchars - seperator.length)) {
                $(this).text($(this).text().substr(0, maxchars - seperator.length) + seperator);
            }
        });
    }
}); //<< end doc ready

/* ============================================================
 placeholder for older browsers
 ============================================================ */
var _debug = false;
var _placeholderSupport = function() {
    var t = document.createElement("input");
    t.type = "text";
    return (typeof t.placeholder !== "undefined");
}();

window.onload = function() {
    var arrInputs = document.getElementsByTagName("input");
    for (var i = 0; i < arrInputs.length; i++) {
        var curInput = arrInputs[i];
        if (!curInput.type || curInput.type == "" || curInput.type == "text")
            HandlePlaceholder(curInput);
        else if (curInput.type == "password")
            ReplaceWithText(curInput);
    }

    if (!_placeholderSupport) {
        for (var i = 0; i < document.forms.length; i++) {
            var oForm = document.forms[i];
            if (oForm.attachEvent) {
                oForm.attachEvent("onsubmit", function() {
                    PlaceholderFormSubmit(oForm);
                });
            }
            else if (oForm.addEventListener)
                oForm.addEventListener("submit", function() {
                    PlaceholderFormSubmit(oForm);
                }, false);
        }
    }
};

function PlaceholderFormSubmit(oForm) {
    for (var i = 0; i < oForm.elements.length; i++) {
        var curElement = oForm.elements[i];
        HandlePlaceholderItemSubmit(curElement);
    }
}

function HandlePlaceholderItemSubmit(element) {
    if (element.name) {
        var curPlaceholder = element.getAttribute("placeholder");
        if (curPlaceholder && curPlaceholder.length > 0 && element.value === curPlaceholder) {
            element.value = "";
            window.setTimeout(function() {
                element.value = curPlaceholder;
            }, 100);
        }
    }
}

function ReplaceWithText(oPasswordTextbox) {
    if (_placeholderSupport)
        return;
    var oTextbox = document.createElement("input");
    oTextbox.type = "text";
    oTextbox.id = oPasswordTextbox.id;
    oTextbox.name = oPasswordTextbox.name;
    //oTextbox.style = oPasswordTextbox.style;
    oTextbox.className = oPasswordTextbox.className;
    for (var i = 0; i < oPasswordTextbox.attributes.length; i++) {
        var curName = oPasswordTextbox.attributes.item(i).nodeName;
        var curValue = oPasswordTextbox.attributes.item(i).nodeValue;
        if (curName !== "type" && curName !== "name") {
            oTextbox.setAttribute(curName, curValue);
        }
    }
    oTextbox.originalTextbox = oPasswordTextbox;
    oPasswordTextbox.parentNode.replaceChild(oTextbox, oPasswordTextbox);
    HandlePlaceholder(oTextbox);
    if (!_placeholderSupport) {
        oPasswordTextbox.onblur = function() {
            if (this.dummyTextbox && this.value.length === 0) {
                this.parentNode.replaceChild(this.dummyTextbox, this);
            }
        };
    }
}

function HandlePlaceholder(oTextbox) {
    if (!_placeholderSupport) {
        var curPlaceholder = oTextbox.getAttribute("placeholder");
        if (curPlaceholder && curPlaceholder.length > 0) {
            Debug("Placeholder found for input box '" + oTextbox.name + "': " + curPlaceholder);
            oTextbox.value = curPlaceholder;
            oTextbox.setAttribute("old_color", oTextbox.style.color);
            oTextbox.style.color = "#c0c0c0";
            oTextbox.onfocus = function() {
                var _this = this;
                if (this.originalTextbox) {
                    _this = this.originalTextbox;
                    _this.dummyTextbox = this;
                    this.parentNode.replaceChild(this.originalTextbox, this);
                    _this.focus();
                }
                Debug("input box '" + _this.name + "' focus");
                _this.style.color = _this.getAttribute("old_color");
                if (_this.value === curPlaceholder)
                    _this.value = "";
            };
            oTextbox.onblur = function() {
                var _this = this;
                Debug("input box '" + _this.name + "' blur");
                if (_this.value === "") {
                    _this.style.color = "#c0c0c0";
                    _this.value = curPlaceholder;
                }
            };
        }
        else {
            Debug("input box '" + oTextbox.name + "' does not have placeholder attribute");
        }
    }
    else {
        Debug("browser has native support for placeholder");
    }
}

function updateOrder(element)
{
    if ($(element).hasClass("defPrices")) {
        $("input[name='order_price']").val("asc");
        $('#order-by-rating').attr("class", "defRating");
        $('#order-by-date').attr("class", "defDate");
        $("input[name='order_rating']").val("");
        $("input[name='order_date']").val("");
    } else if ($(element).hasClass("highPrices")) {
        $("input[name='order_price']").val("desc");
        $('#order-by-rating').attr("class", "defRating");
        $('#order-by-date').attr("class", "defDate");
        $("input[name='order_rating']").val("");
        $("input[name='order_date']").val("");
    } else if ($(element).hasClass("lowPrices")) {
        $("input[name='order_price']").val("");
        $('#order-by-rating').attr("class", "defRating");
        $('#order-by-date').attr("class", "defDate");
        $("input[name='order_rating']").val("");
        $("input[name='order_date']").val("");
    } else if ($(element).hasClass("defRating")) {
        $("input[name='order_rating']").val("asc");
        $('#order-by-price').attr("class", "defPrices");
        $('#order-by-date').attr("class", "defDate");
        $("input[name='order_price']").val("");
        $("input[name='order_date']").val("");
    } else if ($(element).hasClass("highRating")) {
        $("input[name='order_rating']").val("desc");
        $('#order-by-price').attr("class", "defPrices");
        $('#order-by-date').attr("class", "defDate");
        $("input[name='order_price']").val("");
        $("input[name='order_date']").val("");
    } else if ($(element).hasClass("lowRating")) {
        $("input[name='order_rating']").val("asc");
        $('#order-by-price').attr("class", "defPrices");
        $('#order-by-date').attr("class", "defDate");
        $("input[name='order_price']").val("");
        $("input[name='order_date']").val("");
    } else if ($(element).hasClass("defDate")) {
        $("input[name='order_date']").val("desc");
        $('#order-by-price').attr("class", "defPrices");
        $('#order-by-rating').attr("class", "defRating");
        $("input[name='order_price']").val("");
        $("input[name='order_rating']").val("");
    } else if ($(element).hasClass("newestDate")) {
        $("input[name='order_date']").val("");
        $('#order-by-price').attr("class", "defPrices");
        $('#order-by-rating').attr("class", "defRating");
        $("input[name='order_price']").val("");
        $("input[name='order_rating']").val("");
    } else if ($(element).hasClass("oldestDate")) {
        $("input[name='order_date']").val("asc");
        $('#order-by-price').attr("class", "defPrices");
        $('#order-by-rating').attr("class", "defRating");
        $("input[name='order_price']").val("");
        $("input[name='order_rating']").val("");
    }

    setTimeout("reloadProducts()", 200);
}

function Debug(msg) {
    if (typeof _debug !== "undefined" && _debug) {
        var oConsole = document.getElementById("Console");
        if (!oConsole) {
            oConsole = document.createElement("div");
            oConsole.id = "Console";
            document.body.appendChild(oConsole);
        }
        oConsole.innerHTML += msg + "<br />";
    }
}

$('.dropdown-toggle').on('click', function() {
    $(this).parent().find('.dropdown-menu').toggle();
});

//Subscribe
$(window).load(function() {
    var scrollTop = parseInt($(window).scrollTop());
    var windowHeight = $(window).height();
    var persent = parseInt((windowHeight * 25) / 100);
    if (scrollTop > persent) {
        $('.subscribe-overlay').fadeIn(600, function() {
            $('.subscribe-window').css({'top': persent + scrollTop + 'px'}).slideDown();
        });
    }
    else {
        $('.subscribe-overlay').fadeIn(600, function() {
            $('.subscribe-window').css({'top': persent + scrollTop + 'px'}).slideDown();
        })
    }
    $('.close-butt').click(function() {
        $(this).parents('.subscribe-overlay').fadeOut(500);
    })

    $(document).bind('click', function(e) {
        var $clicked = $(e.target);
        if (!$clicked.parents().hasClass("subscribe-window"))
        {
            $(".subscribe-overlay").fadeOut(500);
        }
    });

    $('#alert-link')
        .removeClass('hidden')
        .on('click', function(){
        showProductAlertPopup($(this).attr('href'));
        return false;
    });
})

function showProductAlertPopup(url){
    $('#new-alert-popup').remove();
    $.ajax({
        url: url,
        dataType: 'json',
        success: function(response){
            if (response.success) {
                $('body').append(response.html);
                $('#new-alert-popup').modal();
                initProductAlertPopup();
            } else {
                alert(response.message);
            }
        }

    });

}

function showSharePopup(url){
    $('#share-popup').remove();
    if (typeof(showOverlay) == "function") {
        showOverlay();
    }
    $.ajax({
        url: url,
        dataType: 'json',
        success: function(response){
            if (typeof(hideOverlay) == "function") {
                hideOverlay();
            }
            if (response.success) {
                $('.apt-container').append(response.html);
                $('#share-popup').modal();
            } else {
                alert(response.message);
            }
        }
    });
}

function validateEmail(field) {
    var regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/;
    return (regex.test(field)) ? true : false;
}

function validateMultipleEmailsCommaSeparated(emailcntl, seperator) {
    if (!seperator) {
        seperator = ',';
    }
    if (typeof (emailcntl) == 'string') {
        emailcntl = document.getElementById(emailcntl);
    }
    var value = emailcntl.value;
    if (value != '') {
        var result = value.split(seperator);
        for (var i = 0; i < result.length; i++) {
            if (result[i] != '') {
                result[i] = $.trim(result[i]);
                if (!validateEmail(result[i])) {
                    emailcntl.focus();
                    alert('Please check, `' + result[i] + '` email addresses not valid!');
                    return false;
                }
            }
        }
    }
    return true;
}
function popupwindow(url, title, w, h) {
    var left = (screen.width/2)-(w/2);
    var top = (screen.height/2)-(h/2);
    return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}

(function ($, window, document, undefined) {
    $.fn.mCarousel = function (options) {
        return this.each(function () {
            var $this = $(this),
                $ul = $this.find('ul'),
                $lis = $ul.find('li');

            var wOver = wUl = maxL = null;

            var settings = $.extend({
                step    : 57,
                speed   : 200
            }, options);

            init();

            function reset() {
                wUl   = $lis.length * ($lis.width() + 7) + 1;
                wOver = $this.width();

                maxL = wUl - wOver;
                $ul.width(wUl);

                if($ul.width() < $this.width()) {
                    $this.find('.control').hide();
                } else {
                    $this.find('.control').show();
                }
            }

            function init() {
                reset();
            }

            $(window).on('resize', function () {
                reset();
            });


            $this.on('click', '.prev', function () {
                var left = parseInt($ul.css('left')) + settings.step;
                if (left > 0) left = 0;
                $ul.stop().animate({
                    left: left
                }, settings.speed, 'linear');
            });

            $this.on('click', '.next', function () {
                var left = parseInt($ul.css('left')) - settings.step;
                if (-maxL > left) left = -maxL + 50;
                $ul.stop().animate({
                    left: left
                }, settings.speed, 'linear');
            });
        });
    }
})(jQuery, window, document);