var CONTEXT_PATH_LOCALE = CONTEXT_PATH;
var SHOWIN_SUBMENU = false;
var COFFEESHOP_SHOP = false;
var PHOTO_CONTROL_ACTIVE = false;

var DO_SHOW_SUBMENU = false;
var ITEM_HIGHLIT = false;

var MAIN_SLIDESHOW_PAUSE = false;
var HASH_CHANGE_SUBSCRIBERS = [];

var bigLed;

var topMenu;
var coffeePlaces;
var catalogue;
var mainSlides;

var menuItems;
var menuItemsRating;
var careers;

var citySelector;

$(document).ready(function() {

    CONTEXT_PATH_LOCALE = CONTEXT_PATH + $('#locale_lang').val() + '/';

    bigLed = new BigLed();
    mainSlides = new MainSlides();
    catalogue = new Catalogue();
    topMenu = new TopMenu();
    coffeePlaces = new CoffeePlaces();
    menuItems = new MenuItems();
    menuItemsRating = new MenuItemsRating();
    careers = new Careers();
    citySelector = new CitySelector();

    //initCoffeeshopsMenu();
    initNutritions();
    initListItems();
    initChangeCaptcha();

    if (typeof $.history != 'undefined') {
        $.history.init(function(url) {
            for (var index in HASH_CHANGE_SUBSCRIBERS) {
                HASH_CHANGE_SUBSCRIBERS[index](url);
            }
        });
    }

    if (typeof _ga != 'undefined' && typeof _gaq != 'undefined') {

        _ga.trackComments(); // assumes properly set up & initialized GA social tracking

        /*if (parseInt($('#authd').val()) > 0) {
            _gaq.push(['_setCustomVar', 1, 'User Type', 'Member', 2]);
        } else {
            _gaq.push(['_setCustomVar', 1, 'User Type', 'Visitor', 2]);
        }
        _gaq.push(['_setCustomVar', 1, 'User Type', 'Visitor', 2]);*/
    }


});

function BigLed() {
    this.el = $('#global-loading');
}

BigLed.prototype.show = function() {
    this.el.css({
        'top': '50%',
        'left': '50%'
    });
    this.el.fadeIn(200);
}

BigLed.prototype.hide = function() {
    this.el.fadeOut(300);
}

function TopMenu() {
    this.submenuWrap = $('#top-submenu-outer-wrap');
    this.init();

    $('#submenu-content-business').show();
}

TopMenu.prototype.init = function() {
    var topMenu = this;
    $('#top-menu>ul>li>a').mouseenter(function() {

        DO_SHOW_SUBMENU = true;
        var item = $(this);
        //item.parent().addClass('hl');

        // issue #55
        setTimeout(function() {

            if (!DO_SHOW_SUBMENU) {
                return;
            }


            var id = item.attr('id').split('-')[2];
            var smc = $('#' + 'submenu-content-' + id);

            if (SHOWIN_SUBMENU != id) {
                SHOWIN_SUBMENU = false;

                topMenu.submenuWrap.stop(true, true).fadeOut(100, function() {
                    topMenu.submenuWrap.css('left', '0px');
                    $('#top-menu>ul>li>a').each(function() {
                        var item = $(this).parent();
                        // don't remove 'hl' class from menu section user is in now
                        if (!item.hasClass('keephl')) {
                            item.removeClass('hl');
                        }
                    });
                    $('#btn-tm-' + id).parent().addClass('hl');
                });
            }

            if (smc.is('div') && (SHOWIN_SUBMENU == false || SHOWIN_SUBMENU != id)) {
                SHOWIN_SUBMENU = id;
                $('#top-submenu-wrap-2').html($(smc.html()));
                //$(this).append($('#top-submenu-outer-wrap'));
                topMenu.submenuWrap.stop(true, true).fadeIn(300);
                /*$('#top-submenu-outer-wrap').css('width', 'auto');*/

                var main_width = $('#main').width();

                var menu_item_left_offset = item.parent().position().left;
                var submenu_width = topMenu.submenuWrap.width();
                var submenu_offset = 95;

                if (menu_item_left_offset+submenu_offset+submenu_width >= main_width) {

                    // compensate if submenu too wide

                    var comp = menu_item_left_offset+submenu_offset+submenu_width
                            - main_width + 18;

                    topMenu.submenuWrap.css('left',
                            (menu_item_left_offset+submenu_offset-comp) + 'px');
                } else {
                    topMenu.submenuWrap.css('left', (menu_item_left_offset+submenu_offset) + 'px');
                }

            }

        }, 170);
    }).mouseleave(function() {
        DO_SHOW_SUBMENU = false;
        var btn = $(this);
        if (SHOWIN_SUBMENU == false && !btn.parent().hasClass('keephl')) {
            btn.parent().removeClass('hl');
        }
        //alert("leavin");
        //if (KEEP_TOP_SUBMENU != true) {
            //$('#top-submenu-outer-wrap').hide();
        //}
    });

    $('#top-menu-wrap').mouseleave(function() {
        SHOWIN_SUBMENU = false;
        $('#top-menu>ul>li>a').each(function() {
            var item = $(this).parent();
            // don't remove 'hl' class from menu section user is in now
            if (!item.hasClass('keephl')) {
                item.removeClass('hl');
            }
        });


        //setTimeout(function() {

            topMenu.submenuWrap.fadeOut(300, function() {
                topMenu.submenuWrap.css('left', '0px');
            });

        //}, 50);

    });
}


