$(document).ready(function() {

    $('.sel select').each(function() {
        var _this = $(this);
        _this.prev().find('span').html(_this.find('option:selected').html());
    })

    $('.sel select').unbind("change.ic").bind("change.ic", function() {
        var _this = $(this);
        _this.prev().find('span').html(_this.find('option:selected').html());
    })
    $('.sel select').unbind("keyup.ic").bind("keyup.ic", function () {
        var _this = $(this);
        _this.prev().find('span').html(_this.find('option:selected').html());
    })

    $('.sel select').unbind("focusin.ic").bind("focusin.ic", function () {
        var _this = $(this);
        _this.prev().addClass('focus');
    })

    $('.sel select').unbind("focusout.ic").bind("focusout.ic", function () {
        var _this = $(this);
        _this.prev().removeClass('focus');
    })

    $("#intro").jcarousel({
        scroll: 1,
        auto:10,
        animation: 1000,
        wrap: 'circular',
        initCallback: mycarousel_initCallback,
        itemVisibleInCallback:  highlight,
        itemVisibleOutCallback: removehighlight


    });

    $("#related").jcarousel({
        scroll: 6,
        animation: 1000


    });

    $('.l-header__i map area').mouseover(
            function (e) {
                var _this = $(this);
                var _el = $('.l-header__i').find('a.' + $(this).attr('class'));
                var _offset = _el.offset();
               $('.l-header__i map area').mouseout();
                if (!_el.hasClass('selected'))
                    _el.fadeIn(250, function() {
                        _el.addClass('selected');
                    });


            }
            );

    $('.l-header__i map area').mouseout(

            function (e) {
                var _this = $(this);
                var _el = $('.l-header__i').find('a.' + $(this).attr('class'));
                if (_el.hasClass('selected'))
                    _el.fadeOut(250, function() {
                        _el.removeClass('selected');
                    });


            }
            );

    $(".b-menu-item").click(
            function () {
                var _this = $(this);
                if (_this.hasClass('animate'))
                     return false;
                if (_this.next().length == 1){
                    if (!_this.hasClass('expand')  ) {
                       // $('.lst-category-tree .b-menu-item').next().slideUp();

                        _this.addClass('expand');
                        _this.addClass('animate').next().slideDown(function(){
                            _this.removeClass('animate');
                        });
                    }else{
                       // $('.lst-category-tree .b-menu-item').next().slideDown();

                        _this.removeClass('expand');
                        _this.addClass('animate').next().slideUp(function(){
                            _this.removeClass('animate');
                        });
                    }
                    return false;
                }
            }
            );

    autofill();

    $('.ui-stepper').stepper({step:1, min:1, max:999});


    $(".lnk-reserve").click(function () {
        var info = $(this).attr('rel').split('::');
        //<dt style="padding-top:0;"><img width="70" src="/published/SC/html/scripts/imgval.php" alt=""/></dt><dd>< class="int-txt" type="text" name="fConfirmationCode" value=""/></dd>
        if (!info[2])
            $(this).showPopup('html', '<div id="reserve-popup-block"><h2>Оставить заявку</h2><p>Вы можете оставить предварительную заявку на <span id="product-name"></span>, и когда товар появится в наличии, мы уведомим Вас по электронной почте.</p><div class="frm-standard frm-complaint"><dl><dt class="name">Ваше имя</dt><dd class="name"><input type="text"class="int-txt"size="17"value=""name="customer_name"></dd><dt>E-mail</dt><dd><input type="text"size="17"class="int-txt"value=""name="customer_email"></dd></dl><fieldset><input type="submit"value="Оставить заявку"name="request_information"class="int-btn"><a class="lnk-btn lnk-close cancel"href="#"></a></fieldset></div></div>');
        else
            $(this).showPopup('html', '<div id="reserve-popup-block"><h2>Оставить заявку</h2><p>Вы можете оставить предварительную заявку на <span id="product-name"></span>, и когда товар появится в наличии, мы уведомим Вас по электронной почте.</p><div class="frm-standard frm-complaint"><fieldset><input type="submit"value="Оставить заявку"name="request_information"class="int-btn"><a class="lnk-btn lnk-close cancel"href="#"></a></fieldset></div></div>');
        reservePopUp(info[0], info[1], info[2], info[3], info[4]);
        return false;
    });

    $(".lnk-complaint").click(function () {
//<dt style="padding-top:0;"><img width="70" src="/published/SC/html/scripts/imgval.php" alt=""/></dt><dd><input class="int-txt" type="text" name="fConfirmationCode" value=""/></dd>
        $(this).showPopup('html', '<div id="complaint-popup-block"><h2>Жалоба директору</h2><p>Вы можете отправить свою жалобу директору магазина.</p><div class="frm-standard frm-complaint"><dl><dt class="name">Ваше имя</dt><dd class="name"><input type="text"class="int-txt"size="17"value=""name="customer_name"></dd><dt>E-mail</dt><dd><input type="text"size="17"class="int-txt"value=""name="customer_email"></dd><dt>Сообщение</dt><dd><textarea name="message_text"></textarea></dd></dl><fieldset><button type="submit"name="request_information"class="int-btn">Пожаловаться!</button><a class="lnk-btn lnk-close cancel"href="#"></a></fieldset></div></div>');
        complaintPopUp();
        return false;
    });


    $(".lnk-callback").click(function () {
//<dt style="padding-top:0;"><img width="70" src="/published/SC/html/scripts/imgval.php" alt=""/></dt><dd><input class="int-txt" type="text" name="fConfirmationCode" value=""/></dd>
        $(this).showPopup('html', '<div id="callback-popup-block"><h2>Обратный звонок</h2><p>Вы можете заказать обратный звонок и наш специалист свяжется с вами в удобное для Вас время.</p><div class="frm-standard frm-complaint"><dl><dt class="name">Ваше имя</dt><dd class="name"><input type="text"class="int-txt"size="17"value=""name="customer_name"></dd><dt>Телефон</dt><dd><input type="text"size="17"class="int-txt"value=""name="customer_phone"></dd><dt>Время для звонка</dt><dd><textarea name="message_text"></textarea></dd></dl><fieldset><button type="submit"name="request_information"class="int-btn">Отправить</button><a class="lnk-btn lnk-close cancel"href="#"></a></fieldset></div></div>');
        callbackPopUp();
        return false;
    });


    $(".btn-ajax-cart").click(

            function () {

                var _this = $(this);
                var _id = _this.attr('id').split('-')[1];
                var _form = $('#form-' + _id);
                if (!checkOption(_form)) {
                    return false;
                }
                //alert(_form.serialize());
                //return false;
                $.get('/?' + _form.serialize(), { ukey:'cart', action:'add_product', ajax:true,  view:'noframe'  }, function(data) {
                    _this.attr('disabled', '');
                    if (data.status == true) {
                        $(this).showPopup('html', '<div id="ajax-cart-popup-block"><h2>Товар в количестве ' + _form.find('input[name=product_qty]').val() + ' шт. добавлен в корзину</h2><a href="/cart/" class="lnk-btn">Перейти в корзину</a><a href="#" class="lnk-btn cancel">Продолжить покупки</a></div>');
                         if ($('#shpcrtgc span').text() == '' ){
                             $('#shpcrtgc span').html('Вещей:<span></span>');
                             $('#shpcrtca span').html('На сумму:<span></span>');
                         }
                        $('#shpcrtgc span').text(data.qty+' шт.');
                        $('#shpcrtca span').text(data.total);
                    }
                    if (data.msg)
                        if (data.msg.length > 0) {
                            showErrAlert(data.msg);
                        }

                }
                        , 'json');

                return false;
            }
            );

    $(".frm-product").submit(
            function () {
                return checkOption($(this));
            }
            );


    $(".lst-gallery li").hover(function() {
        $(this).addClass('hover');
        var _id = $(this).attr('id').split('-')[1];
        if ($('.lst-gallery .selected').length == 0)
            showImage(_id, false);
        else {
            if ($('.lst-gallery .selected').attr('id').split('-')[1] != _id)
                showImage(_id, false);
        }
    }, function() {
        $(this).removeClass('hover');
        var _id = $(this).attr('id').split('-')[1];
        if ($('.lst-gallery .selected').length == 0)
            $(this).find('.pic__i').fadeOut();
        else {
            if ($('.lst-gallery .selected').attr('id').split('-')[1] != _id)
                $(this).find('.pic__i').fadeOut();
        }
    });


    $(".lst-gallery li ").click(
            function () {

                var _id = $(this).attr('id').split('-')[1];
                clickImage(_id);
                return false;
            }
            );

    $(".l-gallery .lnk-left ").click(
            function () {
                if ($(".lst-gallery .selected").length != 0)
                    var _id = $(".lst-gallery .selected").attr('id').split('-')[1];
                else
                    var _id = 0;
                var _max = $(".lst-gallery li").last().attr('id').split('-')[1];



                if (_id < 0)
                    _id = 1;


                clickImage(Number(_id) - 1);
                return false;
            });

    $(".l-gallery .lnk-right ").click(
            function () {
                if ($(".lst-gallery .selected").length != 0)
                    var _id = $(".lst-gallery .selected").attr('id').split('-')[1];
                else
                    var _id = 0;
                var _max = $(".lst-gallery li").last().attr('id').split('-')[1];

                if (_id > _max)
                    _id = _max - 1;

                clickImage(Number(_id) + 1);
                return false;
            });

});


