
"use strict";

var FUCKING_IE = (($.browser.msie) && ($.browser.version < 9));

$(function() {
    setupInputs({
        selector : '.r-inp'
    });

    $('input:checkbox')._checkbox();
    $('.slide-block').slideBlock();

    mainMenu({
        selector : '#main-menu'
    });

    basketBlock({
        selector: '#basket-block'
    });

    authBlock({
    });

    pageFilter({
        selector : '.filter'
    });

    galleries({
        selector : '.gallery',
        prPopup : '.pop-gallery'
    });

    bGallery({
        selector : '.big-gallery'
    });

    instantSearch({
        selector : '#search-block',
        ajaxUrl : '/search/ajax/'
    });

    basket({
        selector : '#basket'
    });

    form_contact({
        selector : '#form_contacts'
    });

    forms();

    $('#btnDiscount').click(ajax.basket.discount);
});

/** Форма на странице контактов **/
function form_contact(options) {
    var opt = $.extend({}, options);

    var $wrap = $(opt.selector);

    if($wrap.length)
    {
        $wrap.find("button").click(function(){
            var ret = true;

            $(".message").slideUp(0);

            $("#cnt_frm_have").removeClass("error");
            $("#cnt_frm_name").removeClass("error");
            $("#cnt_frm_email").removeClass("error");

            if( !setInputError( $("#cnt_frm_have") ) ) { ret = false;  /*$(".message").slideDown(200);*/  }
            if( !setInputError( $("#cnt_frm_name") ) ) { ret = false;  /*$(".message").slideDown(200);*/ }
            if( !setInputError( $("#cnt_frm_email") ) ) { ret = false; /*$(".message").slideDown(200);*/ }
            else if( !emailValidation( $("#cnt_frm_email") ) ) { ret = false; /*$(".message").slideDown(200);*/}

            if(ret == true)
            {
                $("#ajax_form").show(100);
                $.post('/form/contacts/', $("#form_contacts").serialize(), function(data){
                    $("#ajax_form").hide(100);
                    if(data == '1')
                    {
                        $("#form_contacts").hide(100).html("<h2 style='text-align: center'>Сообщение отправлено</h2>").show(100);
                    }
                    else
                    {
                        $(".message_2").show();
                    }
                });
            }
            return false;

        });
    }

    function setInputError( obj )
	{
		if(obj.val() == '')
		{
			obj.addClass('error').parent().find('.ph').show();
			return false;
		}
		return true;
	}

	function emailValidation( obj )
	{
		  var reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

		  if(reg.test(obj.val())==false)
		  {
			  obj.addClass('error').parent().find('.ph').show();
			  return false;
		  }
		  return true;
	}
};

function setupInputs(options) {
    var opt = $.extend({}, options);
    var selector = opt.selector + ' input:text,' + opt.selector + ' input:password,' + opt.selector + ' textarea,' + opt.selector + ' select';
    $(document.body).on('focus', selector, function() {
        var $p = $(this).parent();
        $p.addClass('focus');

        $p.find('.ph').hide();

    }).on('blur', selector, function() {
        var $p = $(this).parent().removeClass('focus');
        if (this.value === '')
            $p.find('.ph').show();
    });
}

function galleries(options) {
    $(options.selector).bfLightbox();
    $(options.prPopup).click(function(e) {
        e.preventDefault();
        $(this).parents('.item').eq(0).find('.gallery a').eq(0).triggerHandler('click');
    });
}

/** Блок авторизации **/
function authBlock(options) {
    var opt = $.extend({
        signinSelector : 'a[rel="signin"]',
        signupSelector : 'a[rel="signup"]'
    }, options);

    $(opt.signinSelector).click(signin);
    $(opt.signupSelector).click(signup);

    function signin(e) {
        e.preventDefault();
        Popup.show($('#signin-content').html() + '<hr />' + $('#oauth-content').html());
        Popup.$('form').submit(function(e) {
            e.preventDefault();
            ajax.user.login(Popup.$('form'));
        });
    }
    function signup(e) {
        e.preventDefault();
        Popup.show($('#signup-content').html() + '<hr />' + $('#oauth-content').html());
        Popup.$('form').submit(function(e) {
            e.preventDefault();
            ajax.user.register(Popup.$('form'), congratulations);
        });
    }
    function congratulations() {
        Popup.replace('<h1>Ура!</h1><p>Для вас заведен личный кабинет.</p><p>Мы отправили вам на почту письмо с подиверждением. Чтобы активировать свой кабинет пройдите по ссылке в тексте письма</p>');
    }
}