function CoffeePlaces() {
    this.initPlaces();
    this.requestedPlace();
    this.initPhotos();
    HASH_CHANGE_SUBSCRIBERS.push(this.hashChange);
}


CoffeePlaces.prototype.initPlaces = function() {

    $('.btn-place').click(function() {
        var href = $(this).attr('href');
        var tag = href.substring(href.lastIndexOf('/') + 1);
        $.history.load(tag);
        //coffeePlaces.loadPlace(tag)
        return false;
    }).mouseenter(function() {
        var href = $(this).attr('href');
        var tag = href.substring(href.indexOf('#') + 1);
        tag = tag.substring(tag.lastIndexOf('/') + 1);
        setTimeout(function() {
            coffeePlaces.showPlaceMap(tag);
        }, 100);
    }).mouseleave(function() {
        var href = $(this).attr('href');
        var tag = href.substring(href.indexOf('#') + 1);
        tag = tag.substring(tag.lastIndexOf('/') + 1);
        setTimeout(function() {
            coffeePlaces.hidePlaceMap(tag);
        }, 100);

    });

    this.initMarkers();


}


CoffeePlaces.prototype.initMarkers = function() {
    var placesMap = $('#places-map');
    $('.place-marker').mouseover(function() {

        // total map heihgt = 349 px
        // total map widht = 975 px
        // preview block width = 352
        // preview block height = 128

        // marker height = 6 + 4

        var marker = $(this);

        var markerOffsetTop = marker.offset().top - placesMap.offset().top;
        var markerOffsetLeft = marker.offset().left - placesMap.offset().left;

        var previewOffsetTop = 0;
        var previewOffsetLeft = 0;


        var bottomHeight = 349 - markerOffsetTop;
        var rightWidth = 595 - markerOffsetLeft;



        //alert(bottomHeight);

        if (bottomHeight < 142) {
            previewOffsetTop = markerOffsetTop - 128;
        } else {
            previewOffsetTop = markerOffsetTop + 18;
        }

        if (rightWidth < 352) {
            previewOffsetLeft = 595 - 352;
        } else {
            previewOffsetLeft = markerOffsetLeft - 18;

        }

        var key = marker.attr('id').substring(13); // place-marker-[ID]
        //alert(previewOffsetTop);
        $('#place-preview-' + key).css({
            'top': previewOffsetTop + 'px',
            'left': previewOffsetLeft + 'px'
        }).stop(true, true).fadeIn(300);
    }).mouseout(function() {
        var key = $(this).attr('id').substring(13); // place-marker-[ID]
        $('#place-preview-' + key).stop(true, true).fadeOut(300);
    });
}


CoffeePlaces.prototype.requestedPlace = function() {
    var loc = window.location.href;
    var values = loc.substring(loc.indexOf('#')+1).split('/');
    for (key in values) {
        if (values[key].substring(0, 6) == 'place-') {
            var placeKey = values[key].substring(6);
            this.loadPlace(placeKey);
        }
    }
}


