/*------------------------------------------------------------------
 * Written for : https://www.aptdeco.com/
 * updated     : 23.09.14
 * Author      : @IkantamCorp - @ElmahdiMahmoud
 -------------------------------------------------------------------*/


$(document).ready(function() {

    /*accordion*/
    $('.apt-accordion [data-accordion="collapse"]').on('click', function() {
        var $this = $(this);
        if ($this.next().is(':hidden')) {
            $('.accordion-panel').removeClass('is-active');
            $this.parent('.accordion-panel').addClass('is-active');
        } else {
            $this.parent('.accordion-panel').removeClass('is-active');
        }
        return false;
    });

    $('.sm-tb-collapse').on('click touchstart', function() {
        var $this = $(this),
                _attr = $this.find('h2').data('section');

        $('.sm-section-collapse , .sm-tb-collapse h2').removeClass('is-active');
        $('#' + _attr).addClass('is-active');

        $this.find('h2').addClass('is-active');
    });

    $('.settoggle').on('click', function() {
        $('.toggling').toggle();
        $(this).toggleClass('active');
    });

    var
        current     = 0,
        flagActive  = true,
        aptSlider   = $(".apt-slider"),
        sliderLayer = $('.apt-slider-layer'),
        firstLayer  = sliderLayer.first(),
        totalLayers = sliderLayer.length;

    firstLayer.css('display', 'block');
    sliderBullets = aptSlider.append('<div class="slider-bullets"></div>');

    if (totalLayers - 1) {
        for (i = 0; i < totalLayers; i++) {
            $('<span></span>').appendTo('.slider-bullets');
        }
    }

    var bullet = $('.slider-bullets span');
    bullet.first().addClass('is-active');


    $('[data-src]').each(function() {
        $(this)
        .css('background-image', 'url(' + $(this).data('src') + ')');
    });


    $('.slider-bullets span').on('click', function() {
        return slideMe($(this));
    });

    function slideMe(element) {
        if (!element) {
            var spans = $(".slider-bullets span");
            var activeSpan = $(".slider-bullets span.is-active");
            if (activeSpan.index() < spans.length - 1) {
                element = spans.eq(activeSpan.index() + 1);
            } else {
                element = spans.eq(0);
            }
        }

        var $this = element,
                _index = $this.index();

        if (flagActive) {
            flagActive = false;

            $("span.is-active").removeClass("is-active");
            element.addClass("is-active");
            sliderLayer.hide('slow').css('z-index', 20);

            sliderLayer.eq(_index).css('z-index', 30).fadeIn('slow').css('display','block');
            setTimeout(function() {
                flagActive = true;
            }, 500);
        }
        return false;
    }

    var $div = $('<div>');
    //[data-src-lrg]
    $('.slider-image').each(function(){
        //console.log( $(this).css("background-image").replace('url(','').replace(')','') );
        $div.append($('<img src="' + $(this).css("background-image").replace('url(','').replace(')','') + '">'));

        //$div.append($('<img src="' + $(this).attr('data-src-lrg') + '">'));
    });

    var img = 1;
    if (totalLayers > 1) {
        $div.find('img').load(function(){
            if($div.find('img').length != img){
                img++;
            } else {
                setInterval(slideMe, 5000);
                $('.slider-bullets').addClass('is-active');
            }
            
        });
    }

    $('.share-box').on('click', function() {
        $('.share').select();
    });

    function isUrl(s) {
        var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
        return regexp.test(s);
    }

    $('.share').keyup(function() {
        var nonEscapedValue = $(this).val();
        var value = $('<div/>').text(nonEscapedValue).html();
        var words = value.split(" ");

        for (var i = 0; i < words.length; i++) {
            var n = isUrl(words[i]);
            if (n) {

                var deadLink = '<a href="' + words[i] + '" target="_blank">' + words[i] + '</a>';
                words[i] = words[i].replace(words[i], deadLink);
            }

        }

        $(".output-share").html(words.join(" "));
    });

    /*  */
    $.fn.toggleCheckbox = function() {
        this.prop('checked', !this.prop('checked'));
    }

    $('.social-media-accounts label').on('click', function() {
        $(this).find(':checkbox').toggleCheckbox();

        if ($(this).find(':checkbox').is(':checked')) {
            $(this).find('.checkbox-cover').addClass('is-on');
        } else {
            $(this).find('.checkbox-cover').removeClass('is-on');
        }
        return false;
    });


// Declaring required variables
    var digits = "0123456789";

// non-digit characters which are allowed in phone numbers
    var phoneNumberDelimiters = "()- ";

// characters which are allowed in international phone numbers
// (a leading + is OK)
    var validWorldPhoneChars = phoneNumberDelimiters + "+";

// Minimum no of digits in an international phone no.
    var minDigitsInIPhoneNumber = 10;

// Maximum no of digits in an america phone no.
    var maxDigitsInIPhoneNumber = 13;

//US Area Code
    var AreaCode = new Array(205, 251, 659, 256, 334, 907, 403, 780, 264, 268, 520, 928, 480, 602, 623, 501, 479, 870, 242, 246, 441, 250, 604, 778, 284, 341, 442, 628, 657, 669, 747, 752, 764, 951, 209, 559, 408, 831, 510, 213, 310, 424, 323, 562, 707, 369, 627, 530, 714, 949, 626, 909, 916, 760, 619, 858, 935, 818, 415, 925, 661, 805, 650, 600, 809, 345, 670, 211, 720, 970, 303, 719, 203, 475, 860, 959, 302, 411, 202, 767, 911, 239, 386, 689, 754, 941, 954, 561, 407, 727, 352, 904, 850, 786, 863, 305, 321, 813, 470, 478, 770, 678, 404, 706, 912, 229, 710, 473, 671, 808, 208, 312, 773, 630, 847, 708, 815, 224, 331, 464, 872, 217, 618, 309, 260, 317, 219, 765, 812, 563, 641, 515, 319, 712, 876, 620, 785, 913, 316, 270, 859, 606, 502, 225, 337, 985, 504, 318, 318, 204, 227, 240, 443, 667, 410, 301, 339, 351, 774, 781, 857, 978, 508, 617, 413, 231, 269, 989, 734, 517, 313, 810, 248, 278, 586, 679, 947, 906, 616, 320, 612, 763, 952, 218, 507, 651, 228, 601, 557, 573, 636, 660, 975, 314, 816, 417, 664, 406, 402, 308, 775, 702, 506, 603, 551, 848, 862, 732, 908, 201, 973, 609, 856, 505, 575, 585, 845, 917, 516, 212, 646, 315, 518, 347, 718, 607, 914, 631, 716, 709, 252, 336, 828, 910, 980, 984, 919, 704, 701, 283, 380, 567, 216, 614, 937, 330, 234, 440, 419, 740, 513, 580, 918, 405, 905, 289, 647, 705, 807, 613, 519, 416, 503, 541, 971, 445, 610, 835, 878, 484, 717, 570, 412, 215, 267, 814, 724, 902, 787, 939, 438, 450, 819, 418, 514, 401, 306, 803, 843, 864, 605, 869, 758, 784, 731, 865, 931, 423, 615, 901, 325, 361, 430, 432, 469, 682, 737, 979, 214, 972, 254, 940, 713, 281, 832, 956, 817, 806, 903, 210, 830, 409, 936, 512, 915, 868, 649, 340, 385, 435, 801, 802, 276, 434, 540, 571, 757, 703, 804, 509, 206, 425, 253, 360, 564, 304, 262, 920, 414, 715, 608, 307, 867)

    function isInteger(s) {
        var i;
        for (i = 0; i < s.length; i++) {
            // Check that current character is number.
            var c = s.charAt(i);
            if (((c < "0") || (c > "9")))
                return false;
        }
        // All characters are numbers.
        return true;
    }

    function stripCharsInBag(s, bag) {
        var i;
        var returnString = "";

        // Search through string's characters one by one.
        // If character is not in bag, append to returnString.
        for (i = 0; i < s.length; i++) {
            // Check that current character isn't whitespace.
            var c = s.charAt(i);
            if (bag.indexOf(c) == -1)
                returnString += c;
        }
        return returnString;
    }

    function trim(s) {
        var i;
        var returnString = "";

        // Search through string's characters one by one.
        // If character is not a whitespace, append to returnString.
        for (i = 0; i < s.length; i++)
        {
            // Check that current character isn't whitespace.
            var c = s.charAt(i);
            if (c != " ")
                returnString += c;
        }
        return returnString;
    }

    function checkInternationalPhone(strPhone) {
        strPhone = trim(strPhone)
        if (strPhone.indexOf("00") == 0)
            strPhone = strPhone.substring(2)
        if (strPhone.indexOf("+") > 1)
            return false
        if (strPhone.indexOf("+") == 0)
            strPhone = strPhone.substring(1)
        if (strPhone.indexOf("(") == -1 && strPhone.indexOf(")") != -1)
            return false
        if (strPhone.indexOf("(") != -1 && strPhone.indexOf(")") == -1)
            return false
        s = stripCharsInBag(strPhone, validWorldPhoneChars);
        if (strPhone.length > 10) {
            var CCode = s.substring(0, s.length - 10);
        }
        else {
            CCode = "";
        }
        if (strPhone.length > 7) {
            var NPA = s.substring(s.length - 10, s.length - 7);
        }
        else {
            NPA = ""
        }
        var NEC = s.substring(s.length - 7, s.length - 4)
        if (CCode != "" && CCode != null) {
            if (CCode != "1" && CCode != "011" && CCode != "001")
                return false
        }
        if (NPA != "") {
            if (checkAreaCode(NPA) == false) { //Checking area code is vaid or not
                return false
            }
        }
        else {
            return false
        }
        return (isInteger(s) && s.length >= minDigitsInIPhoneNumber && s.length <= maxDigitsInIPhoneNumber);
    }
//Checking area code is vaid or not
    function checkAreaCode(val) {
        var res = false;
        for (var i = 0; i < AreaCode.length; i++) {
            if (AreaCode[i] == val)
                res = true;
        }
        return res
    }

    function ValidateForm() {
        //var Phone=document.frmSample.test
        var Phone = $('#detect-phone');

        if ((Phone.val() == null) || (Phone.val() == "")) {

            Phone.keyup()
            return false
        }

        if (checkInternationalPhone(Phone.val()) == true) {
            $('.wraning-message').show(); // display warning message if a phone number exists
            //alert("Please Enter a Valid Phone Number")
            Phone.val("")
            Phone.keyup()
            return false
        }
        return true
    }

    $('#new-message').on('submit', function(e) {
        e.preventDefault();
        ValidateForm();
    });

//$('#new-message').on('change', ValidateForm);

    $('[data-show-targ]').on('click', function(e) {
        e.preventDefault();
        var $this = $(this),
                _attr = $this.data('show-targ');
        $('[data-targ="' + _attr + '"]').removeClass('hidden');
    });

    $(document).mouseup(function(e) {
        var $target = $(".data-show-targ");
        if (!$target.is(e.target) && $target.has(e.target).length === 0) {
            $target.find('[data-targ]').addClass('hidden');
        }
    });

    $('#sub-menu-search-field').keyup(function() {
        $('.sub-menu-suggestions-list').show();
        if ($(this).val() == '') {
            $('.sub-menu-suggestions-list').hide();
        }
    });


    $("#add-new-tag").on("click", function() {
        //e.stopPropagation();
        $("#name-tag").show().focus();
        $(this).hide();
        return false;
    });

    $('.clone-holder .add-more').on('click', function(e) {
        e.preventDefault();
        var $this = $(this),
                repeat = $this.prev('.repeatable').eq(0).clone();

        $this.before(
                repeat
                .addClass('clonned')
                );
        //$('.repeatable').each(function(){ $(this).find('input').val($(this).index()); });
    });


    $(document).on('click', '.remove-clonned', function() {
        $(this).parent().remove();
        return false;
    });

    if ($('.ttip').get(0)) {
        var ttContent = '<div class="ttip-content"></div>';
        $('html').append(ttContent);

        $('.ttip').each(function() {
            var $this = $(this);

            $this.hover(function() {
                var _Attr = $this.attr('data-tooltip');

                if ($(this).attr('data-tooltip') == "" || typeof ($(this).attr('data-tooltip')) === "undefined") {
                    $(".ttip-content").hide();
                } else {
                    $(".ttip-content").html(_Attr).show();
                }

            }, function() {
                $(".ttip-content").hide();
            });
        });

        $(document).mousemove(function(event) {
            //var mx = event.pageX - 15,
            var mx = event.pageX - $(".ttip-content").width() / 2,
                    my = event.pageY + 20;

            $(".ttip-content").css({
                "left": mx + "px",
                "top": my + "px"
            });
        });
    }

    /* [ 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 = $(".scrollable").outerHeight(),
                totalHeight = $(".scrollable").prop("scrollHeight"),
                scrollUnitHeight = (viewportHeight / totalHeight) * viewportHeight;
            if (viewportHeight == totalHeight) {
                $('.scrollable-holder').addClass('no-scroll');
            }
            $(".scrollable .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 = 30;

        if ($sidebar.get(0)) {
            $window.scroll(function() {
                $sidebar.css('margin-top',
                        ($window.scrollTop() > offset.top && $window.width() > 998) ? ($window.scrollTop() - offset.top + topPadding) : 0
                        );
            });
        }

    });
    /* datepick ======================================== */
    $('.apt-dp').on('click', function() {
        var $this = $(this),
                aptDp = $this.parent().find('.apt-datepick');
        if ($this.offset().top + 300 > $(window).scrollTop() + $(window).height()) {
            aptDp.css({'top': '-270px'});
        } else {
            aptDp.css({'top': '35px'});
        }

        console.log($this.offset().top, $(window).scrollTop() + $(window).height());

        aptDp.toggle();
    });

    $(document).mouseup(function(e) {
        var datepick = $(".apt-datepick");

        if (!datepick.is(e.target)
                && datepick.has(e.target).length === 0)
            datepick
        {
            datepick.hide();
        }
    });

    $('.dp-time li').on('click', function() {
        var
                $this = $(this),
                delTime = $this.data('time');

        //console.log(delTime);	

        $('.dp-time li').removeClass('active');
        $this.addClass('active');

        // TODO: replace `fit-els` with `delivery-date`
        var $select = $this.closest('.delivery-date').find('select[name="delivery-time"]');

        $select.find('option[value="' + delTime + '"]').prop('selected', true);
    });

    $('select[name="delivery-time"]').change(function() {
        var $this = $(this),
                $listTime = $this.closest('.delivery-date'); // TODO: replace `fit-els` with `delivery-date`
        $listTime.find('.dp-time li').removeClass('active');
        $listTime.find('.dp-time li[data-time="' + $this.val() + '"]').addClass('active');
    });
    /* / hidden-info / */
    $('.hidden-info .get').on('click', function() {
        var $this = $(this);
        $this.closest('.hidden-info').find('.set-vis').toggleClass('hidden');
        return false;
    });
    /* / 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;
    });
    /*user-addresses*/
    $('.set-address').on('click', function() {
        var $this = $(this);
        $('.address-to-set').removeClass('active').addClass('std');
        $this.parent('.address-to-set').addClass('active').removeClass('std');
        return false;
    });
    /* after-sign */
    $('.after-sign').on('click', function() {
        $('.to-account,.as-a-guest').addClass('hidden');
        $('.to-register, .to-guest, .has-signed').removeClass('hidden');
    });
    $('.add-new-address').on('click', function() {
        $('.new-address').removeClass('hidden');
        return false;
    });
    $('.cancel-na').on('click', function() {
        $('.new-address').addClass('hidden');
        return false;
    });
    /* building-type */
    $('select[name="building-type"]').on('change', function() {
        var $this = $(this),
                _name = $this.val();
        if (_name == 'stairs') {
            $('select[name="stairs"]').removeClass('hidden');
        } else {
            $('select[name="stairs"]').addClass('hidden');
        }
    });

    /* building-type */
    $('.select-el').on('change', function() {
        var $this = $(this),
                _selectVal = $this.find('select').val(),
                _fieldVal = $this.find('.select-field').attr('data-option');

        if (_selectVal == _fieldVal) {
            $('.select-field').removeClass('hidden');
        } else {
            $('.select-field').addClass('hidden');
        }
    });

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

    $('.elevator').on('click', function() {
        $('.stairs').hide('slow');
    });
    $('.walk-up').on('click', function() {
        $('.stairs').show('slow');
    });

    $('.doc-req .radio-btn').on('click', function() {
        var
                _proV = $('.provide-more-info');
        _proV.slideToggle('slow');
    });

    $('.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() {
        $('.gallery-images div').hover(
            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');
            },
            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").on('click', function() {
        var checkbox = $(this).find(':checkbox'),
                isChecked = checkbox.is(':checked');
        checkbox.attr('checked', !isChecked);
        if (!isChecked) {
            $(this).addClass("pickedColors")
        } else {
            $(this).removeClass("pickedColors");
        }
    });
    
/*    $(".picolors, .picolor").hover(function() {
        $(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").click(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 ================================================= */
    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);

    $(".secondary-menu li a").mouseenter(function() {
        $(".sub-cats").show();
    })
    .mouseleave(function() {
        $(".sub-cats").hide();
    });

    /* shop-menu ================================================= */
    $(".secondary-menu li:not(.apt-support) a").hover(function() {

        var menuIndex = jQuery(this).parent().index(),
                ulWidth = jQuery(".list-cols ul").outerWidth(true),
                ulPadLeft = parseInt(jQuery(".list-cols ul").css("padding-left")),
                menuOffset = parseInt(jQuery(this).offset().left),
                padLeft = parseInt(jQuery(".list-cols").css("padding-left")),
                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();
    });

    /* 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").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();
    });

    /*$('selector').on('change', function(){});*/

    /* 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, [id*="dp-"]').datepicker({
        showOtherMonths: true,
        selectOtherMonths: true,
        showOn: "both",
        buttonImage: "images/calendar.png",
        buttonImageOnly: true,
        prevText: "",
        nextText: "",
        constrainInput: false
    });

    $('[class*="time-"]').on('change', function() {
        var $this = $(this),
                $_parent = $this.closest('.delivery-date'),
                $dp = $_parent.find('.apt-dp');

        if ($dp.val() === '') {
            $this.val(0);
            $dp.datepicker('show');
        } else {

            var listDp = $('.delivery-date');
            listDp.each(function() {
                var $_this = $(this);
                var $localDp = $_this.find('.apt-dp');
                if ($localDp.val() == $dp.val() && $localDp.get(0) != $dp.get(0)) {
                    $_this.find('select option[value="' + $this.val() + '"]').prop('disabled', 'disabled');
                }
            });
        }
    });

    $('[id*="date-"]').datepicker({
        showOtherMonths: true,
        selectOtherMonths: true,
        showOn: "both",
        buttonImage: "images/calendar.png",
        buttonImageOnly: true,
        prevText: "",
        nextText: "",
        constrainInput: false,
        onSelect: function(date) {
            var $this = $(this);
            $_parent = $this.closest('.delivery-date'),
                    $dp = $_parent.find('.apt-dp');


            var listDp = $('.delivery-date');
            listDp.each(function() {
                var $_this = $(this);
                var $localDp = $_this.find('.apt-dp');

                if ($localDp.val() == $dp.val() && $localDp.get(0) != $dp.get(0)) {
                    $_parent.find('select option[value="' + $_this.find('select').val() + '"]').prop('disabled', 'disabled');
                }
            });
        }
    });

    /* (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,.suggestions-list, .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").show();
                if ($(this).val() == '') {
                    $("#search-suggestions").hide();
                }
            });

            $("#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 {
                                        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(6, 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];
            });

            /* getmobile menu ============================================ */
            $("#get-mobile-menu").click(function() {
                $(".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, .save-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, .save-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, .save-phone-info").show('slow');
                return false;
            });
            /* editPhoneInfo ============================================ */
            $("#editAddressInfo").click(function() {
                $(this).fadeOut();
                $(".def-address-field").hide();
                $(this).parent().addClass("opendEdit-block");
                $(".edit-address-field, .save-address-info").show('slow');
                return false;
            });
            /* add-phone-field =========================================== */
            $(".add-phone-field").click(function() {
                $(this).hide();
                $(".new-phone-field").css('display', 'block');
                return false;
            });
            /* editAccountDetails ======================================== */
            $("#editAccountDetails").click(function() {
                $(this).fadeOut();
                $(".def-account-field").hide();
                $(".edit-account-details, .save-account-details").show('slow');
                $(this).parent().addClass("opendEdit-block");
                return false;
            });
            /* editLoginDetails ========================================= */
            $("#editLoginDetails").click(function() {
                $(this).fadeOut();
                $(".def-login-details").hide();
                $(".edit-login-details, .save-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);
                    }
                });
            }

            $('#product-carousel').mCarousel();

        }); //<< end doc ready

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

            var wOver = wUl = maxL = null;

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

            init();

            function reset() {
                wUl = 0;
                wOver = $this.width();
                $this.find('li').each(function() {
                    wUl += $(this).width() + 2;
                });
                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);




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