/** Блок с корзиной **/
function basketBlock(options) {
    var opt = $.extend({
        slideDuration : 250,
        scrollTimeout : 100,
        hideTimeout : 200,
        rightBar : '#center .aside.right'
    }, options);

    var $wrap = $(opt.selector);
    if (!$wrap.length)
        return;

    $wrap.mouseout(_hide).click(_hide).mouseover(_clearTimeout);
    var $more = $wrap.find('.more').mouseover(show),
        $c = $wrap.find('.content'),
        $z = $wrap.parents('.aside').eq(0),
        $right = $(opt.rightBar),
        shown = false,
        height = $c.height();

    var $list = $c.find('.list'),
        $ul = $list.find('ul'),
        $items = $ul.find('li'),
        sIndex = 0,
        hideTimeout = null,
        scrollTimeout = null,
        scrolling = false;

    function show() {
        if (!shown) {
            $z.stop().animate({
                'padding-bottom' : height
            }, opt.slideDuration, 'swing');
            $right.stop().animate({
                'margin-top' : height
            }, opt.slideDuration, 'swing');
            $c.stop().slideDown(opt.slideDuration);
            shown = true;
            $ul.scrollLeft(($items.eq(0).width() + 1) * sIndex);
            $more.find('.sarr').removeClass('down').addClass('up');
        }
    }
    function _hide() {
        _clearTimeout();
        hideTimeout = window.setTimeout(hide, opt.hideTimeout);
    }
    function hide() {
        if (shown) {
            $z.stop().animate({
                'padding-bottom': 0
            }, opt.slideDuration, 'swing');
            $right.stop().animate({
                'margin-top' : 0
            }, opt.slideDuration, 'swing');
            $c.slideUp(opt.slideDuration);
            shown = false;
            $more.find('.sarr').removeClass('up').addClass('down');
        }
    }

    function _clearTimeout() {
        if (hideTimeout)
            window.clearTimeout(hideTimeout);
    }

    if ($items.length > 4) {
        $ul.addClass('scr');
        var $bw = $(document.createElement('div'))
            .addClass('bw')
            .html('<button class="sbtn"><ins class="right"></ins></button> ')
            .appendTo($list)
            .find('button')
                .mousedown(scrollStart);
        $items.slice(0, 3).clone().appendTo($ul);
    }
    function scrollStart() {
        scrolling = true;
        scroll();
        $(document.body).one('mouseup', scrollStop);
    }
    function scrollStop() {
        scrolling = false;
        window.clearTimeout(scrollTimeout);
    }
    function scroll() {
        if (sIndex == $items.length) {
            sIndex = 0;
            $ul.scrollLeft(0);
        }
        sIndex++;
        $ul.animate({
            scrollLeft : ($items.eq(0).width() + 1) * sIndex
        }, opt.slideDuration, 'swing', scrollD);
    }
    function scrollD() {
        if (scrolling)
            scrollTimeout = window.setTimeout(scroll, opt.scrollTimeout);
    }
}

/** Главное меню **/
function mainMenu(options) {
    var opt = $.extend({
        slideDuration : 250
    }, options);

    var $wrap = $(opt.selector);
    if (!$wrap.length)
        return;

    $wrap.find('li.multi>a').click(function(e) {
        e.preventDefault();
        var $ul = $(this).parent();
        $ul.find('ul').stop().slideToggle(opt.slideDuration, function() { $ul.toggleClass('open'); });
    })
}