function clickImage(_id) {

    var $paneOptions = $('.l-gallery__i');
    var p = $('#pic-' + _id);
    var position = p.position();
    $(".lst-gallery li").removeClass('selected');
    $(".lst-gallery li#pic-" + _id).addClass('selected');
    $paneOptions.scrollTo({top:'0px', left: ($('.l-gallery__i').scrollLeft() + position.left - ($(document).width() - p.width()) / 2) + 'px'}, 800);

    showImage(_id, true);
}

function showImage(_id, sb) {

    var _url = $('#pic-' + _id).attr('imgc');

    var $link = [_url];
    if (sb)
        $('#pic-' + _id).siblings().find('.pic__i').fadeOut();
    $.preload($link, {onComplete:complete});

    function complete(data) {
        //$("#planegal-wait").hide();
        if ($(".lst-gallery li#pic-" + _id).hasClass('hover') || $(".lst-gallery li#pic-" + _id).hasClass('selected')) {

            $('#pic-' + _id).find('.pic__i').css({'background-image' : 'url(' + _url + ')'});
            $('#pic-' + _id).find('.pic__i').fadeIn("normal");
        }
    }

    ;
}


function autofill() {
    $(".autofill").focus(
            function () {
                $(this).addClass("active");
                if ($(this).val() == $(this).attr('title')) $(this).val('');
            }
            );

    $(".autofill").blur(
            function () {
                if ($(this).val() == '') {
                    $(this).val($(this).attr('title'));
                    $(this).removeClass("active");
                }
            }
            );
}