CoffeePlaces.prototype.showPlaceMap = function(placeTag) {
    /*alert('showing ' + placeTag);*/

    //$('#places-maps').show();
    //$('#places-maps>img').stop(true, true);
    setTimeout(function() {
        //$('#places-map').stop(true, true).hide();
    }, 200);
    $('#place-map-' + placeTag).fadeIn(300, function() {
        $(this).css('display', 'block');
    });
}

CoffeePlaces.prototype.hidePlaceMap = function(placeTag) {
    setTimeout(function() {
        //$('#places-map').stop(true, true).show();
    }, 200);
    $('#place-map-' + placeTag).fadeOut(300, function() {
        //$(this).removeClass('hl');
        //$('#places-maps').hide();
    });
}


CoffeePlaces.prototype.loadPlace = function(placeTag) {

    // TODO add en/ru ?

    //bigLed.show();
    $('#curtain').css('z-index', '5').show();
    $('#place-bg-curtain').css('z-index', '4').show();
    $(document).scrollTop(0);

    $.get(CONTEXT_PATH + 'x/places/load/' + placeTag + '/'
            + parseInt($('#city-id').val()),
        '', /* data */
        function(responseHtml) {

            $('#curtain').hide();

            $('#place-placeholder').html(responseHtml);
            var placePlaceholder = $('#place-wrap-placeholder');

            $('#place-wrap').replaceWith(placePlaceholder);
            placePlaceholder.attr('id', 'place-wrap');
            var placeWrap = $('#place-wrap');

            $('#place-wrap').fadeTo(300, 1, function() {
                $('#mediablock-wrap').animate({
                    'height': '410px'
                }, 300);
            });
            coffeePlaces.initPhotos();
            initChangeCaptcha();

            // wait until background image loads before toggling the viewport

            var backSrc = $('#place-bg').attr('src');
            var backImg = new Image();
            $('#place-bg').one('load', function() {

                //bigLed.hide();
                $('#place-bg-curtain').hide();



            }).each(function() {
                if(this.complete) {
                    $(this).load();
                }
            }).attr('src', backSrc);

            var placePagePlaceholder = $('#place-page-placeholder');
            $('#place-page-wrap').replaceWith(placePagePlaceholder);
            placePagePlaceholder.attr('id', 'place-page-wrap');
            $('#city-wrap').hide();
            $('#place-page-wrap').show();

            $('.back-to-city').click(function() {
                $.history.load('');
                return false;
            });

        }, 'html');



}


CoffeePlaces.prototype.hashChange = function(hash) {

    if (hash == 'comment') {
        return;
    }

    //alert(hash);

    var href = window.location.href;
    var places = href.substring(href.indexOf('places') + 7);
    // http://travelerscoffee.ru/places/nsk
    // http://travelerscoffee.ru/places/nsk/kalinina

    places = places.split('/');

    if (typeof hash != 'undefined' && hash.length > 0) {
        // check that hash doesn't have any extra parameters, e.g.:
        // https://www.travelerscoffee.ru/places
        // /nsk#gagarinskaya?utm_campaign=tweet009&utm_medium=twitter&utm_source=twitter
        if (hash.indexOf('?') > 0) {
            hash = hash.substring(0, hash.indexOf('?'));
        }
        coffeePlaces.loadPlace(hash);
    }

    if (typeof hash != 'undefined' && hash.length == 0
            && (places.length < 2 || places[1] == '#' || places[1] == '')) {
        coffeePlaces.backToCity();
    }
}


CoffeePlaces.prototype.backToCity = function() {
    $('#mediablock-wrap').animate({
        height: '349px'
    }, 300, function() {
        $('#place-wrap').fadeOut(300);
    });

    $('#city-wrap').show();
    $('#place-page-wrap').hide();

}


CoffeePlaces.prototype.initPhotos = function() {
    var scrlbl = $('.scrollable');
    if (scrlbl.is('div')) {
        scrlbl.scrollable();
    }
    this.initPhotosControl();
    this.initPhotosLinks();
}