/** Большая галерея **/
function bGallery(options) {
    var opt = $.extend({
        scrollDuration : 300,
        scrollTimeout : 80,
        scrollAdjust : true,
        exCount : 3,
        previewFadeDuration : 200,
        previewShowTimeout : 100
    }, options);

    var $wrap = $(opt.selector);
    if (!$wrap.length)
        return;

    var $body = $(document.body);
    var $scroll = $wrap.find('.scroll'),
        $line = $wrap.find('.line'),
        $items = $line.find('.item'),
        $sc = $scroll.find('.sc'),
        $scLine = $sc.parent(),
        length = $items.length,
        gallery = false;

    if ($items.length < 3) {
        $scroll.remove();
        return;
    }

    $items.slice(0, opt.exCount).clone().addClass('extend').appendTo($items.parent()).find('a').attr('id','').click(redirectClick);
    $items.slice(length - opt.exCount, length).clone().addClass('extend').prependTo($items.parent()).find('a').attr('id','').click(redirectClick);
    $items = $line.find('.item');

    if ($line.hasClass('gallery')) {
        gallery = true;
    }

    var _loaded = 0;
    var $img = $items.find('.i img');
    $img.each(_imageLoad);


    var areaWidth, scrWidth, scrLeft, scrollWidth, leftOffset, rightOffset;

    metrics();

    var pos = 0, _pos = 0, direction = 0, timeout = 0, scrolling = false, dragging = false;
    var origX = 0, mouseX = 0;
    $scroll.find('.sarr').mousedown(scroll);
    $sc.mousedown(startDrag);
    $scLine.parent().mousedown(scrollOnLine);

    var resizeTimeout;
    window.setTimeout(function() {
        scrollTo(0);
        $(window).resize(function() {
            if (resizeTimeout)
                window.clearTimeout(resizeTimeout);
            resizeTimeout = window.setTimeout(__resize, 500);
        });
    }, 20);

    function redirectClick(e) {
        e.stopPropagation();
        e.preventDefault();
        if($('#pic_'+$(this).attr('rel')).length)
        {
            $('#pic_'+$(this).attr('rel')).click();
        }
        else
        {
            window.location = $(this).attr("href");
            return true;
        }
    }

    function __resize() {
        metrics();
        scrollTo(pos);
    }

    function scrollTo(position, callback) {
        pos = position;
        var item = $items.get(position + opt.exCount);
        if (!item) return;
        var left = item.offsetLeft,
            width = item.clientWidth,
            scrollLeft = left - (areaWidth - width) / 2;
        if (gallery) {
            scrollLeft += width / 2;
        }
        $sc.animate({
            left : scrWidth * pos / (length - 1)
        }, opt.scrollDuration, 'swing');
        $line.animate({
            scrollLeft : scrollLeft
        }, opt.scrollDuration, 'swing', callback);
    }

    function scroll(e) {
        if ((e) && (e.preventDefault)) {
            e.preventDefault();
            e.stopPropagation();
            scrolling = true;
            direction = ($(this).hasClass('left')) ? -1 : 1;
            $body.one('mouseup', stopScroll);
        }
        var position = pos + direction;
        if (position === length) {
            position = 0;
        } else if (position < 0) {
            position = length - 1;
        }
        scrollTo(position, _scroll);
    }

    function _scroll() {
        if (scrolling) {
            timeout = window.setTimeout(scroll, opt.scrollTimeout);
        }
    }

    function stopScroll() {
        scrolling = false;
        window.clearTimeout(timeout);
    }

    function startDrag(e) {
        e.preventDefault();
        e.stopPropagation();
        mouseX = e.pageX;
        origX = $sc.position().left;
        dragging = true;
        $body.one('mouseup', stopDrag);
        $body.on('mousemove.bgallery_drag', drag);
    }

    function stopDrag() {
        dragging = false;
        $body.off('mousemove.bgallery_drag');
        pos = Math.round(_pos);
        if (opt.scrollAdjust) {
            scrollTo(pos);
        }
    }

    function drag(e) {
        e.preventDefault();
        if (dragging) {
            var left = e.pageX + (origX - mouseX);
            if (left < 0) {
                left = 0;
            } else if (left > scrWidth) {
                left = scrWidth;
            }
            $sc.css({
                left : left
            });
            _pos = (left / scrWidth) * (length - 1);
            var item = $items.get(Math.floor(_pos) + opt.exCount),
                left = item.offsetLeft,
                width = item.clientWidth,
                scrollLeft = left - (areaWidth - width) / 2 + ((_pos - Math.floor(_pos)) * width);
            if (gallery) {
                scrollLeft += width / 2;
            }
            $line.scrollLeft(scrollLeft);
        }
    }

    function scrollOnLine(e) {
        e.stopPropagation();
        var left = e.pageX - scrLeft,
            pos = Math.round((left / scrWidth) * (length - 1));
        scrollTo(pos);
    }

    var $preview, $pimg, pimg, poffset, pwidth, pheight, $porig, $prec, rwidth, rheight, ratioH, ratioW,inPreview = false;
    function startPreview() {
        inPreview = true;
        $porig = $(this);
        pimg = new Image();
        pimg.onload = loadPreview;
        pimg.src = this.href;

    }

    function stopPreview() {
        inPreview = false;
        if (pimg) pimg.onload = null;
        if ($porig) {
            $porig.parent().removeClass('in-preview');
            $porig.unbind('mousemove.preview');
        }
        if ($preview) $preview.remove();
        if ($prec) $prec.remove();
        $porig = null;
        $preview = null;
        $prec = null;
    }
    function loadPreview() {
        if (!inPreview)
            return;
        pwidth = $porig.width();
        pheight = $porig.height();
        poffset = $porig.offset();
        var mSign = (poffset.left + pwidth / 2 > document.body.scrollWidth / 2) ? -1 : 1
        $porig.parent().addClass('in-preview');
        $preview = $(document.createElement('div'))
            .addClass('preview')
            .css({
                'position' : 'absolute',
                'overflow' : 'hidden',
                'zIndex' : 999,
                'left' : 0,
                'top' : 0,
                'width' : pwidth,
                'height' : pheight,
                'margin-left' : mSign * pwidth
            })
            .hide()
            .appendTo($porig.parent());

        ratioW = (pwidth / this.width);
        ratioH = (pheight / this.height);
        rwidth = ratioW * pwidth;
        rheight = ratioH * pheight;
        $prec = $(document.createElement('span'))
            .addClass('p-rect')
            .css({
                'position' : 'absolute',
                'z-index' : 999,
                'left' : -999,
                'top' : -999,
                'width' : rwidth,
                'height' : rheight
            })
            .hide()
            .appendTo($porig);
        rwidth = $prec.outerWidth();
        rheight = $prec.outerHeight();
        $pimg = $(this).css({ 'position' : 'absolute' }).appendTo($preview.fadeIn(opt.previewFadeDuration));
        $porig.bind('mousemove.preview', movePreview).triggerHandler('mousemove.preview');
    }

    function movePreview(e) {
        e.preventDefault();
        var left = Math.min(Math.max(e.pageX - poffset.left - rwidth / 2, 0), pwidth - rwidth),
            top = Math.min(Math.max(e.pageY - poffset.top - rheight / 2, 0), pheight - rheight);
        $prec.show().css({
            left : left,
            top : top
        });
        $pimg.css({
            left : -left / ratioW,
            top : -top / ratioH
        });
    }

    function metrics() {
        $items.css({ height : $line.height() });
        $img.each(_adjustWidth);
        $line.hide().show();
        areaWidth = $line.width();
        scrWidth = $scLine.width();
        scrLeft = $scLine.offset().left;
    }

    function _imageLoad() {
        if (this.complete) {
            __iload.call(this);
        } else {
            this.onload = __iload;
        }
    }
    function __iload() {
        this._ratio = this.width / this.height;
        _loaded++;
        _adjustWidth.call(this);
        if (gallery) {
            $(this).parents('a').eq(0).mouseenter(startPreview).mouseleave(stopPreview);
        }
        if (_loaded == $img.length) {
            scrollTo(pos);
        }
    }

    function _adjustWidth() {
        var $t = $(this),
            $p = $t.parent();
        var h = $p.height(),
            w = h * this._ratio;
        $(this).css({
            width : w,
            height : h
        });
    }
}

function pageFilter(options) {
    var opt = $.extend({
    }, options);

    var $wrap = $(opt.selector);
    if (!$wrap.length)
        return;

    var $selects = $wrap.find('.select').each(select);

    function select() {
        var $el = $(this),
            $popup = $el.find('.list'),
            input = $el.find('input'),
            popupWidth = $popup.width(),
            width = $el.width() + 6,
            shown = false;

        if (width > popupWidth) {
            $el.width(width);
            $popup.css({ width : '100%' });
        } else {
            $el.width(popupWidth);
        }
        $el.find('.active').click(show);
        $el.find('li a').click(select);
        $el.find('li.hide a').click();
        $el.find('li a').click(function(){
            document.getElementById('searchForm').submit();
        });


        function show(e) {
            if (shown) {
                return hide(e);
            }
            $el.addClass('open');
            $popup.stop().fadeIn(200);
            shown = true;
            window.setTimeout(function() {
                $(document.body).bind('click.filter_select', hide);
            }, 10);
        }
        function hide(e) {
            e.stopImmediatePropagation();
            e.preventDefault();
            $el.removeClass('open');
            $popup.stop().fadeOut(200);
            $(document.body).unbind('click.filter_select');
            shown = false;
        }
        function select(e) {
            e.preventDefault();
            $el.find('li.hide').removeClass('hide');
            $el.find('.active').html(this.innerHTML + '<ins></ins>');
            $(this).parents('li').eq(0).addClass('hide');
            input.val($(this).attr('href'));
        }
    }
}