function reservePopUp(pid, pname, cemail, cname) {
    $("#product-name").html(pname);

    $("#reserve-popup-block input[type=submit]").click(function () {
        var _this = $(this);
        var _form = _this.parent().parent();
        if (!cname)
            var _customer_name = _form.find("input[name=customer_name]").val();
        else
            var _customer_name = cname;
        if (!cemail)
            var _customer_email = _form.find("input[name=customer_email]").val();
        else
            var _customer_email = cemail;
        //var _captcha = _form.find("input[name=fConfirmationCode]");
        //if (_captcha.val().length > 0 ) {
        if (_customer_name.length > 0 && _customer_email.length > 0) {
            _this.attr('disabled', 'disabled');

            //, fConfirmationCode:_captcha.val()
            $.post('/reserve/', { send:'send', reserve:'reserve', ajax: 'ajax', product_id:pid, customer_name: _customer_name, customer_email:_customer_email}, function(data) {
                _this.attr('disabled', '');
                if (data.status == true) {
                    $('#reserve-popup-block').hidePopup();
                    //_msg = $('#msg-place');
                    //_msg.append('<h1 class="h-block">Ваша заявка отправлена</h1>');
                    //_msg.show();
                    //setInterval('_msg.hide("400")', 5000);
                    _form.find("input[name=customer_name]").val('');
                    _form.find("input[name=customer_email]").val('');
                    //_captcha.val('');
                    showErrAlert('Ваша заявка отправлена');
                }
                if (data.msg)
                    if (data.msg.length > 0) {
                        showErrAlert(data.msg);
                    }
            }
                    , 'json');
        }
        else {
            showErrAlert('err_input_all_required_fields');
        }
        return false;
    });
}

