/**
 * Основной скрипт
 */

function init() {

    // Preload icons for Context Popup Menu
    $.preloadImages = function() {
        for(var i = 0; i<arguments.length; i++){
        $('<img>').attr("src", arguments[i]);
        }
    };
    $.preloadImages(
        '/media/images/icons/enlarge-photo.gif',
        '/media/images/icons/enlarge-photo-disabled.gif',
        '/media/images/icons/add-to-cart.gif',
        '/media/images/icons/add-to-compare.gif',
        '/media/images/icons/availability.gif',
        '/media/images/icons/subscibe-price.gif',
        '/media/images/bgs/ajax.gif'
    );

    /*  Event Handlers  */
    $(window).resize(resizeWindowHandler);
    // Вызываем явно, чтобы после загрузки пересчитать ширину
    resizeWindowHandler(true);
    
    // Отображение баннеров на главной странице
    if ( $('#banner-carousel').size() ) {
        
        $('#banner-carousel-action .action a.play').click(playBannerCarouselClick);
        $('#banner-carousel-action .action a.pause').click(pauseBannerCarouselClick);
    
        $('#banner-carousel').cycle({
            fx: 'fade',
            timeout: 3000,
            speed: 1000,
            activePagerClass: 'active',
            pager: '#banner-carousel-action .pages ul',
            pagerAnchorBuilder: function(idx, slide) {
                var title = $('img', slide).size() ? $('img', slide).attr('alt') : ( $('object', slide).size() ? $('object', slide).attr('title') : '' );
                return '<li><a href="javascript:void(0)" title="' + title + '">&nbsp;</a></li>'; 
            },
            pagerClick: pauseBannerCarouselClick
        });
        
    }
    
    // Опросы на главной странице
    $('#polls form').submit(function() {
        if ( $('input[type=checkbox]:checked', this).size() ) {
            $frm = $(this);
            
            $('input[type=button]', $frm).attr('disabled', 'disabled');
            
            $.ajaxSetup({
                dataType: 'json'
            });
            $.post(
                '/ajax/poll-vote.json',
                $frm.serialize(),
                function (json) {
                    if ( '' != json.error ) {
                        // Была ошибка
                        alert(json.error);
                        return false;
                    }
                    if ( error = showPollResults(json) ) {
                        alert(error);
                        return false;
                    }
                }
            );
        } else {
            alert("Выберите хотя бы один из вариантов ответа");
        }
        return false;
    });
    

    // Top Sales navigation
    updateSaleNav();
    $('#sale-back').click(function(){
        if (!$(this).hasClass('disabled')) {
            changeSale(active_sale-1);
        }
    })
    $('#sale-forward').click(function(){
        if (!$(this).hasClass('disabled')) {
            changeSale(active_sale+1);
        }
    });

    //Main Catalog Navigation
    $('#main-catalog > ul > li > a:first-child').click(function(){
        return navigateCatalog($(this).parent());
    });
    $('#main-catalog ul ul ul li a').click(function(){
        location.href = $(this).attr('href');
        return false;
    });
    $('#main-catalog ul ul li div').click(function(){
        return false;
    });
    $('#main-catalog ul.toggled > li').click(function(){
        if ( !$(this).hasClass('simple') ) {
            return navigateSubcateg($(this));
        }
        return true;
    });
    $('#main-catalog > ul > li > ul > li > a:first-child').click(function(){
        return navigateSubcateg($(this).parent());
    });

    // Subscribe on Change Price
    $('a.price-subscribe').click(function(e){
        overlayShow();
        popupPriceSubscribeDialog(this);
        $(document).bind('keyup', function(e){
            if (e.keyCode == 27) {
                popupClose();
            }
        });
        return false;
    });

    $('#enter-with-pasword a[href="/login/"]').click(function(){
        overlayShow();
        popupAuth();
        $(document).bind('keyup', function(e){
            if (e.keyCode == 27) {
                popupClose();
            }
        });
        return false;
    });

    $('a.close-popup').click(popupClose);

    // Работаем с фокусом на поле телефона
    $('#price-subscribe-email').focus(
        function () {
            var $this = $(this);
            if ( $this.val() == 'ваш e-mail' ) {
                $this.removeClass('empty').val('');
            }
        }
    ).blur(
        function () {
            var $this = $(this);
            if ( $this.val() == '' ) {
                $this.addClass('empty').val('ваш e-mail');
            }
        }
    );

    // Context Menu
    var $divPhoto = $('#main-content ul.small-goods-list li.small-goods-item div.photo');
    var $divContextMenu = $('#context-menu');
    if ( $divPhoto.size() ) {
        // Каждые 100 миллисекунд проверяем, не ушли ли мы с товаров и не нужно ли закрыть контекстное меню
        setInterval(hideContextMenu, 100);
    }
    $divPhoto.hover(
        function(e){
            $this = $(this);
            // Делаем товар активным
            $this.addClass('hovered');
            if ( $divContextMenu.is(':visible') ) {
                // Если после другого товара осталось открытое контекстное меню, прячем его
                $divContextMenu.removeClass('hovered').hide();
            }
            // Запоминаем идентификатор временной задержки
            $this.data('timeoutId', setTimeout(function() {
                // Через 1 секунду пытаемся показать контекстное меню
                waitForContextMenu($this);
            }, 1000));
        },
        function(){
            $this = $(this);
            // Делаем товар неактивным (уходим с товара)
            $this.removeClass('hovered');
            setTimeout(function() {
                if ( !$divContextMenu.hasClass('hovered') ) {
                    $divContextMenu.hide();
                }
            }, 1000);
            // Получаем идентификатор временной задержки, соответствующей текущему элементу
            var timeoutId = $this.data('timeoutId');
            if ( timeoutId ) {
                // Задержка определена, значит, нужно очистить setTimeout
                clearTimeout(timeoutId);
                $this.data('timeoutId', 0)
            }
        }
    );

    // Играемся с наведением курсора на контекстное меню
    $divContextMenu.hover(
        function () {
            $(this).addClass('hovered');
        },
        function () {
            $(this).removeClass('hovered');
        }
    );

    // Корзина
    $('#shopping-cart-content input').keyup(function() {
        cart.changeQuantity(this, this.value);
    });
    $('#shopping-cart-content a.delete').click(function() {
        cart.deleteGood(this);
        return false;
    });

    // Обновляем состояние корзины
    cart.recalcGoodsCnt();

    // Сравнение
    $('#add-compare-list').change(function() {
        if ( this.value == '' ) {
            $('#add-compare-frm input[type=button]').attr('disabled', 'disabled');
            return;
        }
        else {
            $('#add-compare-frm input[type=button]').attr('disabled', '');
        }
    });

    $('#add-compare-frm input[type=button]').click(function() {
        document.location.href = $('#add-compare-list').val();
    });

    // Форма быстрого поиска
    $('#suggest').autocomplete('/ajax/suggest.json');

    // Фотогалерея
    $('#photo > a, #photos a').lightBox({
        imageLoading:    '/media/images/lightbox/ico-loading.gif',
        imageBtnPrev:    '/media/images/lightbox/btn-prev.gif',
        imageBtnNext:    '/media/images/lightbox/btn-next.gif',
        imageBtnClose:   '/media/images/lightbox/btn-close.png',
        imageBlank:      '/media/images/lightbox/blank.gif',
        overlayOpacity:  0.4
    });

    // Формы регистрации и редактирования персональных данных
    $('#registration-frm').submit(Validator.signup);
    $('#personal-frm').submit(Validator.personal);

    // Диалог подписки на цену
    $('#price-subscribe-dialog-frm').submit(priceSubscribe);

    // Форма отправки сообщения
    $('#contacts-frm').submit(Validator.contacts);

    // Форма быстрой регистрации
    $('#signup-light-frm').submit(Validator.signupLight);

    // Форма отправки заказа
    $('#make-order-frm').submit(Validator.makeOrder);
    
    // Отслеживаем клик по ссылке скачивания прайса
    $('#pricelist-link a').click(function() {
        var label = removeDomain(location.href);
        _gaq.push(['_trackEvent', 'Прайс', 'Скачка', label]);
    });
}