function forms() {
    $('input.date').datePicker();
    $('.time-range').timerange();
    $('input#jur').bind('click.jur', function() {
        var $bl = $(this).parents('.form').eq(0).find('.jur');
        if ($(this).attr('type') == 'checkbox' && this.checked || $(this).attr('type') == 'hidden' && $(this).val() == 2) {
            $bl.show();
        } else {
            $bl.hide();
        }
    }).triggerHandler('click.jur');


    $('#frmCabinet').submit(function(e){
        e.stopPropagation();
        e.preventDefault();

        ajax.user.save($(this));
    });
}

function instantSearch(options) {
    var opt = $.extend({}, {
        /*timeout : 500,*/
        timeout : 50,
        minLength : 3,
        fadeDuration : 300,
        ajaxTimeout : 10000
    }, options);

    var $wrap = $(opt.selector);

    if (!$wrap.length) return false;

    var $input = $wrap.find('input').keydown(keydown).keypress(keydown).val(''),
        $popup = $wrap.find('.instant-popup').hide(),
        $in = $popup.find('.in'),
        $load = $wrap.find('.load');
    var val = $input.val(),
        timeout = null;

    function keydown(e) {
        _setTimeout();
    }

    function _clearTimeout() {
        if (timeout) {
            window.clearTimeout(timeout);
        }
    }

    function _setTimeout() {
        _clearTimeout();
        timeout = window.setTimeout(check, opt.timeout);
    }

    function check() {
        var newVal = $input.val();
        if (newVal.length >= opt.minLength) {
            if (val !== newVal) {
                val = newVal;
                go();
            }
        } else {
            val = newVal;
            hide();
        }
    }

    function go() {
        $load.show();
        $.ajax({
            url : opt.ajaxUrl,
            cache : true,
            dataType : 'html',
            data : {
                query : val
            },
            type : 'GET',
            timeout : opt.ajaxTimeout,
            success : parseResponse
        });
    }

    function parseResponse(html) {
        $load.hide();
        if (html) {
            $in.html(html);
            show();
        }
    }

    var $body = $(document.body);

    function show() {
        if (FUCKING_IE) {
            $popup.show();
        } else {
            $popup.fadeIn(opt.fadeDuration);
        }
        $body.bind('mousedown.instant_search', checkHide);
    }

    function hide() {
        if (FUCKING_IE) {
            $popup.hide();
            $in.empty();
        } else {
            $popup.fadeOut(opt.fadeDuration, function() { $in.empty(); });
        }

        $body.unbind('mousedown.instant_search');
    }

    var _w = $wrap.get(0);
    function checkHide(e) {
        var obj = e.target;
        while ((obj !== _w) && (obj = obj.parentNode));
        if (obj !== _w) {
            e.preventDefault();
            hide();
        }
    }

}

function basket(options) {
    var opt = $.extend({}, {
        maxTest : 3
    }, options);

    var $wrap = $(opt.selector);
    var testCount = 0;

    if (!$wrap.length) return false;

    var $counters = $wrap.find('.count input:text').cTicker();
    $counters.bind('delete', onDelete);
    $counters.bind('change', onChange);

    var $checks = $wrap.find('.count input:checkbox').click(testClick);
    $checks.filter(':checked').triggerHandler('click');

    var $right = $('#center .aside.right'),
        rightTop = $right.find('h2').eq(0).offset().top;

    var $w = $(window).scroll(_rightCheck).resize(_rightCheck);


    function testClick() {
        var ticker = $(this).parents('.count').eq(0).find('input:text').eq(0).data('cticker');
        if (this.checked) {
            if (testCount < opt.maxTest) {
                testCount++;
                if (ticker) {
                    ticker.disabled(true);
                    ticker.val(1);
                }
            } else {
                this.checked = false;
                $(this)._checkbox(true);
            }

        } else {
            testCount--;
            if (ticker) {
                ticker.disabled(false);
                ticker.val(1);
            }
        }
    }

    function onDelete() {
        // Test;
        $(this).parents('.item').eq(0).remove();
    }

    function onChange() {
        //TODO !!!
    }

    function _rightCheck() {
        if (rightTop < $w.scrollTop() + 24) {
            $right.addClass('aside-fix');
        } else {
            $right.removeClass('aside-fix');
        }
    }

}

/** Overlay **/
var Overlay = (function() {
    var $overlay;

    function _draw() {
        $overlay = $(document.createElement('div'))
            .addClass('overlay')
            .html('<ins></ins>')
            .appendTo(document.body);
        Overlay.$ = $overlay;
    }

    return {
        show : function(callback) {
            if (!$overlay)
                _draw();
            $overlay.stop().fadeIn(100, callback);
        },

        hide : function(callback, delay) {
            $overlay.delay(delay).fadeOut(100, callback);
        }
    };
})();