var hideMeTimeout = null;

$('.dropdown-toggle').on('mouseover', function() {
    clearTimeout(hideMeTimeout);
    $(this).parent().find('.dropdown-menu').show();
});
$('.dropdown-toggle').on('mouseout', function() {
    hideMeTimeout = setTimeout(hideMe, 250);
});

$('.dropdown-toggle').parent().find('.dropdown-menu').on('mouseover', function() {
    clearTimeout(hideMeTimeout);
    $(this).parent().find('.dropdown-menu').show();
});
$('.dropdown-toggle').parent().find('.dropdown-menu').on('mouseout', function() {
    hideMeTimeout = setTimeout(hideMe, 250);
});

function hideMe()
{
    $('.dropdown-toggle').parent().find('.dropdown-menu').hide();
}

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

(function($) {
    $.fn.commaSeparated = function() {

        return this.each(function() {

            var
                    block = $(this),
                    field = block.find('input[type="text"]');

            field.keyup(function(e) {
                if (e.keyCode == 188) {
                    var $this = $(this);
                    var n = $this.val().split(",");
                    var str = n[n.length - 2];

                    if (str)
                        $(this).before('<span class="removeName">' + str + '<i class="apt-icon-x m-0"></i></span>');
                    $this.val('');
                    $("#add-new-tag").show();
                    field.hide();
                }
            });
        });

    };

    $(document).on('click', 'span.removeName .apt-icon-x', function() {
        $(this).closest('span').remove();
    });
    //fire commaSeparated
    $("#commaSep").commaSeparated();
})(jQuery);