CoffeePlaces.prototype.initPhotosControl = function() {

    this.backButtonActive = false;

    $('#place-photos-back').mouseenter(function() {
        coffeePlaces.backButtonActive = true;
    }).mouseleave(function() {
        coffeePlaces.backButtonActive = false;
    });

    var controlWrap = $('#place-photos-control-wrap');
    controlWrap.mouseenter(function() {
        PHOTO_CONTROL_ACTIVE = true;
        wrap = $(this);
        setTimeout(function() {
            if (PHOTO_CONTROL_ACTIVE) {
                wrap.animate({
                    'height': '106px' /* TODO MAGIC */
                });
            }
        }, 100);
    }).mouseleave(function() {
        PHOTO_CONTROL_ACTIVE = false;
        setTimeout(function() {
            if (!coffeePlaces.backButtonActive && PHOTO_CONTROL_ACTIVE == false) {
                controlWrap.animate({
                    'height': '18px'
                });
            }
        }, 1000);
    });

}


CoffeePlaces.prototype.initPhotosLinks = function() {

    $('.place-photos-links>a').click(function() {
        $('#place-photos-wrap').animate({
            'top': '0px'
        });
    });

    $('.place-photos-links>a').click(function() {
        var href = $(this).attr('href');
        coffeePlaces.loadPhoto(href);
        return false;
    });

    $('#place-photos-control').find('.items').find('a').click(function() {
        var href = $(this).attr('href');
        coffeePlaces.loadPhoto(href);
        return false;
    });


    $('#place-photos-back').click(function() {
        $('#place-photos-wrap').animate({
            'top': '500px'
        })
    });
}



CoffeePlaces.prototype.loadPhoto = function(src) {
    //alert(photoId);
    // switch the photo
    $('#place-photo-tmp').load(function() {

        /*var photoTmp = $('#place-photo-tmp');
        var photo = $('#place-photo');

        //photoTmp.css('zIndex', '3');

        photoTmp.fadeTo(800, 1, function() {

            $('#place-photo').attr('src', photoTmp.attr('src'));
            $('#place-photo-tmp').stop(true, true).hide();




        });*/

    }).attr('src', src);
}


var MAX_CALORIES = 2000.0;
var BAR_LENGTH = 139;

var initNutritions = function() {



    $('.btn-port,.btn-hund').click(function() {
        var btn = $(this);
        if (btn.hasClass('active')) {
            return;
        }
        var itemId = parseInt(btn.parent().parent().attr('id').split('-')[2]);

        btn.parent().find('.active').removeClass('active');
        btn.addClass('active');

        var weight = 100;
        if (btn.hasClass('btn-port')) {
            weight = parseInt(btn.parent().parent().parent()
                .find('.serving-val.hl:first').val());
            var selected = btn.parent().parent().find('.weight.hl:first');
            if (!selected.is('a')) {
                //alert('whee');
                var weightId = parseInt(btn.parent().parent().parent()
                        .find('.serving-val.hl:first').attr('id').split('-')[2]);
                $('#weight-' + weightId).addClass('hl');
            }
        } else {
            btn.parent().parent().find('.weight.hl').removeClass('hl');
        }

        calculateNutritions(weight, itemId);
    });

    $('.weight').click(function() {
        var btn = $(this);
        if (btn.hasClass('hl')) {
            return;
        }

        var itemId = parseInt(btn.parent().parent().attr('id').split('-')[2]);
        var portionId = parseInt(btn.attr('id').split('-')[1]);

        $('#price-disp-' + itemId).text($('#price-val-' + portionId).val());

        btn.parent().find('.weight.hl').removeClass('hl');
        btn.addClass('hl');
        btn.parent().find('.serving-val.hl').removeClass('hl');
        var servingVal = $('#serving-val-' + portionId);
        var nutrisWrap = $('#nutris-wrap-' + itemId);
        servingVal.addClass('hl');
        nutrisWrap.find('.btn-hund').removeClass('active');
        nutrisWrap.find('.btn-port').addClass('active');

        calculateNutritions(parseInt(servingVal.val()), itemId);
    });


    $('.serving-wrap>a.weight:first').trigger('click');

}