/** Popup **/
var Popup = (function() {
    var $popup, _callback = null;

    function _draw() {
        $popup = $(document.createElement('div'))
            .addClass('popup')
            .html('<div class="inner"></div><span class="close"></span>')
            .hide()
            .appendTo(document.body);
        $popup.find('.close').click(function() { close(); });
    }

    function content(html) {
        if (!$popup)
            _draw();
        $popup.find('.inner').html(html);
    }

    function show() {
        $popup.css({
            top : _top()
        });
        $popup.show().animate({
            top : 0
        }, 350, 'swing', __callback);
        $(window).bind('keydown.popup', _keydown);
        Overlay.$.bind('click.popup', function() { close(); });
    }

    function close(saveOverlay) {
        $(window).unbind('keydown.popup');
        Overlay.$.unbind('click.popup');
        $popup.animate({
            top : _top()
        }, 350, 'swing', _hideCallback);
        if (!saveOverlay)
            Overlay.hide(null, 150);

    }

    function _top() {
        return -$popup.height() - 100;
    }

    function _hide() {
        $popup.hide();
    }

    function __callback() {
        if (_callback)
            _callback();
    }

    function _hideCallback() {
        _hide();
        __callback();
    }
    function _keydown(e) {
        if (e.which == 27) {
            close();
        }
    }

    return {
        show : function(html, callback) {
            content(html);
            _callback = callback;
            Overlay.show(show);
        },
        hide : function(callback) {
            _callback = callback;
            close();
        },
        replace : function(html, callback) {
            _callback = function() {
                content(html);
                _callback = callback;
                show();
            };
            close(true);
        },
        $ : function(selector) {
            return $popup.find(selector);
        }
    };
})();
/**
* Custom checkboxes
*/
(function() {

    function update() {
        var $checkbox = $(this);
        if ($checkbox.data('ch-wrap'))
            return;
        var $wrap = $(document.createElement('span')).addClass('ch-wrap').click(_click);
        if (this.type === 'radio') {
            $wrap.addClass('ch-radio');
        }
        $checkbox.data('ch-wrap', $wrap);
        $checkbox.bind('click.chwrap', change);
        $checkbox.css({
            'visibility' : 'hidden'
        }).wrap($wrap);

        change.call(this);
    }

    function _click(e) {
        e.preventDefault();
        e.stopPropagation();
        var $input = $(this).find('input'),
            input = $input[0];
        if (!input.disabled) {
            if ((input.type !== 'radio') || (!input.checked)) {
                input.checked = !input.checked;
            }
        }
        $input.triggerHandler('click');

        var searchForm = document.getElementById('searchForm');
        if (searchForm != null)
            document.getElementById('searchForm').submit();
        else {
            var updId = $(input).attr('rel');
            if (updId)
                ajax.basket.choose(updId, 'item', input.checked);
            else
            {
                updId = $(input).attr('rev');
                ajax.basket.choose(updId, 'set', input.checked);
            }
        }
    }

    function change(e) {
        if ((e) && (e.stopPropagation)) {
            e.stopPropagation();
        }
        var $w = $(this).parent();
        if (this.checked) {
            $w.addClass('checked');
            if (this.type === 'radio') {
                $('input[name="' + this.name + '"]').not(this).each(change);
            }
        } else {
            $w.removeClass('checked');
        }

    }

    $.fn._checkbox = function(changeFlag) {
        if (changeFlag) {
            this.each(change);
        } else {
            this.each(update);
        }

        return this;
    };


})();

/** count input **/
(function() {

    var DEFAULT_OPTIONS = {
        min : 1,
        max : 999,
        tickTimeout : 150
    };

    var HTML = '<span class="inp"><span class="m">шт.</span><span class="up"></span><span class="down"></span></span><span class="del"></span>';
    var counter = null;
    function CTicker(el, options) {
        this.$input = $(el);
        this.opt = $.extend({}, DEFAULT_OPTIONS, options);
        this.$input.data('cticker', this);
        this._draw();
    }
    CTicker.prototype = {
        _draw : function() {
            var self = this;
            this.$wrap = $(document.createElement('span'))
                .addClass('cticker')
                .html(HTML)
                .insertAfter(this.$input);
            this.$input.prependTo(this.$wrap.find('.inp'));
            this.$input
                .attr({'maxlength' : this.opt.max.toString().length})
                .focus(function() { self.$wrap.addClass('focus'); })
                .blur(function() { self.$wrap.removeClass('focus'); })
                .keyup(function() {self._update($(this));});

            var attr = (this.$input.attr('rel')) ? {rel:this.$input.attr('rel')} : {rev:this.$input.attr('rev')};

            this.$wrap.find('.up, .down').attr(attr).mousedown(function(e) {
                e.stopPropagation();
                e.preventDefault();
                self._dir = $(this).hasClass('down') ? -1 : 1;
                self._startTick();
                counter = $(this);
            });
            this.$wrap.find('.del').attr(attr).click(function(e) {
                e.stopPropagation();
                e.preventDefault();

                var updId = $(this).attr('rel');
                if (updId)
                    ajax.basket.del(updId, 'item');
                else
                {
                    updId = $(this).attr('rev');
                    ajax.basket.del(updId, 'set');
                }

                self.del();
            });
        },
        _startTick : function() {
            if (this._disabled) {
                return;
            }
            var self = this;
            this._tick();
            this._timeout = window.setInterval(function() { self._tick(); }, this.opt.tickTimeout);
            $(document.body).bind('mouseup.cticker', function() {
                self._update(counter);
                self._stopTick();
            })
        },
        _update : function(counter) {
            var updId = counter.attr('rel');
            if (updId)
                ajax.basket.update(updId, 'item', counter.parent().find('input').val());
            else
            {
                updId = counter.attr('rev');
                ajax.basket.update(updId, 'set', counter.parent().find('input').val());
            }
        },
        _tick : function() {
            var val = Math.max(Math.min(this.$input.val()*1 + this._dir, this.opt.max), this.opt.min);
            this.$input.val(val);
        },
        _stopTick : function() {
            window.clearTimeout(this._timeout);
            $(document.body).unbind('mouseup.cticker');
            this.$input.trigger('change');
        },
        val : function(value) {
            this.$input.val(value).trigger('change');
        },
        disabled : function(disabled) {
            this._disabled = disabled;
            if (this._disabled) {
                this.$wrap.addClass('disabled');
            } else {
                this.$wrap.removeClass('disabled');
            }
            return this._disabled;
        },
        del : function() {
            this.$input.trigger('delete');
        }
    };

    $.fn.cTicker = function() {
        return this.each(function(options) {
            (new CTicker(this, options));
        });
    };
})();