function complaintPopUp() {
    $("#complaint-popup-block [type=submit]").click(function () {
        var _this = $(this);
        var _form = _this.parent().parent();
        var _name = _form.find("input[name=customer_name]");
        var _email = _form.find("input[name=customer_email]");
        //var _subject = _form.find("select[name=message_subject]");
        var _text = _form.find("textarea");
        //var _captcha = _form.find("input[name=fConfirmationCode]");

        if (_name.val().length > 0 && _text.val().length > 0 && _email.val().length > 0) {
            _this.attr('disabled', 'disabled');
            //, fConfirmationCode:_captcha.val()
            $.post('/feedback/', { feedback:'feedback', send:'send', ajax: 'ajax', customer_name: _name.val(), customer_email:_email.val(), message_subject:'Письмо с сайта', message_text:_text.val() }, function(data) {
                _this.attr('disabled', '');
                if (data.status == true) {
                    $('#complaint-popup-block').hidePopup();
                    _name.val('');
                    _email.val('');
                    _text.val('');
                    //_captcha.val('');
                    showErrAlert('Сообщение успешно отправлено');
                }
                if (data.msg && data.msg.length > 0) {
                    showErrAlert(data.msg);
                }
            }
                    , 'json');
        }
        else {
            showErrAlert('err_input_all_required_fields');
        }
        return false;
    });
}

function callbackPopUp() {
    $("#callback-popup-block [type=submit]").click(function () {
        var _this = $(this);
        var _form = _this.parent().parent();
        var _name = _form.find("input[name=customer_name]");
        var _phone = _form.find("input[name=customer_phone]");
        //var _subject = _form.find("select[name=message_subject]");
        var _text = _form.find("textarea");
        //var _captcha = _form.find("input[name=fConfirmationCode]");
         //alert('1');
        if (_name.val().length > 0  && _phone.val().length > 0) {
            _this.attr('disabled', 'disabled');
            //, fConfirmationCode:_captcha.val()
            $.post('/feedback/', { feedback:'feedback', send:'send', ajax: 'ajax', customer_name: _name.val(), customer_phone:_phone.val(), message_subject:'Заказ обратного звонка', message_text:_text.val() }, function(data) {
                _this.attr('disabled', '');
                if (data.status == true) {
                    $('#callback-popup-block').hidePopup();
                    _name.val('');
                    _phone.val('');
                    _text.val('');
                    //_captcha.val('');
                    showErrAlert('Сообщение успешно отправлено');
                }
                if (data.msg && data.msg.length > 0) {
                    showErrAlert(data.msg);
                }
            }
                    , 'json');
        }
        else {
            showErrAlert('err_input_all_required_fields');
        }
        return false;
    });
}

function checkOption(_form) {
    var noerr = true;
    _form.find('.product_option').each(

            function() {

                var _this = $(this);
                if (_this.val() == 0) {
                    _this.parent().parent().addClass('error');
                    noerr = false;
                } else {
                    _this.parent().parent().removeClass('error');

                }
            }
            );

    return noerr;
}


function open_window(link, w, h, returnFocus) {
    if (returnFocus == undefined)
        var returnFocus = false;
    var win = "width=" + w + ",height=" + h
            + ",menubar=no,location=no,resizable=yes,scrollbars=yes";
    var newWin = window.open(link, 'newWin', win);
    if (newWin) {
        if (returnFocus)
            newWin.blur();
        else
            newWin.focus();
    }
    return newWin;
}

function showErrAlert(code) {
    switch (code) {
        case 'product_not_found':
            alert('Продукт не найден.');
            break;
        case 'product_out_of_stock':
            alert('Продукт не продается.');
            break;
        case'err_wrong_ccode':
            alert('Вы ввели неверный код подтверждения');
            break;
        case'msg_error_wrong_email':
            alert('Вы ввели некорректный email');
            break;
        case'err_input_all_required_fields':
            alert('Пожалуйста заполните форму');
            break;
        case'err_email_or_phone':
            alert('Пожалуйста укажите предпочтительный способ связи');
            break;
        case'err_already_exist':
            alert('Вы уже зарезервировали этот товар.');
            break;
        case'err_wrong_product_id':
            alert('Внутренняя ошибка, обновите страницу и попробуйте снова.');
            break;
        default:
            alert(code);
            break;
    }

}


$.fn.alignCenter = function() {
    //get margin left

    var marginLeft = - $(this).width() / 2 + 'px';
    //get margin top
    var marginTop = - $(this).height() / 2 + 'px';

    //return updated element
    return $(this).animate({marginLeft: marginLeft, marginTop: marginTop}, 500);
};