var calculateNutritions = function (weight, itemId) {

    $('#nutris-wrap-' + itemId).find('.menu-item-nutri').each(function() {
        var item = $(this);

        var servingWrap = $('#nutris-wrap-' + itemId).find('.serving-wrap:first');
        var selectedPortionId = parseInt(servingWrap.find('.serving-id.hl:first').val());
        var currentProperty = item.attr('id').substring(0, item.attr('id').lastIndexOf('-'));

        //alert('#' + currentProperty + '-val-' + itemId + '-' + selectedPortionId);
        //alert(weight);

        //alert(currentProperty);

        var val = parseFloat($('#' + currentProperty + '-val-' + itemId).val());
        displayVal = Math.ceil(val * (parseFloat(weight) / 100));

        //alert('val: ' + val + ', displayVal: ' + displayVal);

        item.find('.nutri-disp>a').eq(0).text(displayVal);

        if (item.hasClass('nutri-kcal-wrap')) {
            val = Math.ceil((val / MAX_CALORIES) * BAR_LENGTH);
            val = val * (weight/100);
        } else {
            //alert(val + ' / ' + weight + ' = ' + val / weight + ';' + Math.ceil((val / weight) * BAR_LENGTH));
            val = Math.ceil((val / weight) * BAR_LENGTH);
        }

        if (val > 139) {
            val = 139;
        }

        item.find('.nutri-indic').eq(0).animate({
            'width': val + 'px'
        }, 900);
    });
}

/*$('#top-submenu-outer-wrap').mouseenter(function() {
    KEEP_TOP_SUBMENU = true;
}).mouseleave(function() {
    KEEP_TOP_SUBMENU = false;
});*/

var initListItems = function() {
    $('.item-preview-tint').fadeTo(0,0).css('display', 'none');

    $('.list-item,.list-item-cat').each(function() {
        $(this).find('img').fadeTo(1, .7);
    }).mouseenter(function() {
        $(this).find('img').fadeTo(150, 1);
    }).mouseleave(function() {
        var item = $(this);
        if (item.find('.wrap:first').hasClass('hhll')) {
            return;
        }
        $(this).find('img').fadeTo(150, .7);
    });



    $('.list-item>.wrap').click(function(e) {
        //alert(e.pageX + ' ' + e.pageY);
        var item = $(this).parent();
        var id = parseInt(item.attr('id').split('-')[2]);

        calculateNutritions(100, id);

        var screenHeight = $('html').eq(0).height(); // browser viewport height
        var previewHeight = $('#menu-item-' + id + '-preview').height(); // height of the preview pop-yp
        var itemOffset = item.offset(); // item offset

        var scrollTop = $(window).scrollTop();
        /*alert();*/

        var offset = item.offset();
        var position = item.position();

        //alert(itemOffset.top-scrollTop + '-' + previewHeight);

        var leftOffset = offset.left - 527;
        /*var topOffset = (itemOffset.top-scrollTop) * 2 >= parseInt(screenHeight * 1)
                ? scrollTop + 30 + previewHeight > itemOffset.top
                    ? scrollTop + 30
                    : itemOffset.top - previewHeight + 48
                : scrollTop > offset.top - 30
                    ? scrollTop + 12
                    : offset.top + 12 + previewHeight > scrollTop+screenHeight
                        ? scrollTop + 24
                        : offset.top - 12;*/

        /*var topOffset = (itemOffset.top - previewHeight) > 36
            ? itemOffset.top - previewHeight + 48
            : scrollTop + 36;*/

        var topOffset = (itemOffset.top - previewHeight) > scrollTop - 36
            ? itemOffset.top - previewHeight + 48
            : scrollTop + 36;

        /*alert(topOffset);*/

        if (offset.left < 480) {
            $('#menu-item-' + id + '-preview').addClass('left');
            leftOffset = offset.left + 165;
        }

        var bgOffset = -1470;

        //alert(offset.top + '-' + topOffset + '?' + parseInt(previewHeight/2));

        var bgOffset = -1470 + (offset.top-topOffset) + 12;

        if (offset.top - topOffset < parseInt(previewHeight/2)) {
            // top of preview wrap is near top of thumb
            //bgOffset = -1470 - parseInt(previewHeight/2);
        } else {
        }

        $('#menu-item-' + id + '-preview').css({
            left: leftOffset + 'px',
            top: topOffset + 'px',
            backgroundPosition: '0 ' + bgOffset + 'px'
        }).fadeIn(300);

        item.find('.wrap:first').addClass('hhll');

        $('.item-preview-tint').css('display', 'block').fadeTo(300, .5);
        $('.item-preview-tint:last').insertBefore(item.find('.wrap:first'));
        return false;
    });

    $('.item-preview-tint').click(function() {
    });

    $('.btn-item-preview-close').click(function(e) {

        var item = $(this);
        //item.css('zIndex', '1');
        item.parent().parent().fadeOut(300, function() {
            $('.hhll').removeClass('hhll').trigger('mouseout');
        });
        $('.item-preview-tint').fadeTo(300, 0, function() {
            $(this).css('display', 'none');
        });

    });

    //$('#list-item-172').find('.wrap:first').trigger('click');
}