/** block with arrow **/
(function() {
    var DEFAULT_OPTIONS = {
        slideDuration : 200,
        autoresize : false,
        resizeParent : false
    };

    var blocks = [];

    function SlideBlock(el, options) {
        this.opt = $.extend({}, DEFAULT_OPTIONS, options);
        this.$el = $(el);
        this._height = this.$el.height();
        if (this.$el.data('autoresize')) {
            this.opt.autoresize = true;
            this._$links = this.$el.find('a');
        }
        this._draw();
        this.check();
        this.$el.css({
            'height' : this._height,
            'max-height' : 'none'
        });
        this.open = false;
        blocks.push(this);
    }

    SlideBlock.prototype = {
        _draw : function() {
            var self = this;
            function _toggle(e) {
                e.stopPropagation();
                e.preventDefault();
                self.toggle();
            }
            this.$aw = $(document.createElement('span'))
                .addClass('sarr-w')
                .hide()
                .html('<span class="sarr down"></span>')
                .appendTo(this.$el);
            this.$arr = this.$aw.find('.sarr').click(_toggle);
            this.$el.parents('.p-line').find('a[rel="toggle"]').click(_toggle);

        },

        check : function() {
            var __w = $(document.body).width();
            if (this.__w === __w)
                    return;
            this.__w = __w;
            var open = this.open;
            if (this.opt.autoresize) {
                this.$el.css('width', 'auto');
            }
            if (open) {
                this.toggle(true);
            }
            if (this.$el[0].scrollHeight > this.$el[0].clientHeight + 10) {
                this.$aw.show();
                if (this.opt.autoresize) {
                    for (var i = 1; i < this._$links.length; i++) {
                        if (this._$links[i].offsetTop > this._height) {
                            var w = this._$links[i-1].offsetLeft + this._$links[i-1].offsetWidth;
                            this.$el.css('width', w);
                            break;
                        }
                    }
                }
            } else {
                this.$aw.hide();
            }
            if (open) {
                this.toggle(true);
            }
        },

        toggle : function(fast) {
            var height = (this.open) ? this._height : this.$el[0].scrollHeight;
            if (fast) {
                this.$el.stop().height(height);
            } else {
                this.$el.stop().animate({
                    'height' : height
                }, this.opt.slideDuration, 'swing');
            }
            this.$arr.toggleClass('up').toggleClass('down');
            this.open = !this.open;
        }
    };

    function checkAll() {
        $.each(blocks, SlideBlock.prototype.check);
    }

    $.fn.slideBlock = function(options) {
        this.each(function() {
            new SlideBlock(this, options)
        });
    }
    $(window).resize(checkAll).load(checkAll);
})();

(function() {

    $.fn.autofillImage = function() {
        this.each(function() {
            $(this).css('visibility', 'hidden').parent().css({
                'background' : 'url(' + this.src + ') 50% 0 no-repeat',
                'background-size' : 'cover'
            });
        });
    }

})();