$.fn.showPopup = function(type, iframe) {
    //detect whether popup is visible or not
    $("body").prepend("<div id='popup-overlay' style=' background-color:#000000; cursor:pointer; display:none; left:0; position:absolute; top:0;  width:100%; z-index:999;'></div>");
    $("body").prepend("<div id='popup-content' style='display:none; left:50%; top:50%; position:fixed; z-index:1000;'></div>");
    if ($.browser.msie && $.browser.version == 6) {


        $("#popup-content").css('top', $(window).scrollTop() + $(window).height() / 2);
    }
    if (type == "div") {
        var popupContent = $(this);
        popupContent.wrap("<div id='popup-wrap' style='display:none;'></div>");

        $("#popup-content").append(popupContent.clone().show());

        popupContent.remove();
    } else if (type == "html") {
        $("#popup-content").append("<div class='b-popup-html'>" + iframe + "</div>");
    }
    else if (type == "iframe") {
        $("#popup-content").append("<iframe id='iframe-cart' style='overflow:hidden' width='320px' height='160px' scrolling='no' src='" + iframe + "' />");
    }
    $("#popup-content .cancel").click(function() {

        $("#popup-content").hidePopup(type);
        return false;
    });
    $('#popup-overlay').height($(document).height()).fadeTo(500, 0.7).click(function() {
        $("#popup-content").hidePopup(type);
        return false;
    });
    $("#popup-content").alignCenter().fadeIn();
};

$.fn.hidePopup = function(type) {
    $('#popup-overlay').fadeTo(500, 0, function() {
        $('#popup-overlay').remove();
    });
    $("#popup-content").fadeTo(500, 0, function() {
        if (type == "div") {
            $("#popup-wrap").append($("#popup-content").html());
            $("#popup-wrap").children().hide().unwrap();
        }
        $("#popup-content").remove();


    });

};


function mycarousel_initCallback(carousel) {

    carousel.clip.prepend('<div class="jcarousel-control"></div>');
    carousel.clip.find('.jcarousel-list li').each(function() {

        carousel.clip.find('.jcarousel-control').append('<a href="#" rel="' + $(this).attr('jcarouselindex') + '">' + $(this).attr('jcarouselindex') + '</a>');
    });

    jQuery('.jcarousel-control a').bind('click', function() {

        carousel.scroll($.jcarousel.intval($(this).attr('rel')));
        //carousel.stopAuto();
        return false;
    });
    carousel.clip.bind('mouseleave', function() {

        carousel.next();
        carousel.startAuto();
        return false;
    });
    carousel.clip.bind('mouseenter', function() {

        carousel.stopAuto();
        return false;
    });
    // Pause autoscrolling if the user moves with the cursor over the clip.
    /*
     carousel.clip.hover(function() {

     //carousel.stopAuto();
     }, function() {
     //carousel.startAuto();
     carousel.next();

     });

     jQuery('.jcarousel-control').hover(function() {
     //carousel.stopAuto();
     }, function() {
     //carousel.startAuto();

     });  */


}
;

function highlight(carousel, obejctli, liindex, listate) {
    var len = $('.jcarousel-control a').length;
    //alert('0:'+ idx%len + ' 1:' + idx/len + ' 2:' + Math.floor(idx/len)+ ' 3:' + (Math.floor(idx/len) * len));
    var tmp = liindex % len;
    if (tmp == 0)
        tmp = len;
    //  alert(' highlight '+liindex);
    //$('.b-i1').text('highlight '+liindex + ' tmp' + tmp);
    jQuery('.jcarousel-control a:nth-child(' + tmp + ')').attr("class", "active");
}
;
// it will remove last selected slide from <a>
// <a href="#" class="selected">1</a> to <a href="#">1</a>
function removehighlight(carousel, obejctli, liindex, listate) {
    var len = $('.jcarousel-control a').length;
    //alert('0:'+ idx%len + ' 1:' + idx/len + ' 2:' + Math.floor(idx/len)+ ' 3:' + (Math.floor(idx/len) * len));
    var tmp = liindex % len;
    if (tmp == 0)
        tmp = len;
    // alert(' removehighlight '+liindex);
    // $('.b-i2').text('removehighlight '+liindex + ' tmp' + tmp);
    jQuery('.jcarousel-control a:nth-child(' + tmp + ')').removeAttr("class", "active");
}
;