function Catalogue() {
    this.toggleOrderElements();
    this.initAddBtns();
    this.initDeleteBtns();
    this.initCleanBtn();
    this.initOrderForm();
    this.initAmountInputs();
}

Catalogue.prototype.initAddBtns = function() {
    //alert('ding');
    $('#list-items.catalogue,#catalogue-item-wrap').find('.btn-add').click(function() {
        var id = parseInt($(this).attr('id').split('-')[2]);
        //alert(id);
        $.post(CONTEXT_PATH + 'business/catalogue/add',
            'item_id=' + id,
            function(response) {
                if (response.status == 'ok') {
                    catalogue.addItemSuccess(response);
                } else {
                    alert(response.error);
                }
            }, 'json');
        return false;
    });
}

Catalogue.prototype.toggleOrderElements = function() {
    if ($('.selected-item').length < 1) {
        $('#selected-items-head').hide();
        $('#selected-items-empty').show();
        $('#preorder-footer').hide();
        $('#catalogue-selected-items').hide();

    } else {
        $('#selected-items-head').show();
        $('#selected-items-empty').hide();
        $('#preorder-footer').show();
        $('#catalogue-selected-items').show();
    }
}

Catalogue.prototype.addItemSuccess = function(response) {
    var itemRow = $('#selected-item-frame').clone();
    itemRow.find('.order-selected-item:first').text(response.data.item_title);
    itemRow.find('.item_amount:first').attr('name', 'item_amount_' + parseInt(response.data.item_id));
    itemRow.find('#btn-delete-').attr('id', 'btn-delete-' + parseInt(response.data.item_id));
    itemRow.attr('id', 'selected-item-' + parseInt(response.data.item_id));
    itemRow.addClass('selected-item');
    itemRow.insertBefore('#selected-item-frame');
    this.initDeleteBtns();
    this.toggleOrderElements();
}

Catalogue.prototype.initDeleteBtns = function() {
    $('#catalogue-selected-items').find('.btn-x-delete').unbind().click(function() {
        $.post(CONTEXT_PATH + 'business/catalogue/delete',
            'item_id=' + parseInt($(this).attr('id').split('-')[2]),
            function (response) {
                if (response.status == 'error') {
                    alert(response.error);
                    return;
                }
                $('#selected-item-' + parseInt(response.data.item_id)).remove();
                catalogue.toggleOrderElements();
            }, 'json');

    });
}

Catalogue.prototype.initCleanBtn = function() {
    $('#form-catalogue-clean').submit(function() {
        return confirm($('#msg-are-you-sure').val());
    });
}

Catalogue.prototype.initAmountInputs = function() {
    $('#catalogue-selected-items').find('.item_amount').change(function() {
        var inp = $(this);
        var id = parseInt(inp.attr('name').split('_')[2]);
        $.post(CONTEXT_PATH + 'business/catalogue/amount',
            'item_id=' + id + '&amount=' + inp.val(),
            function(response) {
                // do nothing
            }, 'json');
    });
}

Catalogue.prototype.initOrderForm = function() {
    $('#btn-close-order-form').click(function() {
        $('#catalogue-order-form').slideUp();
    });

    $('#btn-create-order').click(function() {
        $('#catalogue-order-form').slideDown();
    });

    $('#btn-send-order').click(function() {
        var catalogueOrderForm = $('#catalogue-order-form');
        $('#catalogue-selected-items').find('.selected-item').each(function() {
            var item = $(this);
            var id = parseInt(item.attr('id').split('-')[2]);
            //alert(id);
            if (id != NaN && id > 0) {
                var inp = $('<input type="hidden" name="item[' + id + ']" value="'
                        + item.find('.item_amount:first').val() + '" />');
                catalogueOrderForm.append(inp);
            }
        });
        //return false;
    });
}