/** lightbox **/
(function() {

    var DEFAULT_OPTIONS = {
        boxFadeDuration : 150,
        imageFadeDuration : 300,
        thumbSlideDuration : 250
    };

    var HTML = '<div class="photo"></div><div class="prev aw"><span></span></div><div class="next aw"><div class="close"></div><span></span></div><div class="thumbs-o"><div class="thumbs-wrap"><div class="thumbs"></div></div><span class="sc scl"></span><span class="sc scr"></span></div>';

    var $box = null, current = null, $thumbs = null, $thumbsWrap = null, $photo = null, $aw = null, $scr = null, $scl = null;


    function LightBox($links, options) {
        var self = this;
        this.opt = $.extend({}, DEFAULT_OPTIONS, options);
        this.$links = $links;
        $links.click(function(e) {
            e.preventDefault();
            self.show(self.$links.index(this));
        })
    }

    LightBox.prototype = {
        constructor : LightBox,

        show : function(index) {
            if (!$box)
                draw();
            current = this;
            generateThumbs(this.$links);
            $box.fadeIn(this.opt.boxFadeDuration, _thumbs);
            this.load(index);
            $(window).bind('resize.lightbox', _resize);
            $(window).bind('keydown.lightbox', _esc);
        },

        load : function(index) {

            this.index = index;
            scrollThumbs();
            var img = new Image()

            var href = this.$links[this.index].href;
            
            if(href.indexOf("#video_") > 0)
            {
                showVideo( href );
            }
            else
            {
                img.onload = showImage;
                img.src = this.$links[this.index].href;
            }
        },

        next : function() {
            var index = this.index + 1;
            if (index == this.$links.length)
                index = 0;
            this.load(index);
        },

        prev : function() {
            var index = this.index - 1;
            if (index < 0)
                index = this.$links.length - 1;
            this.load(index);
        },

        close : function() {
            current = null
            $box.fadeOut(this.opt.boxDadeDuration, _clean);
            $(window).unbind('resize.lightbox');
            $(window).unbind('keydown.lightbox');
        }
    }

    function draw() {
        $box = $(document.createElement('div'))
            .hide()
            .addClass('lightbox')
            .html(HTML)
            .appendTo(document.body);
        $thumbs = $box.find('.thumbs');
        $thumbsWrap = $thumbs.parent();
        $photo = $box.find('.photo').click(next);
        $aw = $box.find('.aw');
        $box.find('.close').click(function(e) { e.stopImmediatePropagation(); close(); });
        $box.find('.next').click(next);
        $box.find('.prev').click(prev);
        $scr = $box.find('.scr').mousedown(scrollThumbsRight);
        $scl = $box.find('.scl').mousedown(scrollThumbsLeft);
    }
    function _clean() {
        $thumbs.empty();
        $photo.empty();
    }
    function close() {
        if (current)
            current.close();
    }

    function generateThumbs($links) {
        $thumbs.empty();
        for (var i = 0; i < $links.length; i++) {
            var $thumb = $(document.createElement('a'))
                .attr('href', $links[i].href)
                .click(thumbClick);
            var img = $links.eq(i).find('img')[0];
            var src = img ? img.src : $links[i].href;

            $thumb.html('<img src="' + src +'">').appendTo($thumbs);

        }
        thumbsResize();
    }
    function thumbClick(e) {
        e.preventDefault();
        if (current)
            current.load($thumbs.find('a').index(this));
    }

    function scrollThumbs() {

        if (current) {
            var $thumb = $thumbs.find('a').removeClass('active').eq(current.index).addClass('active');
            var img = $thumb.find('img')[0];

            var left =  $thumb[0].offsetLeft + $thumb.outerWidth() / 2 - $thumbsWrap.width() / 2;
            $thumbsWrap.animate({
                scrollLeft : left
            }, current.opt.thumbSlideDuration, 'swing');
        }
    }

    var scrollInterval, scrollDirection;
    function scrollThumbsLeft() {
        startThumbsScroll(-1);
    }
    function scrollThumbsRight() {
        startThumbsScroll(1);
    }
    function startThumbsScroll(direction) {
        scrollDirection = direction;
        stopThumbsScroll();
        scrollInterval = window.setInterval(_scrollThumbs, 10);
        $(document.body).one('mouseup', stopThumbsScroll);
    }
    function stopThumbsScroll() {
        if (scrollInterval)
            window.clearInterval(scrollInterval);
    }
    function _scrollThumbs() {
        $thumbsWrap[0].scrollLeft += scrollDirection * 4;
    }

    function showVideo( $link )
    {
        $link = $link.split('#');

        if($('#'+$link[1]).length)
        {
            var obj = $('#obj_'+$link[1]);
            obj._width  = 457;
            obj._height = 373;
            resize(obj);
            obj.css("position","fixed").css("left","50%").css("top","50%").css("margin-left","-228px").css("margin-top","-186px");

            $photo.find('img').fadeOut(current.opt.imageFadeDuration, _remove);
            $photo.html( $('#'+$link[1]).html() );

            _thumbs();
        }
    }

    function showImage() {
        if (current) {
            this._width = this.width;
            this._height = this.height;
            resize(this);
            $photo.find('object').fadeOut(current.opt.imageFadeDuration, _remove);
            $photo.html("");
            $(this).hide().appendTo($photo).fadeIn(current.opt.imageFadeDuration);
            _thumbs();
        }
    }

    function _resize() {

        if($photo.find('img').length)
        {
            resize($photo.find('img').last()[0]);
        }
        else
        {
            resize($photo.find('object').last()[0]);
        }
        _thumbs();
    }

    function _thumbs() {
        thumbsResize();
        scrollThumbs();
    }

    function next() {
        if (current)
                current.next();
    }

    function prev() {
        if (current)
                current.prev();
    }

    function resize(image) {
        var w = image._width,
            h = image._height,
            maxWidth = $photo.width(),
            maxHeight = $photo.height();

        if (w > maxWidth) {
            h = h * (maxWidth / w);
            w = maxWidth;
        }
        if (h > maxHeight) {
            w = w * (maxHeight / h);
            h = maxHeight;
        }
        $aw.css({
            width : 70 + ((maxWidth - w) / 2)
        });
        $(image).css({
            width : w,
            height : h,
            marginLeft : -w / 2,
            marginTop : -h / 2
        });
    }

    function thumbsResize() {
        if ($thumbsWrap[0].scrollWidth > $thumbsWrap[0].clientWidth) {
            $scr.show();
            $scl.show();
        } else {
            $scr.hide();
            $scl.hide();
        }
    }

    function _remove() {
        $(this).remove();
    }

    function _esc(e) {
        if ((e.which == 27) && (current)) {
            current.close();
        }
    }

    $.fn.bfLightbox = function(options) {
        if (!this[0])
                return;
        if (this[0].tagName === 'A') {
            (new LightBox(this, options))
        } else {
            this.each(function() {
                new LightBox($(this).find('a'), options);
            });
        }
    }
})();

/** time range **/
(function() {

    function TimeRange(el) {
        this.$el = $(el);
        this._init_();
    }

    TimeRange.prototype = {
        _init_ : function() {
            var self = this;
            function downtimeout() {
                if (self._ktimeout) {
                    window.clearTimeout(self._ktimeout);
                }
                self._ktimeout = window.setTimeout(chup, 30);
            }
            function chup() {
                if (self._ktimeout) {
                    window.clearTimeout(self._ktimeout);
                }
                if (self.check())
                    self.update();
            }
            var $inputs = this.$el.find('input')
                .attr('maxlength', 2)
                .keydown(downtimeout)
                .keyup(chup)
                .blur(function() {
                    this.value = $inputs.index(this) == 0 ? self.min : self.max;
                });
            this.$min = $inputs.eq(0);
            this.$max = $inputs.eq(1);
            this.$line = $(document.createElement('span'))
                .addClass('ln')
                .mousedown(function(e) {
                    self._startDrag(e);
                })
                .appendTo(this.$el);
            this.$ac = $(document.createElement('span'))
                .addClass('ac')
                .appendTo(this.$line);
            this.$minS = $(document.createElement('span'))
                .addClass('sl')
                .appendTo(this.$line);
            this.$maxS = $(document.createElement('span'))
                .addClass('sl')
                .appendTo(this.$line);
            this.check();
            this.update();
        },
        update : function() {
            var l = (this.min - 9) * 12,
                r = (this.max - 9) * 12;
            this.$minS.css('left', l);
            this.$maxS.css('left', r);
            this.$ac.css({
                left : l,
                width : r - l
            });
            this.$min.val(this.min);
            this.$max.val(this.max);
        },
        check : function(what, val) {
            var min = parseInt(what === 'min' ? val : this.$min.val()),
                max = parseInt(what === 'max' ? val : this.$max.val());
            if ((min >= 9) && (max >= 9) && (min <= 22) && (max <= 22) && (min <= max)) {
                this.min = min;
                this.max = max;
                return true;
            }
            return false;
        },
        _startDrag : function(e) {
            var self = this;
            e.stopPropagation();
            e.preventDefault();
            var x = e.pageX;
            var minL = this.$minS.offset().left + this.$minS.width() / 2;
            var maxL = this.$maxS.offset().left + this.$maxS.width() / 2;
            this._sl = this.$line.offset().left;
            this._p = (Math.abs(x - minL) > Math.abs(x - maxL)) ? 'max' : 'min';
            this._drag(e);
            $(document.body).bind('mousemove.timerange', function(e) { self._drag(e); });
            $(document.body).one('mouseup', function(e) { self._stopDrag(e); });
        },
        _drag : function(e) {
            e.preventDefault();
            e.stopPropagation();
            var c = Math.round((e.pageX - this._sl) / 12) + 9;
            if (this.check(this._p, c)) {
                this.update();
            }
        },
        _stopDrag : function(e) {
            $(document.body).unbind('mousemove.timerange');
        }
    };


    $.fn.timerange = function() {
        this.each(function() {
            (new TimeRange(this));
        });
    };
})();