function removeDomain(url) {
    var reg = /^(http:\/\/)?[^\/]+/;
    url = url.replace(reg, '');
    
    return url;
} // end of function removeDomain

function quoteHtml(str) {
    str = str.replace(/&/g, '&amp;');
    str = str.replace(/</g, '&lt;');
    str = str.replace(/>/g, '&gt;');
    str = str.replace(/"/g, '&quot;');
    return str;
} // end of function quoteHtml

///
/// Polls
///
function showPollResults(data) {
    if ( 'open' == data.mode ) {
        // Открытый опрос, показываем развернутые результаты
        var html = '<div class="results">';
        html    += '    <div class="question">' + quoteHtml(data.poll.title) + '</div>';
        html    += '    <div class="total_voters">' + data.poll.voters_total_str + '</div>';
        html    += '    <ul class="answers">';
        for ( i in data.poll.answers ) {
            html += '       <li>';
            html += '           <div class="total"><div class="vote" style="width: ' + parseInt(data.poll.answers[i].voters * 100/data.poll.answers_total) + '%">&nbsp;</div></div>';
            html += '           <div class="voters">' + parseInt(data.poll.answers[i].voters) + '</div>';
            html += '           <div class="answer">' + quoteHtml(data.poll.answers[i].answer) + '</div>';
            html += '       </li>';
        }
        html    += '    </ul>';
        
    } else if ( 'close' == data.mode ) {
        // Закрытый опрос
        var html = '<div class="thanks">';
        html    += '    <div class="question">' + quoteHtml(data.poll.title) + '</div>';
        html    += '    <div class="message">Ваш выбор учтен, спасибо за участие в опросе.</div>';
        html    += '</div>';
    } else {
        return "Ошибка получения результатов опроса (Код 701)";
    }
    
    // Выводим результаты голосования
    $(html).insertAfter('#polls .poll');
    
    // Прячем форму голосования
    $('#polls .poll').hide();
    
    return "";
} // end of function showPollResults


///
/// Form validators
///
var Validator = {};
Validator.clearErrors = function(frm) {
    $('label.error, input.error', frm).removeClass('error');
}

Validator.addError = function(frm, el) {
    $(el).addClass('error').parent().children('label.field').addClass('error');
}

Validator.signup = function() {
    var frm = this;
    var has_errors = false;
    Validator.clearErrors();
    if ( !frm['email'].value.match(/^[a-z0-9_\-\.]+@([a-z0-9_\-]+\.)+[a-z]{2,5}$/i) ) {
        Validator.addError(frm, frm['email']);
        has_errors = true;
    }

    if ( frm['passw'].value.match(/^\s*$/) ) {
        Validator.addError(frm, frm['passw']);
        has_errors = true;
    }

    if ( frm['passw_conf'].value.match(/^\s*$/) ) {
        Validator.addError(frm, frm['passw_conf']);
        has_errors = true;
    }

    if ( frm['passw'].value != frm['passw_conf'].value ) {
        Validator.addError(frm, frm['passw']);
        Validator.addError(frm, frm['passw_conf']);
        has_errors = true;
    }

    return !has_errors;
}

Validator.makeOrder = function() {
    var frm = this;
    var has_errors = false;
    Validator.clearErrors();
    if ( frm['fio'].value.match(/^\s*$/) ) {
        Validator.addError(frm, frm['fio']);
        has_errors = true;
    }
    if ( frm['phone'].value.match(/^\s*$/) ) {
        Validator.addError(frm, frm['phone']);
        has_errors = true;
    }
    if ( frm['email'].value.match(/[^\s]/) && !frm['email'].value.match(/^[a-z0-9_\-\.]+@([a-z0-9_\-]+\.)+[a-z]{2,5}$/i) ) {
        Validator.addError(frm, frm['email']);
        has_errors = true;
    }

    return !has_errors;
}

Validator.signupLight = function() {
    var frm = this;
    var has_errors = false;
    Validator.clearErrors();
    if ( !frm['email'].value.match(/^[a-z0-9_\-\.]+@([a-z0-9_\-]+\.)+[a-z]{2,5}$/i) ) {
        Validator.addError(frm, frm['email']);
        has_errors = true;
    }
    return !has_errors;
}

Validator.personal = function() {
    var frm = this;
    var has_errors = false;
    Validator.clearErrors();
    if ( !frm['email'].value.match(/^[a-z0-9_\-\.]+@([a-z0-9_\-]+\.)+[a-z]{2,5}$/i) ) {
        Validator.addError(frm, frm['email']);
        has_errors = true;
    }

    if ( !frm['passw'].value.match(/^\s*$/) ) {
        if ( frm['passw_old'].value.match(/^\s*$/) ) {
            Validator.addError(frm, frm['passw_old']);
            has_errors = true;
        }

        if ( frm['passw_conf'].value.match(/^\s*$/) ) {
            Validator.addError(frm, frm['passw_conf']);
            has_errors = true;
        }

        if ( frm['passw'].value != frm['passw_conf'].value ) {
            Validator.addError(frm, frm['passw']);
            Validator.addError(frm, frm['passw_conf']);
            has_errors = true;
        }
    }

    return !has_errors;
}

Validator.priceSubscribe = function(frm) {
    var has_errors = false;
    Validator.clearErrors();
    if ( !frm['email'].value.match(/^[a-z0-9_\-\.]+@([a-z0-9_\-]+\.)+[a-z]{2,5}$/i) ) {
        Validator.addError(frm, frm['email']);
        has_errors = true;
    }
    return !has_errors;
}

Validator.contacts = function() {
    var frm = this;
    var has_errors = false;
    Validator.clearErrors();

    if ( frm['fio'].value.match(/^\s*$/) ) {
        Validator.addError(frm, frm['fio']);
        has_errors = true;
    }

    if ( frm['contacts'].value.match(/^\s*$/) ) {
        Validator.addError(frm, frm['contacts']);
        has_errors = true;
    }

    if ( frm['message'].value.match(/^\s*$/) ) {
        Validator.addError(frm, frm['message']);
        has_errors = true;
    }

    return !has_errors;
}


///
/// Price subscribe
///
function priceSubscribe() {
    var frm = this;
    var $frm = $(frm);
    if ( !Validator.priceSubscribe(frm) ) {
        return false;
    }

    $.ajaxSetup({
        dataType: 'json'
    });
    $.post(
        '/ajax/price-subscribe.json',
        $frm.serialize(),
        function (json) {
            if ( '' != json.error ) {
                // Была ошибка
                alert(json.error);
                return;
            }

            $('#price-subscribe-dialog div.popup-content').toggleClass('invisible');
            $('input[name=email]', $frm).val('ваш e-mail');
        }
    );

    return false;
}

///
/// Window Handlers
///
// Выполняем перетрубации при изменении размеров окна
function resizeWindowHandler() {
    // Если показан popup с подпиской на цену, перемещаем его
    var $popup = $('#price-subscribe-dialog');
    if ($popup.is(':visible')) {
        var popupXY = calcCenterPopupPosition($popup);
        $popup.animate({'left':popupXY[0], 'top':popupXY[1]}, 500);

        var windowXY = calcWindowSize();
        $('#div-overlay').css({'width' : windowXY[0], 'height' : windowXY[1]});
    }

    // Центрируем элемент относительно его родителя
    var $ulCenter = $('#main-content > div.content-container > ul.large-goods-list, #main-content > div.content-container > ul.small-goods-list');
    if ($ulCenter.size()) {
        centerElements($ulCenter);
    }
}


function checkCookie( msg ) {
    if ( msg == undefined ) {
        msg = 'Необходимо включить cookie';
    }
    $.cookie('cookie_test', '1', {expires: 10});
    if ( $.cookie('cookie_test') != '1' ) {
        alert(msg);
        return false;
    }

    $.cookie('cookie_test', null);
    return true;
}

///
/// Helpers
///
var Helpers = {};
Helpers.html = function (str) {
    str = str.replace(/&/g, '&amp;');
    str = str.replace(/</g, '&lt;');
    str = str.replace(/>/g, '&gt;');
    str = str.replace(/"/g, '&quot;');
    return str;
} // end of method html()

Helpers.number = function (number, decimals, point, separator) {
    if(!isNaN(number)) {
        point = point ? point : '.';

        number   = number + '';
        number   = number.split('.');

        if(separator) {
            var tmp_number = new Array();
            for(var i = number[0].length, j = 0; i > 0; i -= 3) {
                var pos = i > 0 ? i - 3 : i;
                tmp_number[j++] = number[0].substring(i, pos);
            }
            number[0] = tmp_number.reverse().join(separator);
        }
        if ( decimals ) {
            if ( number[1] == undefined ) {
                number[1] = '';
            }
            for ( i=number[1].length; i<decimals; i++) {
                number[1] += '0';
            }

            number[1] = '' + Math.round(parseFloat(number[1].substr(0, decimals) + '.' + number[1].substr(decimals, number[1].length), 10));

            while ( number[1].length < decimals ) {
                number[1] = '0' + number[1];
            }
        }
        else {
            number.length = 1;
        }
        return(number.join(point));
    }
    else return(null);
} // end of method number()

///
/// Возвращает отформатированную сумму.
///
/// Копейки выводяться только если они есть
///
Helpers.sum = function (num) {
    var decimal = (num == Math.floor(num)) ? 0 : 2
    return Helpers.number(num, decimal, ',', '&nbsp;');
} // end of function sum()


// Вычисляем координаты popup слоя для позиционирования его по центру окна
function calcCenterPopupPosition($popup) {
    var wWidth, wHeight;
    var windowSize = calcWindowSize();

    wWidth = parseInt(windowSize[0]);
    wHeight = parseInt(windowSize[1]);

    var left = wWidth/2 - ($popup.width() + parseInt($popup.css('padding-left')) + parseInt($popup.css('padding-right')))/2;
    var top  = wHeight/2 - ($popup.height() + parseInt($popup.css('padding-bottom')) + parseInt($popup.css('padding-top')))/2;

    left += 'px';
    top += 'px';
    return [left, top];
}
// Вычисляем размеры окна
function calcWindowSize() {
    var width = $('html')[0].clientWidth + 'px';
    var height = $('html')[0].clientHeight + 'px';

    return [width, height];
}
// Распределяем товары по всей ширине экрана
function centerElements($thisUl) {
    var containerWidth = $thisUl.parent().width();
    var child = $thisUl.find('li:first');

    var baseMinWidth = parseInt(child.css('min-width'));
    var baseWidth = baseMinWidth ? baseMinWidth : 180;
    var margin = Math.max(parseInt(child.css('margin-left')), parseInt(child.css('margin-right'))) +5; // 5 подобрано экспериментально

    containerWidth += parseInt(child.css('margin-left')) + parseInt(child.css('margin-right')); // Чтобы компенсировать margin'ы у крайних элементов

    var liPerString = parseInt(containerWidth / (baseWidth + margin));  // Количество элементов в строке родителя
    var excess  = (containerWidth % (baseWidth + margin));              // Остаток, который нужно распределить между элементами
    var newWidth = (parseInt(excess/liPerString) + baseWidth);   // Распределяем остаток - получаем новую ширину
    //alert(newWidth);
    $('>li', $thisUl).animate({width: newWidth}, 300);
}

///
/// Popups
///
function popupPriceSubscribeDialog(elem) {
    // Если нужно будет передавать id товара
    $('#good-id').val($(elem).attr('rel'));
    var $popup = $('#price-subscribe-dialog');

    // Информация о продукте
    var goods_name= $('#good-name').text();
    var old_price=$('#buy-info div.old-price span.uah').text();
    var price_uah=$('#buy-info div.price span.uah').text();
    var price_usd=$('#buy-info div.price span.usd').text();



    // Получаем название товара
    if (goods_name == '') {
        $popup.find('div.name').removeClass('invisible').addClass('invisible');
    }
    else {
        $popup.find('div.name').removeClass('invisible').text(goods_name);
    }
    // Получаем старую цену
    if (old_price == '') {
        $popup.find('div.old-price').removeClass('invisible').addClass('invisible');
    }
    else {
        $popup.find('div.old-price').removeClass('invisible').find('span.uah').text(old_price);
    }
    // Получаем цену в uah и usd, проверяем, является ли она новой
    if (price_uah == '') {
        $popup.find('div.price span.uah').removeClass('invisible').addClass('invisible');
    }
    else {
        $popup.find('div.price span.uah').removeClass('invisible').text(price_uah);
    }
    if (price_usd == '') {
        $popup.find('div.price span.usd').removeClass('invisible').addClass('invisible');
    }
    else {
        $popup.find('div.price span.usd').removeClass('invisible').text(price_usd);
    }
    $popup.find('div.price').removeClass('new');
    if ($('#buy-info div.price').hasClass('new')) {
        $popup.find('div.price').addClass('new');
    }

    // Вычисляем координаты окна: располагаем по центру экрана
    var popupXY = calcCenterPopupPosition($popup);
    $popup.css({'left':popupXY[0], 'top':popupXY[1]}).show();
}

function popupAuth() {
    var $popup = $('#auth-dialog');
    // Вычисляем координаты окна: располагаем по центру экрана
    var popupXY = calcCenterPopupPosition($popup);
    $popup.css({'left':popupXY[0], 'top':popupXY[1]}).show();
}

function popupClose() {
    $(document).unbind('keyup');

    overlayClose();
    $('div.popup:visible').hide();
    return false;
}

function overlayShow() {
    var windowXY = calcWindowSize();

    $('#div-overlay').css({'width' : windowXY[0], 'height' : windowXY[1]}).show();
    $('#div-overlay').bind('click', popupClose);
}
function overlayClose() {
    $('#div-overlay').unbind('click', popupClose);
    $('#div-overlay').hide();
}


///
/// Catalogue Navigation
///
function collapseItem($liItem) {
    $span = $('span:first', $liItem);
    if ( !$span.size() ) {
        // First opening
        return true;
    }
    $('>ul', $liItem).animate({'height': 'hide', 'paddingBottom': '0'}, 'fast');

    $span.replaceWith('<a href="javascript:void();">'+$span.text()+'</a>');
    $liItem.children('a:first-child').bind('click', function(){
        navigateCatalog($liItem) ;
        return false;
    });
}

function expandItem($liItem) {
    var $a = $('>a:first-child', $liItem);
    $a.replaceWith('<span class="selected">'+$a.text()+'</span>');
    $('>ul', $liItem).animate({'height': 'show', 'paddingBottom': '20px'}, 'fast');
}

function navigateCatalog($liItemActive) {
    var $cur_lielem = $liItemActive.parent().find('> li > span.selected').parent();
    if ( $cur_lielem.size() ) {
        collapseItem($cur_lielem);
    }
    expandItem($liItemActive);
    return false;
}

function navigateSubcateg($liItemActive) {
    var $ul = $liItemActive.find('> div > ul');
    if ( !$ul.size() ) {
        // No subitems so let browser follow the link
        return true;
    }
    $ul.animate({'height': 'toggle'}, 'fast');
    $liItemActive.toggleClass('expanded');
    return false;
}

///
/// Context Menu
///
function waitForContextMenu($this) {

    if (!$this.hasClass('hovered')) {
        // Этот товар уже неактивный, значит, меню показывать не будем
        return false;
    }
    // Товар активный, поэтому нужно показать меню. Определяем координаты блока меню
    var offset = $this.offset();                                                    // Координаты слоя с фотографией товара относительно всего документа
    var left = Math.round(offset.left + 100);                                       // Смещаем блок с меню вправо относительно блока с фотографией
    var delta = $('html')[0].clientWidth - (left + $('#context-menu').width() + 20) ;    // Определяем ширину той части блока меню, которая не помещается на экране

    if ( delta < 0 ) {
        // И правда что-то не помещается, двигаем меню влево
        left += delta;
    }
    left += 'px';

    var top = Math.round(offset.top + 40) + 'px';                                   // Смещаем блок с меню вниз относительно блока с фотографией

    var $menu = $('#context-menu');

    // Получаем id активного товара
    var id = parseInt($this.parent('li:first').attr('id').replace(/^gcard-/, ''));
    // Исправляем URL'ы контекстного меню
    $('#add-to-cart', $menu).attr('href', '/cart/add-good-'+id+'.html');
    $('#add-to-compare', $menu).attr('href', '/compare/add-good-'+id+'.html');

    // Формируем ссылку на картинку
    var $img = $('div.img-inner a img', $this);
    if ( $img.size() ) {
        // Есть фотография
        $('#enlarge-photo', $menu).parent().html('<a href="#" id="enlarge-photo" target="_blank">увеличить фото</a>');
        var img_url = $img.attr('src').replace(/^\/thumbnails\//, '/files/').replace(/\/\d+x\d+\//, '/');
        $('#enlarge-photo', $menu).attr('href', img_url).lightBox({
            imageLoading:    '/media/images/lightbox/ico-loading.gif',
            imageBtnPrev:    '/media/images/lightbox/btn-prev.gif',
            imageBtnNext:    '/media/images/lightbox/btn-next.gif',
            imageBtnClose:   '/media/images/lightbox/btn-close.png',
            imageBlank:      '/media/images/lightbox/blank.gif',
            overlayOpacity:  0.4
        });
    }
    else {
        // Фотографии нет
        $('#enlarge-photo', $menu).parent().html('<span id="enlarge-photo" class="disabled">увеличить фото</span>');
    }

    $menu.css({ 'left':left, 'top':top}).show();                       // Позиционируем и отображаем блок меню
    $this.data('timeoutId', 0)                                                      // Сбрасываем идентификатор задержки
}

function hideContextMenu() {
    // Прячем контекстное меню, если нет ни одного активного товара/меню
    if (!$('#main-content > div.content-container > ul.small-goods-list > li.small-goods-item > div.hovered').size() && !$('#context-menu').hasClass('hovered')) {
        $('#context-menu').hide();
    }
}

function updateSaleNav() {
    if ( undefined === window.active_sale ) {
        return;
    }

    if ( active_sale ) {
        $('#sale-back').removeClass('disabled');
    }
    else {
        $('#sale-back').addClass('disabled');
    }

    if ( active_sale < (sales.length - 1) ) {
        $('#sale-forward').removeClass('disabled');
    }
    else {
        $('#sale-forward').addClass('disabled');
    }
}
function changeSale(ind) {

    if ( ind < 0 || ind >= sales.length ) {
        return false;
    }

    var cur_sale = sales[ind];
    $('#sale-item').html('<a href="' + Helpers.html(cur_sale['url']) + '">' + Helpers.html(cur_sale['linked_text']) + '</a> ' + Helpers.html(cur_sale['unlinked_text']));

    active_sale = ind;
    updateSaleNav();

}

function playBannerCarouselClick() {
    $('#banner-carousel').cycle('resume');
    $('#banner-carousel-action .action a').removeClass('play')
                                          .addClass('pause')
                                          .attr({
                                            title : 'Пауза'
                                          })
                                          .unbind('click', playBannerCarouselClick)
                                          .bind('click', pauseBannerCarouselClick);
} // end of function playBannerCarouselClick

function pauseBannerCarouselClick() {
    $('#banner-carousel').cycle('pause');
    $('#banner-carousel-action .action a').removeClass('pause')
                                          .addClass('play')
                                          .attr({
                                            title : 'Возобновить'
                                          })
                                          .unbind('click', pauseBannerCarouselClick)
                                          .bind('click', playBannerCarouselClick);
} // end of function pauseBannerCarouselClick

/**
 * Класс для работы с корзиной
 */
Cart = function() {

    this.goods = {};
    this.goodsCnt = 0;
    this.goodsSum = 0;

    ///
    /// Загрузка товаров из куки
    ///
    this.loadGoods = function() {
        this.goods = {};
        this.goodsCnt = 0;
        this.goodsSum = 0;

        var rawGoods = $.cookie('cart');

        if ( rawGoods != null && rawGoods.match(/^(\d+\:\d+)(\|(\d+\:\d+))*$/) ) {
            var chunks = rawGoods.split('|');

            for ( var i=0; i < chunks.length; i++ ) {
                var buf = chunks[i].split(':');
                var entid = parseInt(buf[0]);
                var quantity = parseInt(buf[1]);
                if ( undefined === cart_prices[entid] ) {
                    // Товар не существует, пропускаем его
                    continue;
                }
                this.goods[entid] = quantity;
                this.goodsCnt += quantity;
                this.goodsSum += quantity * cart_prices[entid];
            }
        }
    } // end of method loadGoods()

    ///
    /// Сохранение товаров в куку
    ///
    this.saveGoods = function(goods) {
        var rawGoods = '';

        for ( k in this.goods ) {
            if ( this.goods[k] != undefined ) {
                rawGoods += ((rawGoods == '') ? '' : '|') + k + ':' + this.goods[k];
            }
        }

        $.cookie('cart', rawGoods, {expires: 1000, path: '/'});
    } // end of method saveGoods()

    ///
    /// Изменение количества товара
    ///
    this.changeQuantity = function(el, quantity) {
        var entid = parseInt(el.id.replace(/^[^\d]+/, ''));
        quantity = parseInt(quantity);
        if ( isNaN(quantity) ) {
            quantity = 0;
        }

        this.loadGoods();

        if ( this.goods[entid] != undefined ) {
            // Товар уже есть в корзине
            var oldQuantity = this.goods[entid];
        }
        else {
            var oldQuantity = 0;
        }

        if ( quantity == 0 ) {
            this.goods[entid] = undefined;
        }
        else {
            this.goods[entid] = quantity;
        }

        this.goodsCnt += quantity - oldQuantity;
        this.goodsSum += (quantity - oldQuantity) * cart_prices[entid];
        this.saveGoods();

        // Обновляем изображение корзины
        this.redrawCart(entid, quantity);
    } // end of method changeQuantity()

    ///
    /// Удаление товара из корзины
    ///
    this.deleteGood = function(el) {
        if ( !confirm('Вы действительно хотите удалить этот товар?') ) {
            return;
        }

        this.changeQuantity(el, 0);

        if ( this.goodsCnt ) {
            // Товары еще остались, удаляем только текущий
            $(el).parents('tr').remove();
        }
        else {
            // Товаров больше нет, скрываем форму отправки заказа
            $('#main-content div.content-container').html('<h1>Корзина покупателя</h1><p class="top-indent">Корзина пуста</p>');
        }
    } // end of method deleteGood()

    ///
    /// Отрисовываем корзину
    ///
    this.redrawCart = function(entid, quantity) {

        // Перерисовываем только сумму для измененного товара,
        // общую сумму и количество товаров в корзине
        // Выводим количество товаров в корзине
        $('#shopping-cart-link span.total-goods').html('('+this.goodsCnt+')');

        // Выводим стоимость товара
        $('#cost-'+entid).html(Helpers.sum(cart_prices[entid]*quantity)+'&nbsp;грн');

        // Выводим общую стоимость
        $('#cost-total').html(Helpers.sum(this.goodsSum)+'&nbsp;грн');

    } // end of method redrawCart()

    ///
    /// Пересчет количества товаров в корзине
    ///
    this.recalcGoodsCnt = function() {
        var rawGoods = $.cookie('cart');
        var goodsCnt = 0;

        if ( rawGoods != null && rawGoods.match(/^(\d+\:\d+)(\|(\d+\:\d+))*$/) ) {
            var chunks = rawGoods.split('|');

            for ( var i=0; i < chunks.length; i++ ) {
                var buf = chunks[i].split(':');
                goodsCnt += parseInt(buf[1]);
            }
        }

        $('#shopping-cart-link span.total-goods').html('('+goodsCnt+')');
    } // end of method recalcGoodsCnt()
} // end of class cart

var cart = new Cart;
init();