function MainSlides() {
    if (!$('#main-show-control').is('div')) {
        return false;
    }
    this.slides = $('.main-show-slide');
    if (this.slides.length < 2) {
        return;
    }
    this.initControls();

        /*var backSrc = $('#place-bg').attr('src');
            var backImg = new Image();
            $('#place-bg').one('load', function() {

                $('#place-wrap').fadeTo(300, 1, function() {
                    $('#mediablock-wrap').animate({
                        'height': '410px'
                    }, 300);
                });

            }).each(function() {
                if(this.complete) {
                    $(this).load();
                }
            }).attr('src', backSrc);*/

    this.scheduleNext(0);
}

MainSlides.prototype.initControls = function() {
    var slider = this;
    $('#main-show-control>a').click(function() {
        $('#main-show-btn-p').trigger('click');
        slider.loadSlide(parseInt($(this).attr('id').split('-')[3]));
            $('#main-show-btn-p').addClass('hl');
            MAIN_SLIDESHOW_PAUSE = true;
    });

    $('#main-show-btn-p').click(function() {
        var btn = $(this);
        if (btn.hasClass('hl')) {
            btn.removeClass('hl');
            MAIN_SLIDESHOW_PAUSE = false;
            //mainSlides.scheduleNext();
        } else {
            btn.addClass('hl');
            MAIN_SLIDESHOW_PAUSE = true;
        }
    });
}

MainSlides.prototype.loadSlide = function(slideId) {
    var slide = $('#main-show-slide-' + slideId);
    slide.hide();
    slide.addClass('loading');

    // only load the slide when its image is loaded
    var slideImg = slide.find('img:first');
    var imgSrc = slideImg.attr('src');

    slideImg.one('load', function() {

        slide.fadeTo(1200, 1, function() {
            var slide = $(this);
            mainSlides.slides.removeClass('current');
            $(this).addClass('current');
            slide.removeClass('loading');

            $('#main-show-control>a').removeClass('hl');
            $('#main-show-btn-' + slideId).addClass('hl');

            mainSlides.scheduleNext();
        });

    }).each(function() {
        if(this.complete) {
            $(this).load();
        }
    }).attr('src', imgSrc);


}



MainSlides.prototype.scheduleNext = function(timeout) {
    if (typeof timeout === 'undefined' || isNaN(timeout)) {
        timeout = 3000;
    }

    setTimeout(function() {

        if (MAIN_SLIDESHOW_PAUSE) {
            mainSlides.scheduleNext();
            return;
        }

        var current = $('#main-show-wrap').find('.current:first');
        var next = current.next();
        if (!next.is('div') || next.attr('id') === 'curtain') {
            next = $('.main-show-slide:first');
        }
        var nextId = next.attr('id');
        nextId = nextId.split('-')[3];
        mainSlides.loadSlide(nextId);
    }, timeout);
}


function MenuItems() {
    this.initTint();
    this.initPopup();
}

MenuItems.prototype.initTint = function() {
    $('.item-preview-tint').click(function() {
        var highlit = $('a.hhll:first');
        if (highlit.is('a')) {
            var id = parseInt(highlit.parent().attr('id').split('-')[2]);
            $('#menu-item-' + id + '-preview').find('.btn-item-preview-close:first').trigger('click');
        }
    });
}

MenuItems.prototype.initPopup = function() {
    ESCAPE_EVENT_SUBSCRIBERS.push(this.closePopup);
}

MenuItems.prototype.closePopup = function() {
    var highlit = $('a.hhll:first');
    if (highlit.is('a')) {
        var id = parseInt(highlit.parent().attr('id').split('-')[2]);
        $('#menu-item-' + id + '-preview').find('.btn-item-preview-close:first').trigger('click');
    }
    //$('.btn-item-preview-close').trigger('click');
}


function Careers() {
    var careersWrap = $('#careers-wrap');
    if (!careersWrap.is('div')) {
        return false;
    }

    this.initMenu();
}

Careers.prototype.initMenu = function() {
    var menu = $('#careers-menu');
    var cityKey = 'nsk';
    menu.show();
    $('#btn-careers-' + cityKey).addClass('hl');
    $('#careers-' + cityKey).addClass('hl');

    menu.find('li').click(function() {
        var btn = $(this);
        if (btn.hasClass('clearleft')) {
            return;
        }

        menu.find('.hl').removeClass('hl');
        btn.addClass('hl');
        careers.showCity(btn.attr('id').split('-')[2]);

        return false;


    });
}