/**
* DatePickers
*/
(function() {
    $.datepicker.setDefaults({
        currentText : 'Сегодня',
        dateFormat : 'dd.mm.yy',
        minDate : 0,
        dayNames : [ 'Воскресенье', 'Понедельник', 'Вторник', 'Среда',
                'Четверг', 'Пятница', 'Суббота' ],
        dayNamesMin : [ 'Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб' ],
        dayNamesShort : [ 'Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб' ],
        firstDay : 1,
        monthNames : [ 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
                'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь' ],
        monthNamesShort : [ 'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл',
                'Авг', 'Сен', 'Окт', 'Ноя', 'Дек' ],
        nextText : '',
        prevText : '',
        weekHeader : 'Нед',
        showWeek : false
    });

    var $popups = {},
        $datepickers = {},
        current = null;

    function DatePicker(el, options) {
        var self = this;
        this.$input = $(el);
        this.shown = false;
        this.options = $.extend({}, options);
        this._name = this.options.name || 'datepicker';
        this._$button = $(document.createElement('span'))
            .addClass('btn')
            .html('<ins class="date"></i>')
            .mousedown(function(e) { e.preventDefault(); e.stopImmediatePropagation(); self.toggle(); })
            .insertAfter(this.$input);
        this.$popup = createPopup(this._name);
        this.$datepicker = $datepickers[this._name];
        this.$wrap = this.$input.parents('.r-inp').eq(0).parent();
        if (this.$wrap.length) {
            this.$wrap.append('<span class="date-i-z"></span>');
        }
    }

    DatePicker.prototype = {
        toggle : function() {
            if (this.shown) {
                this.hide();
            } else {
                this.show();
            }
        },
        show : function() {
            if (this.$input.prop('disabled')) {
                return;
            }
            if ((current) && (current.shown))
                current.hide();
            current = this;
            this.$datepicker.datepicker('setDate', this.$input.val());
            this.$wrap.addClass('active');
            var offset = this.$input.offset();
            this.$popup.show().css({
                left : offset.left + (this.$input.outerWidth() / 2),
                top : offset.top + 30
            });
            this.shown = true;
        },
        hide : function() {
            this.$wrap.removeClass('active');
            this.$popup.hide();
            this.shown = false;
        },
        setDate : function(dateText, inst) {
            var self = this;
            this.$input.val(dateText);
            this.hide();
        }
    };

    function createPopup(name) {
        if (!$popups[name]) {
            var options = {
                onSelect : dateSelect
            };
            var $popup = $popups[name] = $(document.createElement('div'))
                .hide()
                .addClass('datepicker-pop')
                .mousedown(_stop)
                .html('<div class="inner"></div>')
                .appendTo(document.body);
            $datepickers[name] = $popup.find('.inner').datepicker(options);
        }
        return $popups[name];
    }
    function _prevent(e) {
        e.preventDefault(); e.stopPropagation();
    }
    function _stop(e) {
        e.stopPropagation();
    }

    function bodyClick(e) {
        if ((current) && (current.shown)) {
            current.hide();
        }
    }

    function dateSelect(dateText, inst) {
        current.setDate(dateText, inst);
    }

    $(function() {
        $(document.body).mousedown(bodyClick);
    });

    $.fn.datePicker = function(options) {
        this.each(function() {
            (new DatePicker(this, options));
        });
    };
})();



function checkorder() {
    var error = false;

    $(".orderForm input, .orderForm textarea").removeClass('error');


    if ($('#person').val() == '' || $('#person').val() == '- не заполнено') {
        $('.r-inp input[name="person"]').parent().find('.ph').show();
        $('#person').addClass('error');
        error = true;
    }
    if ($('#email').val() == '' || $('#email').val() == '- не заполнено' || $('#email').val().length < 6) {
        $('.r-inp input[name="email"]').parent().find('.ph').show();
        $('#email').addClass('error');
        error = true;
    }
    if ($('#phone').val() == '') {
        $('.r-inp input[name="phone"]').parent().find('.ph').show();
        $('#phone').addClass('error');
        error = true;
    }
    if ($('#address').val() == '') {
        $('.r-inp textarea[name="address"]').parent().find('.ph').show();
        $('#address').addClass('error');
        error = true;
    }


//    if (!error) this.submit();
    if (!error) ajax.order.send({
        'person': $('#person').val(),
        'email': $('#email').val(),
        'phone': $('#phone').val(),
        'address': $('#address').val(),
        'info': $('#info').val(),
        'date': $('#date').val(),
        'time_start': $('#time_start').val(),
        'time_end': $('#time_end').val()
    }, function(orderId){
        Popup.show('<h1>Заказ отправлен!</h1><p>Вашему заказу присвоен номер <b>' + orderId + '</b>. Уведомление о составе заказа отправлено Вам по почте. Наши менеджеры свяжутся с Вами для уточнения данных.</p>');

        window.setTimeout(function() {
            Popup.hide(function(){
                window.location.href = '/basket/';
            });
        }, 3000);
    });

    return false;
}


function chCaptcha(id, name) {
    var source = '/captcha/captcha.php?r='+Math.random();
    if (name) source += '&n=' + name;
    document.getElementById(id).setAttribute('src', source);
}