Careers.prototype.showCity = function(cityKey) {
    var found = $('#careers-' + cityKey);
    found.parent().find('.careers-city-wrap.hl').removeClass('hl');
    found.addClass('hl');
}


function MenuItemsRating() {
    this.initStarsWithin($('#wrap').parent());
}

MenuItemsRating.prototype.initStarsWithin = function(el) {
    this.initStarsHover(el);
    this.initRateBtns(el);
}

MenuItemsRating.prototype.initStarsHover = function(el) {
    var max = 5; // TODO MAGIC
    el.find('.stars>img').unbind('mouseover').mouseover(function() {
        var star = $(this);
        var id = parseInt(star.attr('class').split('-')[1]);
        for (var i = 1; i <= id; i++) {
            star.parent().find('.star-' + i + ':first').attr('src', CONTEXT_PATH + 'static/img/icon-star-small-100.png');
        }
        for (var i = id + 1; i <= max; i++) {
            star.parent().find('.star-' + i + ':first').attr('src', CONTEXT_PATH + 'static/img/icon-star-small-0.png');
        }
    }).unbind('mouseout').mouseout(function() {
        var star = $(this);
        var id = parseInt(star.attr('class').split('-')[1]);
        for (var i = 1; i <= max; i++) {
            star.parent().find('.star-' + i + ':first').each(function() {
                var currentStar = $(this);
                currentStar.attr('src', currentStar.attr('osrc'));
            });
        }
    });
}

MenuItemsRating.prototype.initRateBtns = function(el) {
    var mir = this;
    el.find('.stars>img').unbind('click').click(function() {
        var star = $(this);
        var itemId = parseInt(star.parent().attr('id').split('-')[1]);
        var rate = parseInt(star.attr('class').split('-')[1]);
        if (typeof _ga !== 'undefined' && _ga.trackMenuRating) {
            var gaLabel = star.parent().parent().find('.ga-stars-label:first').val();
            _ga.trackMenuRating(gaLabel, rate);
        }

        $.post(CONTEXT_PATH + 'menu/rate',
            'item_id=' + itemId + '&rate=' + rate,
            function (response) {
                if (response.status == 'ok') {
                    mir.rateSuccess(response);
                }
            }, 'json');
    });
}

MenuItemsRating.prototype.rateSuccess = function(response) {
    var itemId = parseInt(response.data.item_id);
    var newStars = $(document.createElement('div'));
    newStars.html($(response.data.rating_html));
    $('#stars-' + itemId).replaceWith(newStars);
    newStars.attr('id', 'stars-' + itemId).addClass('stars');

    this.initStarsWithin($('#stars-' + itemId).parent());
}

function CitySelector() {
    this.panel = $('#city-selection-wrap');
    this.initSelector();
}

CitySelector.prototype.initSelector = function() {
    $('#btn-select-city').click(function() {
        if (citySelector.panel.css('display') == 'block') {
            citySelector.panel.hide();
            return false;
        }
        citySelector.panel.show();
        var btn = $(this);
        var height = citySelector.panel.css('height');
        var btnOffsetTop = btn.offset().top;
        var scrollTop = $(document).scrollTop();
        var pixelsLeft = btnOffsetTop - scrollTop; // this is the amount of pixels between "city"
                                                                                             // button and upper border of scrolled window
        //alert(pixelsLeft);
        var citySelectorOffset = scrollTop + 36;

        citySelector.panel.css({
            'left': btn.offset().left - 564, /*    */
            'top': citySelectorOffset,
        });
        return false;
    });

    // close on escape
    ESCAPE_EVENT_SUBSCRIBERS.push(this.hideSelector);

    // close on close btn
    $('#btn-close-city-selection').click(function() {
        citySelector.hideSelector();
    });

    $('.btn-switch-city').click(function() {
        var id = parseInt($(this).attr('id').split('-')[3]);

        $.post(
            CONTEXT_PATH + 'selectcity',
            'city-id=' + id,
            function(response) {
                var loc = window.location.href;
                window.location = loc;
            }
        );
    });
}

CitySelector.prototype.hideSelector = function() {
    citySelector.panel.hide();
}

function initChangeCaptcha() {
    var btn = $('#btn-captcha-change');
    if (btn.is('a')) {

        btn.click(function() {

            $('.captcha-image').attr('src', CONTEXT_PATH + 'captcha/?operawhyuno=' + Math.random());
        });
    }
}

