

$(document).ready(function(){
    
    
   
    $.ajaxSetup({
        error: function(jqXHR, textStatus, errorThrown) {
            if (textStatus !== 'abort') {
                // если ошибка не вызвана abort - перенаправлять на страницу ошибки    
            }
        }
    });
    
    // global messageBox
     mMessageBox = new MessageBox();
    
    // инициализация страниц
    mPages = new Pages(start_scale);

    mPagesContent = new PagesContent();
    // показать статьи при загрузке
    //mPagesContent.show();

    // комментарии могут быть показаны для объектов (Article, Question)
    mComments = new Comments(mag);

    // создать экземпляр статьи
    mArticle = new Article();
    

    /*+++ Preview +++*/
    function Preview (_initMag) {
        var that = this;
        var initMag = _initMag;
        var currentMag = _initMag;
        var init = function () {
            changeNumberToString3Format();
            bind();
        };

        var bind = function () {
            that.obj.bind("click", function(event) {
                logEvent('previewClick');
                var target = $(event.target),
                        parent = $(event.target).parent();
                if (parent.hasClass("prev_left_div") || parent.hasClass("prev_right_div")) {
                    if (currentMag === initMag) {
                        go_to_page( parent.attr("id") );
                    } else {
                        //  that.obj.trigger("previewshowmagazine", { mag: currentMag, id: parent.attr("id") });
                        that.obj.trigger("previewshowmagazine", { mag: currentMag, page: parent.find('p').text() });
                    }
                }
                else if (target.hasClass("scrollbtn")) {
                    scrlbtn(target);
                }
            });
        }

        var changeNumberToString3Format = function() {
            $(".preview_content p").each(function(k, value) {
                var page = +$(value).text();
                switch (page) {
                    case -2: page = "0"; break;
                    case -1: page = "00"; break;
                    default: page = page.toString3(); break;
                }
                $(value).text(page);
            });
        };

        this.obj = $("#preview");
        this.setMag = function(magazine) {
            if (magazine === undefined) {
                return;
            }
            //TODO в разных номерах - разное число страниц
            currentMag = magazine;
            $("img", ".preview_element").each(function() {
                $(this).attr('src', $(this).attr('src').replace(/\/\d{2}\//, '/' + magazine + '/'));
            });
        };

        this.resize = function () {
            $("#preview").height($(window).height() - 83);
        };

        init();
    }
    /*--- Preview ---*/

    _preview = new Preview(+mag); //TODO in core init 

    /*+++ Main Page +++*/
    function MainPage (core) {
        //this._bind(core);
    }

    MainPage.prototype = {
        /* _bind: function ($core) {
         $("#linkToEditor, #redactorWordSmall").live('click', function () {
         document.location.href = "http://21mm.ru/?mag=" + newNumber + "#003"; //TODO event
         });

         $("#linkToContent, #journalContentSmall").live('click', function () {
         document.location.href = "http://21mm.ru/?mag=" + newNumber + "004"; //TODO event
         });
         }*/
    };
    /*--- Main Page ---*/

    /*+++ Core +++*/
    // init
    var $core = $("#core");
    topPanel = new TopPanel();
    $mainPage = new MainPage($core);



    /*--- Core ---*/

    var timeScroll = 0,
    timerId,
    lastScrollTop = 0,
    currentScrollTop = 0,
    TIME_ADMISSION = 250; // 0.1s

    function onscrollend () {
        return;
        
        
        var b = $('html, body'),
        max = 2274 + 1142,
        min = max - $(window).height() - 40,
        middle = min + (max - min) / 2,
        st = $(document).scrollTop();
        
        if (st < max && st > min) {
            if (currentScrollTop > lastScrollTop) {
                b.animate({ 'scrollTop' : max });
            }/* else {
                b.animate({ 'scrollTop' : min });
            }*/
        }        
    };
    
    function scrollWatcher () {
        if (+new Date - timeScroll >= TIME_ADMISSION) {
            onscrollend();
            if (timerId) {
                window.clearInterval(timerId);
                timerId = null;
            }
        }
    };
    
    $(document).scroll(function () {
        if (!timerId) {
            timerId = window.setInterval(scrollWatcher, 100);
        }
        timeScroll = +new Date;
        lastScrollTop = currentScrollTop;
        currentScrollTop = $(document).scrollTop();
    });


    function log() {
        var log = "";
        for(var i = 0, l = arguments.length; i < l; i++) {
            log += arguments[i] + " ";
        }

        if (typeof console !== 'undefined') {
            console.log(log);
        }
        else {
            alert(log);
        }
    }

    // dS definition
    var S = {
        normalpage      : $(".normalpage"),
        preview_content : $(".preview_content"),
        prev_divs       : $(".prev_left_div, .prev_right_div"),
        prev_right_div  : $(".prev_right_div"),
        prev_left_div   : $(".prev_left_div"),
        prev_element    : $(".preview_element"),
        preview         : $("#preview"),
        highlighted_preview_id : null
    },
        //  lastHref,
            aboutbutton_url = "discussedAndPopular";

    var userAgent = navigator.userAgent.toLowerCase();
    jQuery.browser = {
        version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
        safari: /webkit/.test( userAgent ),
        opera: /opera/.test( userAgent ),
        msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
        mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
    };



    $(".aboutbutton").live("click",function() {
        aboutbutton_url = $(this).attr("url");
        if (!scaled) {
            switch_to_one_page_mode();
        }
        else {
            $("#mainText").html($("#"+$(this).attr("url")).html());
        }
    });

    $("#upbutimg").bind("mouseover",function(){
        $("#upbutton").stop();
        $("#upbutton").animate({opacity:1}, 500);
    });

    $("#upbutimg").bind("mouseout",function(){
        $("#upbutton").stop();
        if($("#upmenu").css("display")=='none'||$("#downpartmenu").css("display")=='none'){
            $("#upbutton").animate({opacity:opacity}, 500);
        }
    })

    function get_current(item, type) {
        var page_offset = $(".main").offset().top - $(document).scrollTop() - $("#blanckpalce").height();
        var page_height = $(".normalpage:last").height();
        var first_page_height = $(".normalpage:first").height();
        // -2.5 as так как сверху 2 pages, for one-pages-mode
        
        var topPageIndexAddition = - mPages.topCount() / 2 - 0.5;
        
        var index = ((scaled) ? topPageIndexAddition : 0) + 2.15 + ( (page_offset + first_page_height  ) / - page_height );
        var page = parseInt(index);
        var side = ( index > page + 0.5 ) ? "right" : "left";

        //TODO правильное определение текущей стрнаницы
        if (page <= 0) {
            page = 1;
            side = "left";
        }

        switch (item) {
            case "page":
                return (type === "int") ? page : page.toString3();
                break;
            case "list":
                return page.toString3() + "_" + side;
                break;
            case "side":
                return side;
            case "div":
                // текущий .normalpage для развороти и текущий .leftdivimage или .rightdivimage
                var div;
                if (scaled) {
                    div = $('.' + side + 'divimage', '#page' + page.toString3());
                } else {
                    div = $('#page' + page.toString3());
                }
                return div;
            default:
                break;
        }
    }

    function scrolldoc(){
        curpage = +get_current("page");


        if (scaled) {
            highlight_and_scroll_current_preview("list");
        }
        else {
            highlight_and_scroll_current_preview("page");
        }

        movepane();

        var fint = parseInt(firstpage,10)
        if(fint == 1){
            var numberofpage = curpage+parseInt(fint,10)-1;
        }
        else{
            var numberofpage = curpage+parseInt(fint,10);
        }

        if(numberofpage!=curentpage){
            
            curentpage= parseInt(numberofpage,10);
            testarr = String(curentpage).split("");
            switch (testarr.length){
                case 3:
                    break;
                case 2:
                    curentpage="0"+curentpage;
                    break;
                case 1:
                    curentpage="00"+curentpage;
                    break;
            }

            varscroll= false;
            load();
        }

    }

    function unhighlight_previews() {
        // TODO refactoring
        if (S.highlighted_preview_id) {
            if (scaled) {
                $("#" + S.highlighted_preview_id)
                        .css("border","1px solid transparent")
                        .find("p")
                        .show();
            }
            else {
                $(".preview_content", "#" + S.highlighted_preview_id)
                        .css("border", "1px solid transparent")
                        .find("p")
                        .show();
            }
            S.highlighted_preview_id = null;
        }
    }

    function highlight_and_scroll_current_preview(item, id)	{
        var cur_id;

        if (id === undefined) id = get_current(item);
        cur_id = (item === "page") ? id + "prev" : id;

        //showRealPagesInTopPanel(cur_id);
        topPanel.currentPage(cur_id);

        if (cur_id === S.highlighted_preview_id) return;

        unhighlight_previews();
        S.highlighted_preview_id = cur_id;

        $("p", "#" + cur_id).hide();

        if (item === "page") {
            $(".preview_content", "#" + cur_id)
                    .css("border","1px solid #ffffff");
        }
        else if (item === "list") {
            $("#" + cur_id)
                    .css("border","1px solid #ffffff")
        }

        scrollPreviewTo(cur_id);
    }

    var mPreview = new MPreview();

    function scrollPreviewTo(id) {
        mPreview.lasyLoad();

        if (id === undefined || id === null) {
            if (S.highlighted_preview_id === null) {
                return;
            }
            else {
                id = S.highlighted_preview_id;
            }
        }

        // todo fix
        try {
            var pos = parseInt($("#" + id).position().top + S.preview.scrollTop() - $(window).height()/2 + 122);
            S.preview.scrollTop( (pos < 0) ? 0 : pos );
        } catch(e) {}

    }

    function load(hash){
        if (arguments.lenght == 0) hash = true;

        refresh_max_and_min_page(curpage);
        $(".hashbtn").unbind("click");
        curentminus1= parseInt(curentpage,10)-1;
        curentplus1= parseInt(curentpage,10)+1;

        testarr = String(curentplus1).split("");
        switch (testarr.length){
            case 3:
                break;
            case 2:
                curentplus1="0"+curentplus1;
                break;
            case 1:
                curentplus1="00"+curentplus1;
                break;
        }
        testarr = String(curentminus1).split("");
        switch (testarr.length){
            case 3:
                break;
            case 2:
                curentminus1="0"+curentminus1;
                break;
            case 1:
                curentminus1="00"+curentminus1;
                break;
        }
        var minus=false;
        var plus=false;
        var cur = false;
        $.each(pages,function(index,value){
            if(curentminus1==value){
                minus=true;
            }
            if(curentplus1==value){
                plus=true;
            }
            if(curentpage==value){
                indexcur=index;
                cur=true;
            }
        });
        if(cur == true){
            $("#page" + curentpage).show();
            if (varscroll == true && hash == true) {
                //document.location.hash = curentpage;
                setHash(curentpage);
            }
            $(".hashbtn").bind("click",btn);
            renderdiv(curentpage);
        }
        else{
            pages.push(curentpage);
            indexcur = pages.length-1;
            if(varscroll==true&&hash==true){
                //document.location.hash = curentpage;
                setHash(curentpage);
            }
            $.ajax({
                url:"/welcome/ajax_page/"+curentpage+"?scaled="+scaled,
                data:{ 	mag: mag },
                dataType: 'json',
                type: "POST",
                success: function(data){

                    $(".hashbtn").bind("click",btn);

                    if(data=="error"){
                        return;
                    }
                    var obj = $("#page"+data.url);
                    obj.html(data.html);

                    AddButtonBuy();
                    //AddHtmlVersionButton();
                    if (scaled) {
                        make_one_page();
                    }

                    renderdiv(curentpage);

                    // показать какие статьи есть на страницах
                    //mPagesContent.showWidgets( $(".article, .voting", ".normalpage") ,get_current('div') );
                    mPagesContent.showWidgets( get_current('page') );
                }
            });
        }
        if(minus==true){
            $("#page"+curentminus1).show();
            renderdiv(curentpage);
        }else{
            pages.push(curentminus1);
            indexcur=indexcur+1;
            $.ajax({
                url:"/welcome/ajax_page/"+curentminus1+"?scaled="+scaled,
                data:{ 	mag: mag },
                dataType: 'json',
                type: "POST",
                success: function(data){

                    if(data=="error"){

                        return;
                    }

                    var obj = $("#page"+data.url);
                    obj.html(data.html);

                    AddButtonBuy();
                    //AddHtmlVersionButton();
                    if (scaled) {
                        make_one_page();
                    }
                    // показать какие статьи есть на страницах
                    //mPagesContent.showWidgets( $(".article, .voting", ".normalpage") ,get_current('div') );
                    mPagesContent.showWidgets( get_current('page') );
                }});
        }
        if(plus==true){
            $("#page"+curentplus1).show();
            renderdiv(curentpage);
        }else{
            pages.push(curentplus1);
            $.ajax({
                url:"/welcome/ajax_page/"+curentplus1+"?scaled="+scaled,
                data:{ 	mag: mag },
                dataType: 'json',
                type: "POST",
                success: function(data){

                    if(data=="error"){

                        return;
                    }

                    var obj = $("#page"+data.url);
                    obj.html(data.html);
                    AddButtonBuy();
                    //AddHtmlVersionButton();
                    if (scaled) {
                        make_one_page();
                    }
                    // показать какие статьи есть на страницах
                    //mPagesContent.showWidgets( $(".article, .voting", ".normalpage") ,get_current('div') );
                    mPagesContent.showWidgets( get_current('page') );
                }});
        }
        pages.sort();
        $.each(pages,function(index,value){
            if(curentpage==value){
                indexcur=index;

            }
        });
        indexmax=indexcur+2;
        indexmin=indexcur-2;

        var temparray = Array();
        $.each(pages,function(index,value){


            if(index<indexmin||index>indexmax){
                if(index<indexmin){
                    $("#page"+value).html("");
                }
                if(index>indexmax){
                    $("#page"+value).html("");
                }
            }
            else{
                temparray.push(value);
            }
        });
        pages=new Array();
        $.each(temparray,function(index,value){
            pages.push(value);
        });
    }
    var varscroll= true;

    function setHash(hash) {
        if (hash !== "#empty") goForward = true;
        document.location.hash = hash;
    }

    function renderdiv(curentpage){
        pages.sort();

        lastpage =curentpage;

        if(size<=960){
            $('#bodydiv').width("960px");
            $(document).scrollLeft((960 - size)/2)
        }
        makepane();
    }
    $(".hashbtn").bind("click",btn);
    function btn(){
        $("#upbutton").stop();
        $("#upmenu").stop();
        $("#upbutton").animate({opacity:opacity}, 500);
        $("#upmenu").animate({opacity:opacity}, 500);
        varscroll= true;
        $(".hashbtn").unbind("click");
        switch ($(this).attr('id')) {
            case "stepLeft":
                curentpage= parseInt(curentpage,10)-1;
                break;
            case "stepRight":
                curentpage= parseInt(curentpage,10)+1;
                break;


        }
        testarr = String(curentpage).split("");
        switch (testarr.length){
            case 3:
                break;
            case 2:
                curentpage="0"+curentpage;
                break;
            case 1:
                curentpage="00"+curentpage;
                break;
        }
        //document.location.hash=curentpage;
        setHash(curentpage);

    }
    var opacity = "0.4"
    var curentpage = curpage;
    var current_list = curpage + "_right";
    var lastpage = curpage;
    var
            max_page = 2,
            min_page = 0,
            min_main_offset = 8;
    var rightpage = false;
    var height = 0;
    var pages = new Array();
    var pageshistory = new Array();
    pages.push(curpage);
    var firstpage = curpage;
    pages.push(maxurl);
    if(minurl!="000"){
        pages.push(minurl);
    }
    pages.sort();
    /*$("#"+maxurl).hide();
     $("#"+minurl).hide();*/
    renderdiv(curpage);

    var size = 0;
    var thinScreen = false;
    function resizediv(){
        size = $(window).width();
        if(size <= 1446){
            $('#bodydiv').width("1050px");
            $(document).scrollLeft((1050 - size)/2);
            
            $(".topPanelContainer").css({"left" : "534px"});
            $('#icons_panel').addClass('small_panel');

            if (size <= 1090) {
                var k = 1090 - size,
                        navigationLeft =  534 - k/2,
                        bodydivWidth = 1050 - k;

                if (!scaled) {
                    //scaled = true;
                    var c_page = switch_to_one_page_mode();
                    if (c_page) go_to_page(c_page, "left");
                }

                $('#bodydiv').width(  bodydivWidth + "px" );
                $(".topPanelContainer").css({"left" : navigationLeft + "px"});
            }

        }else{
            $('#bodydiv').width("99%");
            $(".topPanelContainer").css({"left" : "50%"});
            $('#icons_panel').removeClass('small_panel');


        }

        var tOffLeft = $('.topPanel').offset().left;
        // подвинуть кабинет и окно входа по верхней панели
        $('#cabinet-container, #enter, #pop_articles').css('left', tOffLeft + 7 + 'px');
        
        $('#pop_articles, #m-article').css('left', tOffLeft - 1 + 'px');
        
        $('#orange_bottom_menu').css('left', tOffLeft + 18 + 'px' );

        // for ipad
        if( size <= 1260 ) {
            if (!thinScreen) {
                thinScreen = true;
                RightPanelSliding("on");
            }
        }
        else {
            if (thinScreen) {
                thinScreen = false;
                RightPanelSliding("off");
            }
        }

        // $("#scroll_container").height($(window).height() - $("#blanckpalce").height());
    }

    function RightPanelSliding(s) {
        var shift = '200',
                panel = $("#preview, #topbutton, #downbutton");

        if (s === "on") {

            slideDownRightPanel();
            panel.bind({
                mouseenter : function () {
                    SlideUpRightPanel();
                },
                mouseleave : function () {
                    slideDownRightPanel();
                }
            });
        }
        else if (s === 'off') {
            panel.unbind("mouseenter mouseleave");
            SlideUpRightPanel();
        }
    }

    function SlideUpRightPanel() {
        $("#preview").clearQueue().animate({ right: '6px' });
        $("#topbutton, #downbutton").clearQueue().animate({ right: '-11px' });
    }

    function slideDownRightPanel() {
        $("#preview").clearQueue().animate({ right: '-190px' });
        $("#topbutton, #downbutton").clearQueue().animate({ right: '-207px' });
    }


    function refresh_max_and_min_page(current_page) {
        var
                min = current_page - 1,
                max = current_page + 1;
        if ( max_page < max ) max_page = max;
        if ( min_page > min ) min_page = min;
    }

    function makescroll(){
        var hieght = $(window).height() - $("#topbutton").height() - $("#downbutton").height() + 19;
        $('#scroll').height(hieght);
        $('#scrollzone').height(hieght - $("#scrolldownbutton").height() - $("#scrollupbutton").height());
        makepane();
        movepane();
        $("#scrollupbutton").unbind("click");
        $('#scrollzone').unbind("click")
        $("#scrolldownbutton").unbind("click");
        $("#scrollupbutton").unbind("mousedown");
        $("#scrolldownbutton").unbind("mousedown");
        $("#scrollupbutton").unbind("mouseup");
        $("#scrolldownbutton").unbind("mouseup");

        $("#scrollupbutton").bind("mousedown",function(){
            $(".main").stop();
            move= setInterval(function(){
                movedown(-80)
            },200);
        });

        $("#scrolldownbutton").bind("mousedown",function(){
            move= setInterval(function(){
                movedown(80)
            },200);
        });

        $("#scrollupbutton").bind("mouseup mouseleave",function(){
            breakdown();
        });

        $("#scrolldownbutton").bind("mouseup mouseleave",function(){
            breakdown();
        });

        $("#scrollupbutton").bind("click",function(){
            scrollchange(-40)

        });
        $("#scrolldownbutton").bind("click",function(){
            scrollchange(40)
        });

        var click_timeout;
        $('#scrollzone').bind("mousedown", function(e) {
            jumpscroll(e);
            click_timeout = setTimeout(function() {
                move = setInterval(function() {
                    jumpscroll(e);
                }, 50);
            }, 230);
        });
        $("#scrollzone").bind("mouseup mouseleave", function() {
            clearInterval(click_timeout);
            breakdown();
        });
    }

    var move, scrollStartY;

    var iPad = !!navigator.userAgent.match(/iPad/);

    S.preview.bind({
        "mousewheel" : function(event, delta) {
            mPreview.lasyLoad();

            var m = 50;
            if(delta<0){
                S.preview.scrollTop(S.preview.scrollTop()+m);
            }
            else {
                S.preview.scrollTop(S.preview.scrollTop()-m);
            }
            return false;
        },
        'scrollstart' : function(event) {
            if (iPad) {
                scrollStartY = event.pageY;
            }
        },
        'scrollstop' : function(event) {
            if (iPad) {
                var diff = event.pageY - scrollStartY;
                S.preview.scrollTop(S.preview.scrollTop() + diff);
                scrollchange(scrollStartY - event.pageY);
            }
        }
    });

    function goToPrevPage () {
    	mPages.showPrevPage();
    	return;
    	
       /* var
                temp,
                c_page = get_current("page");

        temp = get_current("page", "int") - 1;
        temp = temp.toString3();

        if (scaled) {
            if (get_current("side") === "left") {
                if ($("#page" + temp).length !== 0) {
                    go_to_page(temp, "right");
                }
                else {
                    go_to_page("001", "left");
                }
            }
            else {
                go_to_page(c_page, "left");
            }
        }
        else {
            if ($("#page" + temp).length !== 0) {
                go_to_page(temp, "left");
            }
            else {
                go_to_page("001", "left");
            }
        }*/
    }

    function goToNextPage () {
    	mPages.showNextPage();
    	return;
        /*var
                temp,
                c_page = get_current("page");

        temp = get_current("page", "int") + 1;
        temp = temp.toString3();

        if (scaled) {
            if (get_current("side") === "right") {
                if ($("#page" + temp + "_left").length !== 0) {
                    go_to_page(temp, "left");
                }
                else {
                    go_to_page(c_page, "right");
                }
            }
            else {
                if ($("#" + c_page + "_right").length !== 0) {
                    go_to_page(c_page, "right");
                }
                else {
                    go_to_page(c_page, "left");
                }
            }
        }
        else {
            if ($("#page" + temp).length !== 0) {
                go_to_page(temp, "left");
            }
            else {
                go_to_page("current");
            }
        }*/
    }

    function scrlbtn(button) {
        switch ($(button).attr('rel')) {
            case "top":
                goToPrevPage();
                break;

            case "bottom":
                goToNextPage();
                break;
        }

    }
    //ll = 0;
    function go_to_page(page, side, init) {
       
        if (page === "") {
            page = get_current("page");
        }
        else if (page === "current" && side === undefined) {
            page = get_current("page");
            side = get_current("side");
        } else if (page === undefined) {
            page = "001";
            side = "left";
        } else if (page !== "" && side === undefined) {
            var target = page.split("_");
            page = target[0];
            side = target[1];
        }

        // TODO принимать настоящий номер страницы
        if (page === '001') {
            if (side === 'left') page = '0';
            else page = '00';
        } else if (side === 'left') {
            page = ((parseFloat(page) - 2) * 2).toString3();
        } else {
            page = ((parseFloat(page) - 2) * 2 + 1).toString3();
        }

        mPages.showPage(page);
        //mPages.showPage(page, side, scaled);


        return;

        setHash("empty");

        $(".main").css("top", "0px");


        /*if ( scaled || jQuery.browser.opera ) {
         //$(".main").offset({ top: 0 });
         }*/
        if (!scaled && jQuery.browser.opera) {
            if (init) {
                setTimeout(function() {
                    if (page === "001") {
                        scrollchange(-50);
                    }
                    else {
                        go_to_page(page, side);
                    }
                }, 100);
            }
            else if (page === "001") {
                scrollchange(-50);
            }
        }

        setHash(page);

        if (scaled) {
            if (page === "001" ) {
                $(".main").css("top", "0px");
                $('html').scrollTop(0);
            }
        };



        if (scaled) {
            highlight_and_scroll_current_preview("list", page + "_" + side);

            if (side == "right") {
                setTimeout(function(){
                    var halfPage;
                    if ( page === "001" ) {
                        //halfPage = ( $(".normalpage").height() - $("#bigAds").outerHeight(true) ) / 2;
                        halfPage = 1425;
                    }
                    else {
                        halfPage = 2284 / 2; //$(".normalpage").height() / 2;
                    }

                    target_offset = $("html").scrollTop() + halfPage;
                    //$(".main").offset({ top: target_offset });
                    $("html").scrollTop(target_offset);
                },100);
            }
        }
        else {
            highlight_and_scroll_current_preview("page");
        }
        movepane();
    }



    $("#inBegin").live("click",function() {
        go_to_page("001","left");

    });

    function jumpscroll(e){
        yz = e.pageY;
        yp = $('#scrollpane').offset().top;
        var count = $(window).height();

        if (yz > (yp+$('#scrollpane').height())){
            scrollchange(count)
        }
        if (yz < yp){
            scrollchange(-count)
        }
    }
    function breakdown(){
        clearInterval(move);
    }

    function movedown(pos){
        //$(".main").offset({ top: $(".main").offset().top - pos });
        scrolldoc();
    }

    function scrollchange(pos){
        var target_offset = $(".main").offset().top - pos;
        if(target_offset > $(document).scrollTop() + $("#blanckpalce").height()) {
            target_offset = $(document).scrollTop() + $("#blanckpalce").height()
        }
        if(target_offset < (-$(".main").height()+$(window).height())) {
            target_offset = (-$(".main").height()+$(window).height());
        }
        //$(".main").offset({ top: target_offset });
        scrolldoc();
    }

    function makepane(){
        if ( $('#scrollpane').height() == 48 ) return;

        var
                window_height = $(window).height(),
                document_heigth = $(".main").height(),
                scrollpane_height = Math.round((window_height - 40) * window_height / document_heigth);

        $('#scrollpane').height( ( scrollpane_height < 48 ) ? 48 : scrollpane_height );

    }

    function movepane(){
        var

                height_of_all_pages = $(".main").height(),
                scroll_zone = $("#scrollzone").height() - $('#scrollpane').height(),
                offset_mod = $(".main").offset().top -$(document).scrollTop(),
                from_the_top_to_the_middle =  - offset_mod + $(window).height()/2,
                position = Math.round(from_the_top_to_the_middle * scroll_zone / height_of_all_pages);
        $('#scrollpane').css("top", position + "px");
    }

    var pane_top_before_drag;

    $('#scrollpane')
            .draggable({
                containment: "#scrollzone",
                scroll:false,
                start: save_pane_position,
                drag: drag_scroll
            })
            .mousedown(function(event) {
                event.stopPropagation();
            });

    function save_pane_position() {
        pane_top_before_drag = parseInt($('#scrollpane').css("top"));
    }

    function drag_scroll() {
        var
                height_of_all_pages = $(".main").height(),
                scrollpane_top = parseInt($('#scrollpane').css("top")),
                scroll_zone_height = $("#scrollzone").height() - $('#scrollpane').height(),
                blanckpalce = $("#blanckpalce").height(),
                window_height = $(window).height(),
                target_offset = blanckpalce + $(document).scrollTop() - parseInt( scrollpane_top * height_of_all_pages / scroll_zone_height );

        if( target_offset < ( - height_of_all_pages + window_height ) ) {
            target_offset = ( - height_of_all_pages + window_height );
        }

        // $(".main").offset({ top: target_offset });
        scrolldoc();
    }

    $(window).resize(function(){
        resizediv();
        makescroll();
        scrollPreviewTo();
        _preview.resize();
    });

    $(window).resize();

    pageshistory.push(curpage);



    $("#upbutton").bind("click",dropmenu);
    $("#upmenu").bind("click",stop);
    $("body").bind("click",close);
    $("#searchInp").bind("focusin",hidedownmain);
    $("#searchInp").bind("click",stop);

    function stop(e){
        e.stopPropagation();
    }
    function hidedownmain(e){
        $("#downpartmenu").hide();
        $("#upmenu").slideDown(" ",function(){
            $("#upbutton").unbind("click");
            $("#upbutton").bind("click",dropdown);
            $("#uppartmenu").unbind("click");
            $("#searchInpW").focus();
        });
    }

    function close(){
        $("#upmenu").slideUp();
        $("#downpartmenu").slideDown();
        $("#upbutton").unbind("click");
        $("#upbutton").bind("click", dropmenu);

        $("#upbutimg").attr("src","/media/images/button.png");

        $("#upbutton").animate({opacity:opacity}, 500);
    }
    function dropmenu(e){
        e.stopPropagation();

        $("#upmenu").stop();
        $("#upmenu").slideDown();
        $("#upbutton").unbind("click");
        $("#upbutton").bind("click",upmenu);
        $("#uppartmenu").bind("click",hidedown);
        $("#upbutimg").attr("src","/media/images/Butt.png");

        $("#upbutton").animate({opacity:1}, 500);
        $("#upmenu").animate({opacity:1}, 500);
    }
    function hidedown(e){
        e.stopPropagation();
        $("#upbutton").unbind("click");
        $("#upbutton").bind("click",dropdown);
        $("#uppartmenu").unbind("click");
        $("#downpartmenu").slideUp();
        $("#upbutimg").attr("src","/media/images/button.png");
    }
    function dropdown(e){
        e.stopPropagation();

        $("#upmenu").stop();
        $("#upbutton").unbind("click");
        $("#upbutton").bind("click",upmenu);
        $("#uppartmenu").bind("click",hidedown);
        $("#downpartmenu").slideDown();
        $("#upbutimg").attr("src","/media/images/Butt.png");

        $("#upbutton").animate({opacity:1}, 500);
        $("#upmenu").animate({opacity:1}, 500);

    }
    function upmenu(e){
        e.stopPropagation();
        $("#upmenu").slideUp();
        $("#upbutton").unbind("click");
        $("#upbutton").bind("click", dropmenu);
        $("#upbutimg").attr("src","/media/images/button.png");

        $("#upbutton").animate({opacity:opacity}, 500);
    }



    var scaled = ( $(window).width() <= 1090 ) ? true : false;



    function switch_to_one_page_mode() {
        if(scaled) return;

        var c_page = get_current("page");
        $("body").removeClass("two-page-size").addClass("one-page-size");
        //$("#forhashback, body").removeClass("two-page-size").addClass("one-page-size");

        $(".scaleButton").toggle();
        //$(".main").toggleClass("minus plus");

        unhighlight_previews();
        scaled = true;

        if (pages.include("001")) {
            page_001_load(scaled);
        }

        make_one_page();
        changeimage();
        switch_widget_styles();
        $("#editbutton").prop("disabled", false);
        return c_page;
    }

    function switch_to_two_page_mode() {
        if(!scaled) return;
        var c_page = get_current("page");

        $("body").removeClass("one-page-size").addClass("two-page-size");

        //TODO fix in base
        $("#mUS1").addClass("activeItem");

        $(".scaleButton").toggle();
        //$(".main").toggleClass("minus plus");

        unhighlight_previews();
        scaled = false;

        if (pages.include("001")) {
            page_001_load(scaled);
        }

        make_two_page();
        changeimage();
        switch_widget_styles();
        $("#editbutton").prop("disabled", true);
        return c_page;
    }

    function changeimage(){
        $(".imagepage").each(function(){
            if(scaled){
                var str = $(this).attr("src");
                var tar = str.split(".");
                tar[0]=tar[0]+"large.jpg";
                //$(this).attr("height",1024);
                //$(this).attr("width",849);
                $(this).attr("src",tar[0]);
            }else{
                var str = $(this).attr("src");
                var tar = str.split("large");
                tar[0]=tar[0]+".jpg";
                //$(this).attr("height",593);
                //$(this).attr("width",480);
                $(this).attr("src",tar[0]);
            }
        });
    }
    var one_page_mode = {
        old_height: $(".normalpage").height() + "px",
        left: ($(".leftdivimage").width() / 2) + 5 + "px",
        right: - $(".rightdivimage").width() / 2 + "px"
    };

    function make_one_page() {

        if (pages.include("001") && aboutbutton_url) {
            $("#mainText").html($("#" + aboutbutton_url).html());
        }

       

        $("#centernav")
                .css({
                    "width" : "825px"
                });
        $(".topright")
                .css({
                    "width" : "389px"
                });
        $(".topleft")
                .css({
                    "width" : "335px"
                });
        $("#inBegin")
                .css({
                    "margin":"7px 0 0 26px"
                });
        $("#login")
                .css({
                    "margin":"5px 0 0 16px"
                });
        $("#password")
                .css({
                    "margin":"5px 0 0 15px"
                });

        $("#Entrance").css({ "margin-left" : "166px" });


        // for the preview
        S.preview_content
                .css({
            "padding" : "0px 0px",
            "width"	  : "75px"
        })
                .find("p")
                .css("margin-bottom", "0px")

        S.prev_divs
                .css({
            "padding" : "5px 8px",
            "height"  : "94px",
            "border"  : "1px solide transparent"
        });

        S.prev_right_div
                .css("margin-bottom", "6px");

        S.prev_left_div
                .css("margin-bottom", "8px");

        S.prev_element
                .css({
            "margin-left" : "36px",
            "height"      : "auto"
        });

        Stretch_first_page_for_bigAds();
        AddButtonBuy();
       // AddHtmlVersionButton();
    }

    function make_two_page() {
        $("#centernav")
                .css({
                    "width" : "940px"
                });

        $(".topright")
                .css({
                    "width" : "417px"
                });

        $(".topleft")
                .css({
                    "width" : "423px"
                });
        $("#inBegin")
                .css({
                    "margin":"7px 0 0 76px"
                });
        $("#login")
                .css({
                    "margin":"5px 0 0 20px"
                });
        $("#password")
                .css({
                    "margin":"5px 0 0 20px"
                });

        $("#Entrance").css({ "margin-left" : "194px" });


        /* for the preview */
        S.preview_content
                .css({
            "padding" : "5px 8px",
            "width"   : "auto"
        })
                .find("p")
                .css("margin-bottom", "-4px")

        S.prev_divs
                .css({
            "padding"       : "0px 0px",
            "margin-bottom" : "0px",
            "height"        : "auto"
        });

        $(".preview_element")
                .css({
                    "margin-left" : "0px",
                    "height"      : "115px"
                });
    }

    function openEditorDialog(){
        $.ajax({
            url:"/welcome/edit/",
            data:{
                mag: mag,
                page: get_current("page")
            },
            dataType: 'json',
            type: "POST",
            success: function(data){
                if(data.access=="true"){
                    var obj;
                    if (get_current("side") == "right"){
                        $("#page" + get_current("page") + " .rightdivimage > div").remove();
                        obj = $("#page"+ get_current("page")).find(".rightpage");
                        obj.append(data.rightdiv);
                    }else{
                        $("#page" + get_current("page") + " .leftdivimage > div").remove();
                        obj = $("#page"+ get_current("page")).find(".leftpage");
                        obj.append(data.leftdiv);
                    }

                    $("#dialog")
                            .draggable({
                                drag: function(event, ui) {
                                    $("#new_widget_button").css({ "left": ui.position.left, "top": ui.position.top })
                                }
                            })
                            .click(function(event) {
                                event.stopPropagation();
                            });


                    startEditMode();
                    $("#close_editing_mode").bind("click", exitEditMode);

                    fillAndBindScripts();

                    $("#delete_widget").bind("click", deleteWidget);
                    $("#save_widget").bind("click", submitRequest);

                }
            }
        });
    }

    function startEditMode() {
        $(".widget").die();

        $("#new_widget_button").draggable({
            helper: "clone",
            containment: '.editwidgetarea',
            revert: "invalid",
            distance: 30,
            start: function() {
                $(".editwidjet").deselectWidget();
            }
        });

        $(".editwidgetarea").droppable({
            drop: function(event, ui) {
                if (!$(ui.draggable).hasClass("new_widget_branch")) {
                    return;
                }

                var new_widget = $(ui.helper).clone()
                var new_widget_id = "new_" + String(parseInt(Math.random() * 1000000));

                $(this)
                        .append(new_widget)
                        .append('<div id="' + new_widget_id + '_params" class="params"></div>');

                new_widget
                        .attr("id", new_widget_id)
                        .removeClass("ui-draggable ui-draggable-dragging new_widget_branch")
                        .addClass("editwidjet new")
                        .editable()
                        .selectWidget()
                        .inValid();
            }
        });

        $(".editwidjet").editable();

        // disable "Start Edit" button
        $("#editbutton").prop("disabled", true);

        // edit area click hanlder
        $(".editwidgetarea").bind("click", function(event) {
            $(".editwidjet").deselectWidget();
        })
    }

    function exitEditMode() {
        liveWidgets();
        // make regular style
        $(".editwidjet").css("border-color", "black");

        // enable "Start Edit" button
        $("#editbutton").prop("disabled", false);

        // remove edit area
        $(".editwidgetarea").remove();

        sendData({
            callback: function (data) {
                if (get_current("side") == "right"){
                    $("#page" + get_current("page") + " .rightdivimage").append(data);
                }else{
                    $("#page" + get_current("page") + " .leftdivimage").append(data);
                }
            }
        });

    }

    var editing_widget_id = '';

    var widgetCss = {
        selected: {
            "background-color" : "blue",
            "opacity"          : "0.4"
        },
        deselected: {
            "background-color" : "",
            "opacity"          : "1"
        },
        inValid: {
            "border-color": "red"
        },
        valid: {
            "border-color": "green"
        }
    }

    $.fn.selectWidget = function () {
        if (editing_widget_id !== this.attr("id")) {

            $(".editwidjet").deselectWidget();

            editing_widget_id = this.attr("id");

            this.css(widgetCss.selected);

            $("#scripts").prop("disabled", false);

            if (!this.hasClass("new")) {
                this.addClass("edited");
            }

            if (this.attr("type") === undefined) {

                $("#select_script_option").removeAttr("disabled");
                $("#scripts").val("Р’С‹Р±РµСЂРёС‚Рµ СЃРєСЂРёРїС‚");
                $("#scripts").change();
            }
            else {
                $("#scripts").val(this.attr("type"));
                $("#scripts").change();
            }
        }

        return this;
    }

    $.fn.deselectWidget = function () {
        editing_widget_id = '';
        $("#select_script_option").removeAttr("disabled");
        $("#scripts").val("Р’С‹Р±РµСЂРёС‚Рµ СЃРєСЂРёРїС‚");
        $("#scripts").change();
        $("#scripts").prop("disabled", "true");
        return this.css(widgetCss.deselected);
    }

    $.fn.editable = function() {
        this.unbind();
        this
                .bind({
            click: function(event) {
                $(this).selectWidget();
                event.stopPropagation();
                event.preventDefault();
            }
        })
                .draggable({
                    containment: ".editwidgetarea",
                    start: function(event, ui) {
                        $(this).selectWidget();
                    }
                })
                .resizable({
                    //containment: $(this).parent(),
                    handles: "all",
                    start: function(event, ui) {
                        $(this).selectWidget();
                    }
                })
                .css("position", "absolute")
                .css(widgetCss.valid);
        return this;
    }

    $.fn.inValid = function () {
        return this.css(widgetCss.inValid);
    };

    $.fn.valid = function () {
        return this.css(widgetCss.valid);
    };

    function deleteWidget()	 {
        var id = editing_widget_id;
        if (id.substr(0,3) === "new") {
            $("#" + id).deselectWidget();
            $("#" + id).remove();
        }
        else {
            $(".editwidjet").each(function(key, value) {
                if ($(this).attr("id") == id) {
                    $(this)
                            .deselectWidget()
                            .removeClass("edited")
                            .addClass("deleted")
                            .hide();
                }
            });
        }

    }

    function submitRequest() {
        var widgets = [];

        $(".deleted").each(function(i, element) {
            widgets.push(queryToDelete($(this)));
        });

        $(".new").each(function(i, element) {
            widgets.push(queryToCreate($(this)));
        });

        $(".edited").each(function(i, element) {
            widgets.push(queryToUpdate($(this)));
        });

        if (widgets.length !== 0) {
            if (allFieldsFilled(widgets)) {
                sendData({
                    widgets: widgets,
                    callback: function() {
                        $(".editwidjet").removeClass("new edited");
                    }
                });
            }
            else {
                alert("Заполните все поля");
            }
        }
    }

    function sendData(params) {
        var
                send_data,
                flag,
                obj,
                widgets = params.widgets,
                callback = params.callback;

        if (get_current("side") == "right") {
            flag = 1;
        }
        else {
            flag = 0;
        }

        send_data = {
            flag: flag,
            mag: mag,
            curpage: get_current("page"),
            widjets: widgets
        };

        $.ajax({
            url: "/admin/save/",
            type: "POST",
            data: send_data,
            success: function(data){
                if (callback !== undefined) {
                    callback(data);
                }
            }
        });
    }

    function allFieldsFilled(widgets_array) {
        var filled = true;
        
        $.each(widgets_array, function(key, widget) {
        	
            if ( "params" in widget ) {
            	
            	
            	$.each(widgetTypes[widget.id].params, function (k, param) {
            		
            		$.each(widget.params, function(i, paramInWidget) {
            			if (paramInWidget.name === param.name) {
            				if (paramInWidget.value.length === 0) {
            					filled = false;
            				}
            			}
            		});
                //$.each(value.params, function(k, v) {
                    /*try {
                        if ( widget.params[param.name].length === 0) {
                            filled = false;
                        }
                    }
                    catch (e) {
                        filled = false;
                    }*/
                });
            }
        });
        return filled;
    }

    function queryToDelete(element) {
        return {
            widjetid: element.attr("id"),
            "delete": 1
        }
    }

    function queryToUpdate(element) {
        var query = queryToCreate(element);
        query.widjetid = element.attr("id");
        return query;
    }

    function queryToCreate(element) {
        var params_json,
                params = [],
                element_params,
                type = element.attr('type');

        element_params = $("#" + element.attr("id") + "_params").html();

        params_json = stringToObject(element_params);

        if (params_json !== null) {

            /*$.each(params_json, function(key, value){
             temp = {
             name:  key,
             value: value
             }
             params.push(temp);
             });	*/

            for(p in params_json){
                var temp = {
                    name:  p,
                    value: params_json[p]
                }
                params.push(temp);
            };

        }
        else {
            params.push({});
        }



        if (get_current("side") == "right") {
            obj = $("#page"+ get_current("page")).find(".rightpage");
        }
        else {
            obj = $("#page"+ get_current("page")).find(".leftpage");
        }

        var query = {
            id:     type,
            params: params,
            height: element.height(),
            width:  element.width(),
            top :   element.offset().top - obj.offset().top,
            left :  element.offset().left - obj.offset().left
        }

        return query;
    }

    $(".needparams").live({
        "keyup" : function() {
            if (!$("#" + editing_widget_id).hasClass("new")) {
                $("#" + editing_widget_id).addClass("edited");
            }

            if (isValid()) {
                $("#" + editing_widget_id).valid();
            }
            else {
                $("#" + editing_widget_id).inValid();
            }

            var params = stringToObject($("#" + editing_widget_id + "_params").html()),
                    key = $(this).attr("name");

            // спецсимволы вместо кавычек
            params[key] = $(this).val();

            $("#" + editing_widget_id + "_params").html(objectToString(params));
        },

        // для типа Voting
        "change" : function() {
            if ($(this).is('select')) {
                if (!$("#" + editing_widget_id).hasClass("new")) {
                    $("#" + editing_widget_id).addClass("edited");
                }

                if (isValid()) {
                    $("#" + editing_widget_id).valid();
                }
                else {
                    $("#" + editing_widget_id).inValid();
                }

                var params = stringToObject($("#" + editing_widget_id + "_params").html()),
                        key = $(this).attr("name");

                // спецсимволы вместо кавычек
                params[key] = $(this).val();
                params['question'] = $(this).find('option:selected').text();

                $("#" + editing_widget_id + "_params").html(objectToString(params));
            }
        }
    });

    function isValid() {
        var valid = true;
        $(".needparams").each(function() {
            if ($(this).val().length === 0) {
                valid = false;
            }
        });
        return valid;
    }

    // типы виджетов, для проверки заполнения всех полей
    var widgetTypes = null;
    function fillAndBindScripts() {
        $.ajax({
            url:"/admin/getscripts/",
            dataType: 'json',
            type: "POST",
            success: function(data){
            	widgetTypes = data;
                $.each(data,function(index,value){
                    $("#scripts").append("<option value='"+value.text+"'>"+value.text+"</option>");
                });
                $("#scripts").unbind("change");
                $("#scripts").bind("change", function(){
                    var script = $(this).val();
                    $("#needparams").empty();

                    // если выбран скрипт
                    if (script != "Выберите скрипт") {

                        // голосование
                        if (script == 'voting') {
                            $("#select_script_option").attr("disabled", "disabled");

                            // id объекта голосования, созданного, через админку
                            var value = data[script].params[0];

                            // текст вопроса голосования
                            var quest = data[script].params[1];

                            if (!value.options) {
                                $.ajax({
                                    url: '/ajax/get_questions',
                                    type: 'get',
                                    dataType: 'json',
                                    success: function(data) {

                                        value.options = data;
                                        value.html = '<input class="needparams" type="hidden" value="" name="' + quest.name + '" id="' + quest.name + '" />';
                                        value.html += '<label for="' + value.name + '">' + value.text + '</label><select  class="needparams" name="' + value.name + '" id="' + value.name + '">';
                                        value.html += '<option value="">Выберите опрос</option>';

                                        $.each(value.options, function(key, v) {
                                            value.html += '<option value="' + v.id + '">' + v.name + '</option>';
                                        });
                                        value.html += '</select>';
                                        $("#needparams").append(value.html);

                                        if (editing_widget_id !== '') {
                                            $("#" + editing_widget_id ).attr("type", script);
                                        }

                                        //var widget_params = $("#" + editing_widget_id + "_params").html().replace(/\\"/g, "\""); // remove \"
                                        var widget_params = $("#" + editing_widget_id + "_params").html();
                                        var params = stringToObject(widget_params);

                                        // если параметры не прочитаны из html
                                        if (params === null) {
                                            /*params = [];
                                             // собрать объект с пустыми параметрами
                                             $(".needparams").each(function() {
                                             params.push('"' + $(this).attr("name") + '":""');
                                             });
                                             params = '{' + params.join(',') + '}';*/


                                            params = {};
                                            // собрать объект с пустыми параметрами
                                            $(".needparams").each(function() {
                                                params[$(this).attr("name")] = '';
                                            });
                                            params = objectToString(params);


                                            // записать объект с параметрами в html
                                            $("#" + editing_widget_id + "_params").html(params);
                                        } else {
                                            // если параметры прочитаны - заполнить соответствующие поля
                                            $.each(params, function(key, value) {
                                                // разэкранировать кавычки
                                                var val = value;
                                                if (key) $("#" + key + ".needparams").val(val);
                                            });
                                        }
                                    }
                                });
                            } else {
                                $("#needparams").append(value.html);

                                if (editing_widget_id !== '') {$("#" + editing_widget_id ).attr("type", script); }
                                //var widget_params = $("#" + editing_widget_id + "_params").html().replace(/\\"/g, "\""); // remove \"
                                var widget_params = $("#" + editing_widget_id + "_params").html();
                                var params = stringToObject(widget_params);

                                if (params === null) {

                                    /*
                                     params = [];
                                     $(".needparams").each(function() {	params.push('"' + $(this).attr("name") + '":""');});
                                     params = '{' + params.join(',') + '}';
                                     $("#" + editing_widget_id + "_params").html(params);
                                     */
                                    params = {};
                                    // собрать объект с пустыми параметрами
                                    $(".needparams").each(function() {
                                        params[$(this).attr("name")] = '';
                                    });
                                    params = objectToString(params);


                                    // записать объект с параметрами в html
                                    $("#" + editing_widget_id + "_params").html(params);
                                } else {
                                    $.each(params, function(key, value) {
                                        if (key) $("#" + key + ".needparams").val(value);
                                    });
                                }
                            }


                            // всё кроме голосования
                        } else {
                            $("#select_script_option").attr("disabled", "disabled");
                            var new_needparams = '';
                            $.each(data[script].params, function(index,value){
                                new_needparams +=
                                        "<label for='"+value.name+"'>"+value.text+": </label>\
									<input class='needparams' name='"+value.name+"' id='"+value.name+"' type='input'><br>"
                            });
                            $("#needparams").append(new_needparams);

                            if (editing_widget_id !== '') {
                                $("#" + editing_widget_id ).attr("type", script);
                            }

                            //var widget_params = $("#" + editing_widget_id + "_params").html().replace(/\\"/g, "\""); // remove \"
                            var widget_params = $("#" + editing_widget_id + "_params").html();
                            var params = stringToObject(widget_params);

                            if (params === null) {
                                /*params = [];
                                 $(".needparams").each(function() {
                                 params.push('"' + $(this).attr("name") + '":""');
                                 });
                                 params = '{' + params.join(',') + '}';*/


                                params = {};
                                // собрать объект с пустыми параметрами
                                $(".needparams").each(function() {
                                    params[$(this).attr("name")] = '';
                                });
                                params = objectToString(params);
                                $("#" + editing_widget_id + "_params").html(params);
                            }
                            else {
                                for (name in params) {
                                    if (params.hasOwnProperty(name)) {
                                        $("#" + name + ".needparams").val(params[name]);
                                    }
                                }
                                /*$.each(params, function(key, value) {
                                 $("#" + key + ".needparams").val(value);
                                 });*/
                            }
                        }
                    }
                });
            }
        });
    }


    /*$(".tips").each(function() {
     $(this).attr("title", getParams($(this).attr("id")).text);
     });*/

    function getFieldFromParams(id, field) {
        try {
            var s = ($("#" + id + "_params").html());
            return $.parseJSON(s)[field];
        } catch (e) {
            return '';
        }

    }

    liveWidgets();

    function liveWidgets() {
        $(".tips-link").mmTooltip({
            emptySource: false,
            getMessage: function() {
                return getFieldFromParams($(this).attr("id"), 'text');
            }
        });

        $(".video").mmTooltip({
            emptySource: false,
            getMessage: function() {
                return getFieldFromParams($(this).attr("id"), 'rel');
            }
        });

        $(".video").live('click', function() {
            var id = $(this).attr("id");
            Video.show(id, getFieldFromParams(id, 'link'));
        });


        //$(".tips").live("click", showTip);
        $(".links, .tips-link").live({
            "click": function(e) {
                var params, linkpage, linktype;
                e.stopPropagation();

                if ($(this).is('a[href^="http://www.21mm.ru/#"]')) {
                    linkpage = $(this).attr('href').substr(-3);
                    if (scaled) {
                        switch_to_one_page_mode();
                        go_to_page(linkpage, "left");
                    } else {
                        switch_to_two_page_mode();
                        go_to_page(linkpage, "left");
                    }

                    e.preventDefault();
                    return false;
                } else if ($(this).attr('id') == '1787030' || $(this).attr('id') == '1787164') {
                    Video.show($(this).attr('id'));
                    //Video.show(this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'), $(this).attr('rel'), 1);
                    return false;
                }

                params = getParams($(this).attr("id"));
                linkpage = params.link.substr(0,3);
                linktype = params.linktype;

                switch (+linktype) {
                    case 1:
                        
                        // проверка на текущий номер
                        var reg = new RegExp('mag=' + mag);
                        if (reg.test(params.link) && !reg.test(document.location.href)) {
                            params.link = params.link.replace(/\?mag=\d{1,3}/, '');
                        }
                        document.location = params.link;
                        return false;
                        break;
                    case 2:
                        var targetPage = parseInt(linkpage, 10)/2 + 2;
                        switch_to_two_page_mode();
                        go_to_page(targetPage.toString3(), "left");
                        break;
                    case 3:
                        /*var temp  = parseInt(linkpage, 10) / 2 + 1.5,
                         page = Math.round(temp).toString3(),
                         side = (temp % 1 === 0.5) ? "left" : "right";
                         switch_to_one_page_mode();
                         go_to_page(page, side)*/


                        switch_to_one_page_mode();
                        mPages.onePageMode();
                        topPanel.onePageMode();
                        mPages.showPage(params.link);

                        break;
                }

            },
            mouseenter: function(event){
                var $this = $(this), id = $this.attr('id'), tip;
                if ((id != '1787030' && id != '1787164') || $this.hasClass('mmtooltip')) return;
                if (id == '1787030') tip =  "«Выбор», беседа с издателем Александром Новиковым";
                if (id == '1787164') tip = "«Отдых» (1), беседа с издателем Александром Новиковым";

                $(this).attr("rel", tip).addClass('mmtooltip');
                event.preventDefault();
                event.stopPropagation();
                $this.trigger('mouseenter', { pageX: event.pageX, pageY: event.pageY });
            }
        });
    }

    function showTip (e) {
        var params = getParams($(this).attr("id"));
        alert(params.text);
        e.stopPropagation();
    }

    function getParams(id) {
        return stringToObject($("#" + id + "_params").html());
    }

    function switch_widget_styles() {
        $(".widjet").each(function(i) {
            var temp_style = $(this).attr("stylesecond");
            $(this).attr("stylesecond", $(this).attr("style"));
            $(this).attr("style", temp_style);
        });
    }

    function objectToString (obj) {
        return JSON.stringify(obj);
        /*
         var pairs = [];
         $.each(obj, function(key, value) {
         if (value !== undefined) {
         pairs.push('"' + key + '":"' + value + '"');
         }
         });
         return '{' + pairs.join(',') + '}';
         */
    }

    function stringToObject(string) {
        return $.parseJSON(string);

        //var r = string.replace(/{"|"}/g, "").split(/":"|","/g)
        /*var r = string.replace(/{"|"}|}/g, "").split(/":"|","|":|,"/g);
         var obj = null;
         if (r.length >= 2) {

         for (var i = 0, l = r.length; i < l; i += 2) {
         obj || (obj = {});
         obj[ r[i] ] = r[i+1];
         }

         }

         return obj;*/
    }

    function page_001_load(scaled) {
        if (scaled) {
            //preprend to load big version of MainPage
            $(".mainpageBig").replaceWith('<div style="border: 0px;" class="leftdivimage leftpage"></div>');
            $("#page001").prepend('<div class="mainpageBig"></div>');
        } else {
            //preprend to load small version of MainPage
            $(".mainpageBig").remove();
            $("#page001 .leftdivimage").replaceWith('<div class="mainpageBig"></div>');
        }

        $.ajax({
            url: "/welcome/ajax_page/001?scaled="+scaled,
            data: {
                mag: mag
            },
            dataType: 'json',
            type: "POST",
            success: function(data){
                $(".hashbtn").bind("click",btn);

                if(data == "error") {
                    return;
                }
                var obj = $("#page"+data.url);
                obj.html(data.html);
                if (scaled){
                    make_one_page();
                }
                renderdiv(curentpage);
                // показать какие статьи есть на страницах
                //mPagesContent.showWidgets( $(".article, .voting", ".normalpage") ,get_current('div') );
                mPagesContent.showWidgets( get_current('page') );
            }
        });

        $.ajax({
            url: "/welcome/ajax_page/002?scaled="+scaled,
            data: {
                mag: mag
            },
            dataType: 'json',
            type: "POST",
            success: function(data){
                $(".hashbtn").bind("click",btn);

                if(data == "error") {
                    return;
                }
                var obj = $("#page"+data.url);
                obj.html(data.html);
                if (scaled){
                    make_one_page();
                }
                renderdiv(curentpage);
                // показать какие статьи есть на страницах
                //mPagesContent.showWidgets( $(".article, .voting", ".normalpage") ,get_current('div') );
                mPagesContent.showWidgets( get_current('page') );
            }
        });
    }

    $('.PersBottoms').live({
        mouseenter: function(){
            $(this).css('background','url(/media/images/main/PersBottomsAct.png)');
        },
        mouseleave: function(){
            $(this).css('background','url(/media/images/main/PersBottoms.png)');
        }
    });

    $('.tMPBMBottCent').live({
        mouseenter: function(){
            $(this).css('color','#ff5f11');
        },
        mouseleave: function(){
            $(this).css('color','#484848');
        }
    });

    $(".changeButt").live({
        mouseover: function(){
            $(this).removeClass("sodMailDiv").addClass("sodMailDivAct");
        },
        mouseout: function(){
            $(this).removeClass("sodMailDivAct").addClass("sodMailDiv");
        }
    });

    $(".changeButt2").live({
        mouseover: function(){
            $(this).removeClass("sodMailDiv2").addClass("sodMailDivAct2");
        },
        mouseout: function(){
            $(this).removeClass("sodMailDivAct2").addClass("sodMailDiv2");
        }
    });

    /* $(".addPrettyText").live({
     click : function(e) {
     alert("Р Р°Р·РґРµР» РЅР°С…РѕРґРёС‚СЃСЏ РІ СЂР°Р·СЂР°Р±РѕС‚РєРµ.");
     }
     });

     $(".removePrettyText").live({
     click : function() {
     $("p#prettyText").remove();
     }
     });*/





    // двойной клик по странице - переключить режим
    $(".main").dblclick(function(e) {
        if ( $(e.target).hasClass("imagepage")  ) {
        	
        	if (scaled) {
        		// если сейчас увеличен -> уменьшить
        		var c_page = switch_to_two_page_mode();
                mPages.twoPageMode();
                topPanel.twoPageMode();
            } else {
            	// если сейчас уменьшен -> увеличить
                var c_page = switch_to_one_page_mode();
                mPages.onePageMode();
                topPanel.onePageMode();
            }
        	
        	/*
            var side = $(e.target).closest("div");
            var page = side.closest("div.normalpage").attr("id");;

            if (side.hasClass("rightpage")) {
                side = "right";
            }
            else if (side.hasClass("leftpage")) {
                side = "left";
            }


            if (typeof page !== 'undefined') {
                if (scaled) {
                    switch_to_two_page_mode();
                    go_to_page(page, "left")
                }
                else {
                    switch_to_one_page_mode();
                    go_to_page(page, side);
                }
            }*/
        }
    });

    

    $(".inDevelope").live({
        click: function(e){
            e.stopPropagation();
            $("#alertOverlay").children().hide();
            $("#inDevelope").show();
            $("#alertOverlay").fadeToggle();
        }
    });

    $("#Entrance").live('click', function (){
        $("#alertOverlay").children().hide();
        $("#entranceDiv").show();
        $("#alertOverlay").fadeToggle();
    });

    $.fn.clearByFocus = function() {
        $(this).each(function(k, input) {
            var $input = $(input);
            var defaultText = $input.attr('init');
            $input
                    .focusin(function() {
                if ($input.val() === defaultText) {
                    $input.val("");
                }
            })
                    .focusout(function() {
                        if ($input.val().length === 0) {
                            $input.val(defaultText);
                        }
                    });

        });
        return $(this);
    };

    $(".clearByFocus").clearByFocus();

    

    $("#inDevelopeMessage").live("click", function(event) {
        event.stopPropagation();
    });

    // stretch first page for Big ads
    function Stretch_first_page_for_bigAds() {
        $("#bigAds").show();
        var shift = $("#bigAds").outerHeight(true),
                page = $("#" + "page001"),
                list = $(".rightdivimage", page),
                shadow = $(".rightshadow", page);

        page.height( page.height() + shift );
        list.css("top", parseInt( list.css("top") ) + shift + "px" );
        shadow.css("top", parseInt( shadow.css("top") ) + shift + "px" );
    };



    var cache = {};
    var pagesWithoutAdsObj = null;
    // add Button "Bye"
    function AddButtonBuy() {
        // newMag - глобальная переменная
        if (mag == newMag) {
            if (!pagesWithoutAdsObj) {
                pagesWithoutAdsObj = { left: ['001'], right: ['001'] };
                $.each(pagesWithoutAds, function(k, page) {
                    var integ = +page;
                    if (!isNaN(integ)) {
                        if (integ % 2) {
                            pagesWithoutAdsObj.right.push(((integ - 1) / 2 + 2).toString3());
                        } else {
                            pagesWithoutAdsObj.left.push( (integ / 2 + 2 ).toString3());
                        }
                    }
                });
            }

            $.each(pages, function(key, id) {
                var left = $("#page" + id).find(".leftpage");
                var right = $("#page" + id).find(".rightpage");



                if (pagesWithoutAdsObj.left.notInclude(id)) {

                    if (left.find(".buyRound").length === 0 ) {
                        left.prepend($("#buyRound ").html());
                    }
                }
                if (pagesWithoutAdsObj.right.notInclude(id)) {
                    if (right.find(".buyRound").length === 0 ) {
                        right.prepend($("#buyRound").html());
                    }
                }

            });

        }
    }

   /*function AddHtmlVersionButton() {
        $.each(pages, function(key, id) {
            var left = $("#page" + id).find(".leftpage");
            var right = $("#page" + id).find(".rightpage");
            var article, href = 'http://21dev.uniqhosting.ru/ajax/show_article/';
            if (right.find('.htmlVersion').length === 0 ) {
                article = right.find('.article:first');
                if (article.length) {
                    href += article.attr('id');
                    right.prepend('<a class="htmlVersion" target="_blank" href="' + href + '">текстовый вариант страницы</a>');
                }
            }

            if (left.find('.htmlVersion').length === 0 ) {
                article = left.find('.article:first');
                if (article.length) {
                    href += article.attr('id');
                    left.prepend('<a class="htmlVersion" target="_blank" href="' + href + '">текстовый вариант страницы</a>');
                }
            }
        });
    }*/

    $(".mmtooltip").mmTooltip();
    // $('#widget1').mmTooltip();

    /*- open Editor --*/
    var mmlogoClicked = 0;
    $(".searchContainer span").click(function() {
        mmlogoClicked += 1;
        if(mmlogoClicked === 5) {
            //if ("123456" === window.prompt('Нажмите отмена','null')) {
            openEditorDialog();
            //}
            mmlogoClicked = 0;
        } else {
            setTimeout(function() {
                if(mmlogoClicked !== 0) {
                    mmlogoClicked -= 1;
                }
            }, 2000);
        }
    });

    $("#goToReg").click(function () {
        $("#regDiv").show();
    });

    /*+++ Top Panel +++*/
    $(".topPanelSort").click(function (event) {
        var $target = $(event.target);
        if ($target.hasClass("prevPage")) {
            goToPrevPage();
        } else if ($target.hasClass("nextPage")) {
            goToNextPage();
        } else if ($target.hasClass("firstPage")) {
            go_to_page("001","left");
        } else if ($target.hasClass("lastPage")) {
            if (scaled) {
                go_to_page($(".normalpage:last").attr("id"), "right");
            } else {
                go_to_page($(".normalpage:last").attr("id"), "left");
            }
            //TODO в режиме страницы - правильно определять последнюю
        }
    });

    //change Background
    //if(typeof bodyBackgroundColor !== undefined) {
    //    $('body').css('background-color', '#' + bodyBackgroundColor);
    //}

    // клик на палитру изменения цвета
    $(".colorSample").live('click', function () {
        var hex = $(this).attr('data-color');
        $('body').css('background-color', '#' + hex);
        $.post('/ajax/setBodyBackgroundColor', { hex: hex });
    });




    /* +++ True Core ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
    _preview.obj.bind({
        'previewshowmagazine': function (event, params) {
            //TODO go to show real page with SCale!!
            // var page = params.id.match(/\d{3}/)[0];
            var page = params.page;
            // window.location.href = "http://21mm.ru/?mag=" + params.mag + "#" + page;
            window.location.href = "http://21mm.ru/?mag=" + params.mag + "#" + page;
        }
    });

    topPanel.obj.bind({
        /*'toppanelhome': function (event) {
            //switch_to_one_page_mode();
            //go_to_page("001", "left");
            
            mPages.showPage('0');
        },*/
        'toppanelswitchsize': function (event, params) {
            if (params.scaled) {
                //TODO scaled = true
                var c_page = switch_to_one_page_mode();
                /*if (document.location.hash === "#buy" &&  c_page === "059") {
                 go_to_page(c_page, "right");
                 } else {
                 go_to_page(c_page, "left");
                 }*/
                mPages.onePageMode();
                topPanel.onePageMode();
            } else {
                //TODO scaled = false
                var c_page = switch_to_two_page_mode();
                mPages.twoPageMode();
                topPanel.twoPageMode();
                //go_to_page(c_page, "left");
            }
        },
        'toppanelopenarchive': function () {
            if (!scaled) {
                switch_to_one_page_mode();
                mPages.onePageMode();
                topPanel.onePageMode();
            }
            
            //mArchive.show();
            mPages.showPage('topstart');
            
        }
        /*,
        'toppanelclosearchive': function () {
            //closeArchive();
        }*/
    });

    mArchive = new Archive(+mag, mPages.getTopPage(2, 'archive'));

    mArchive.bind("archiveselectnumber", function (event, params) {
        _preview.setMag(params.mag);
    });

    mArchive.bind("archiveclose", function (event) {
        $(".topPanelContainer, #overlay").unbind("mousewheel");
        //closeArchive();
        //topPanel.dropDown().hideUp();
    });
    
    mAbout = new About(+mag, mPages.getTopPage(4, 'about'));
   // mPages.getTopPage(5, 'empty')
    //mBlog = new Blog(+mag, mPages.getTopPage(6, 'blog'));

    

   

    $(".arch").live({
        click: function() {
            if (!scaled) {
                switch_to_one_page_mode();
            }
            //topPanel.showDown();
            
            
            mArchive.show();
            topPanel.bounceOrange();
            mPages.showPage('archive');
        }
    });

    //GO to last page
    function goToLastPage() {
        if (scaled) {
            go_to_page($(".normalpage:last").attr("id"), "right");
        } else {
            go_to_page($(".normalpage:last").attr("id"), "left");
        }
    }



    /* --- True Core ---------------------------------------------------------------------------------- */

    //Magic with hidden content
    var activeHiddenContentId = "where_to_buy";

    $(".viaHiddenContent").live("click", function (event) {
        if ($(event.target).hasClass('mmtooltip')) {
            return;
        }

        var target = $(this);
        activeHiddenContentId = target.attr("data-hidden-id");
        goToLastPage();
    });

    //Ajax core Handler
    $("#ajaxHandler").ajaxSuccess(function(e, x, ajaxOptions) {
        if (!!ajaxOptions.url.match(/059/)) {
            $("#main_button_content")
                    .empty()
                    .html($("#" + activeHiddenContentId).html());
        }
    });

    $('#002prev').after('<a class="ads-preview" target="_blank" href="http://www.galileo-tv.ru/">');

    // счётчик - загрузка страницы
    logEvent('pageload');

    mVoting = new Voting(mPages.getTopPage(1, 'voting'), mag);
    
    mContainer = new Container();
    
    // инициализация сообщества
    mCommunity = new Community(mPages.getTopPage(3, 'community/71'));

    // init Overlay
    mOverlay = new Overlay();

    // init questions
    mQuestions = new Questions(mag);

    // обработка событий Questions
    mQuestions.bind({
        // открытие Опроса
        'onshow': function() {
            // закрыть Коментарии к статье
            mArticle.hide();

            // изменить размер комментариев по размеру опроса
            var q = $('#m-question-subject').outerHeight(true) + $('.rating_results_div').outerHeight(true)  + $('#soc_icons_wrap').outerHeight(true) + $('#m-comment-show-window').outerHeight(true);
            $('#scroll_comments').height(420 - q);
        },
        'onclose': function() {
            mPagesContent.show();
            //mPagesContent.showWidgets( $(".article, .voting", ".normalpage") ,get_current('div') );
            mPagesContent.showWidgets( get_current('page') );
        }
    });

    

    // прокрутка документа
    $(window).bind("scroll",function(event){
        scrolldoc();
            
            mPages.scroll(event);
            topPanel.tryScroll();
            
            
    });
    
    $(document).bind('mousewheel', function(event, delta) {
        if(!scaled) return true;
        
        var st = $(document).scrollTop();
            if (mPages.topPageIsOpen) {
                /*var m = 3 - mPages.topIndex();
                if (delta > 0 && st <= m * 1142) {
                    $(document).scrollTop(m * 1142); 
                    return false;
                } else if (delta < 0 && st >= (m + 1) * 1142 - $(window).height() - 100) {
                    $(document).scrollTop((m + 1) * 1142 - $(window).height() - 100); 
                    return false;
                }*/
                if (delta < 0 && st >= mPages.topCount() * 1142 - $(window).height()) {
                    $(document).scrollTop(mPages.topCount() * 1142 - $(window).height() + 10); 
                    return false;
                }
            } else {
                if (delta > 0 && st <= mPages.topCount() * 1142) {
                    $(document).scrollTop(mPages.topCount() * 1142); 
                    return false;
                }
            }
        
        
        
        
    });
    
    // 
    account.bind({   
        'onopencabinet' : function() {
            mArticle.hide();
           // mQuestions.hide();
            mPagesContent.hide();
            mComments.hide();
        },
        // выход из аккаунта
        'onlogout' : function() {
            // запретить ставить рейтинг
            mArticle.ratingDisable(); 
            
         // обновить опросы
            if (mVoting.isOpened) {
                mVoting.show();
                mVoting.showTips();
            }
        },
        // вход в аккаунт
        'onlogin' : function() {
            // разрешить ставить рейтинг
            mArticle.ratingEnable(); 
            
            
            // обновить опросы
            if (mVoting.isOpened) {
                
                mVoting.show();
                mVoting.hideTips();
                
            }
        } 
    });

    // изменение страницы
    mPages.bind('pagechange', function() {
        Hash.go(mPages.current);
        mPreview.lasyLoad();
        // показать какие статьи есть на страницах
        //mPagesContent.showWidgets( $(".article, .voting", ".normalpage") ,get_current('div') );
        mPagesContent.showWidgets( get_current('page') );
        
        if (!mVoting.isOpened && mPages.current === 'voting') {
            mVoting.show();
        } else if (!mArchive.isOpened && mPages.current === 'archive') {
            mArchive.show();
        } else if (!mCommunity.isOpened && mPages.current === 'community/71') {
            mCommunity.show(71);
        } else if (!mAbout.isOpened && mPages.current === 'about') {
            mAbout.show();
        } /*else if (!mBlog.isOpened && mPages.current === 'blog') {
            mBlog.show();
        }*/
    });


    // клик по оверлею - закрыть сообщества
    mOverlay.bind('hide', function() {
        //community.hide();
        mOverlay.hide();
        mContainer.hide();
        // отобразить в хеше текущую страницу
        Hash.go('0');
        
        // вернуться на первую страницу
        mPages.showPage('0');
    });

    // клик   по иконке новикова под цитатой
    $('.question_thumbl').live('click', function() {
        if  ($(this).parent().siblings('.user-cloud').data('show')) {
            mCommunity.show(71);
            //mOverlay.show();
            Hash.go('community/71');
            return false;
        } 
    });
    
    // клик по кнопке  "Сообщетсва"
    $('#mUB5, #mUS5').live('click',function() {
        switch_to_one_page_mode();
        mPages.onePageMode();
        topPanel.onePageMode();
        mCommunity.show(71);
        //mOverlay.show();
        topPanel.bounceOrange();
        Hash.go('community/71');
    });
    
    // клик по кнопке  "about"
    $('#mUB2, #mUS2').live('click',function() {
       /* switch_to_one_page_mode();
        mPages.onePageMode();
        topPanel.onePageMode();
        mContainer.show('about');
        mOverlay.show();*/
        switch_to_one_page_mode();
        mPages.onePageMode();
        topPanel.onePageMode();
        mAbout.show();
        //mOverlay.show();
        topPanel.bounceOrange();
        Hash.go('about');
    });

    // клик по кнопке  "rubrik"
    $('#mUB4, #mUS4').live('click',function() {
        switch_to_one_page_mode();
        mPages.onePageMode();
        topPanel.onePageMode();
        coreNotice('toppanel down');
    });
    

    // клик по кнопке  "voting"
    /*$('.voting_show').live('click',function() {
       // mContainer.show();
        
        //mOverlay.show();
        switch_to_one_page_mode();
        mPages.onePageMode();
        topPanel.onePageMode();
        mVoting.show();
        mPages.showPage('voting');
        //
    });*/


    // обработка сообщества
    mCommunity.bind({
        'video': function(event, params) {

            // params.link - id видео на youtube
            //Video.show('http://www.youtube.com/v/' + params.link, params.title, 2);
            // params.id - id видео в базе
            Video.show(params.id);
        },
        'hide': function() {
            return false;
            
            mCommunity.hide();
            mOverlay.hide();
            // отобразить в хеше текущую страницу
            Hash.go('0');
            // кликнуть по кнопке "Главная" на главной странице
            $('#mUB1').mouseenter().click();
        }/*,
        'openarchive': function() {
            return false;
            
            community.hide();
            mOverlay.hide();
            // отобразить в хеше текущую страницу
            Hash.go('0');
            // кликнуть по кнопке "Главная" на главной странице
            $('#mUB1').mouseenter().click();
            if (!scaled) {
                switch_to_one_page_mode();
            }
            
            
            mArchive.show();
            mPages.showPage('archive');
        }*/
    });


    // Обработка статей
    mPagesContent.bind({
        // on module load
        'onload': function(event, data) {
            mPagesContent.showWidgets( get_current('page') );
        },
        
    	// клик по статье
        'onclickarticle': function(event, data) {
            
            // активировать статью
            mArticle.on = true;
            
            // ждать статьи с id и не вызывать onarticlechange пока она не откроется
            mPagesContent.waitingFor = data.page_id;
            mPages.scrollToPage(data.page_id, data.right);

            //mComments.setSubject(data.id, data.subject);
            mPagesContent.showWidgets( get_current('page') );
        },
        
        // страница прокручена до другой статьи ( текущая статья изменилась )
        'onarticlechange': function(event, data) {
            
            // если mArticle включен
        	if (mArticle.on) {
        	    
        	    // показать текущую статью
        	    mArticle.show(data.id);
        	    mComments.setSubject(data.id, data.subject);
        	}
        },
        
        'showvoting': function(event, data) {
            mQuestions.show(data.id);
            //mPages.scrollToWidget(data.id);

            mPages.scrollToPage(data.page_id);
            mComments.setSubject(data.id, data.subject);
        },
        'onshow': function() {
            // скрыть статью
            mArticle.hide();
            mQuestions.hide();
        }
    });

    // обработка комментариев
    mComments.live({
        // комментарии обновились
        'onreload' : function(event, data) {

            // виджет, который прокомментировали
            var commentedWidget = $('#' + data.subjectId)

            // увеличить на 1 число комментариев за виджет
            commentedWidget.data('com', +commentedWidget.data('com') + 1);

            // показать какие статьи есть на страницах
            //mPagesContent.showWidgets( $(".article, .voting", ".normalpage") ,get_current('div') );
            mPagesContent.showWidgets( get_current('page') );

            // обновить высоту блока комментариев
            // если показан опрос
            if ($('#m-question-subject:visible').length) {
                // изменить размер комментариев по размеру опроса
                var q = $('#m-question-subject').outerHeight(true) + $('.rating_results_div').outerHeight(true)  + $('#soc_icons_wrap').outerHeight(true) + $('#m-comment-show-window').outerHeight(true);
                $('#scroll_comments').height(530 - q);
            } else {
                // изменить размер комментаниев. по контенту статьи
                var m = $('#comment_block_title').outerHeight(true) + $('#soc_icons_wrap').outerHeight(true) + $('#m-comment-show-window').outerHeight(true);
                $('#scroll_comments').height(570 - m)
            }
        },
        
        'onshowenter': function(event, data) {
            account.showLogin('', function() {
                // показать сохранённую статью
                mArticle.show(data.id, function() {
                    mComments.showAddComment(data.msg, data.uid, data.cid, data.email);
                });   
            }, function() {
                // показать сохранённую статью
                mArticle.show(data.id, function() {
                    mComments.showAddComment(data.msg, data.uid, data.cid, data.email);
                }); 
            });
        }
    });
    
    
    coreNotice = function(e,data){
        switch (e) {
        case 'document ready':
            break;
            
            
        /* обработка mArticle */
            
        // статья открылась
        case 'article show':
            // закрыть Опрос
            mQuestions.hide();

            // изменить размер комментаниев. по контенту статьи
            var m = $('#comment_block_title').outerHeight(true) + $('#soc_icons_wrap').outerHeight(true) + $('#m-comment-show-window').outerHeight(true);
            $('#scroll_comments').height(570 - m);
            break;
            
        // статья скрылась
        case 'article hide':
            mPagesContent.show();
            //mPagesContent.showWidgets( $(".article, .voting", ".normalpage") ,get_current('div') );
            mPagesContent.showWidgets( get_current('page') );
            break;
            
         /*-----------------------------------------------------------------------------------------*/
        /* обработка TopPanel */
            
        // topPanel будет опущена вниз, будут показаны верхние страницы
        case 'toppanel down': 
            if (!scaled) {
                switch_to_one_page_mode();
                mPages.onePageMode();
                topPanel.onePageMode();
            }
            
            // показать нижнюю часть "Верха"
            mPages.showPage('topstart');
            
            
            // закрыть статьи, комментарии и добавление комментария
            mArticle.hide();
            mPagesContent.hide();
            mComments.hide();
            break;
            
        // верхняя панель поднимается вверх   
        case 'toppanel top':
            mPages.showPage('0');
            break;
        
        
         /*-----------------------------------------------------------------------------------------*/
        /* mPages  */
            
        // страница прокручена до низа "верха"
        case 'pages show top':
            // покачать оранжевую панель
            topPanel.bounceOrange();
            break;
            
        // страница прокручена до "журнала"
        case 'pages show magazine':
            // покачать белую панель
            topPanel.bounceWhite();
            break;
            
            
            
        /*-----------------------------------------------*/
        /* mVoting*/
        
        //требуется вход для голосования
        case 'voting need enter' :

            mPages.showPage('0');
            account.showLogin('', function() {
                // показать сохранённую статью
                mPages.showPage('topstart');
            }, function() {
                // показать сохранённую статью
                mPages.showPage('topstart');
            });
            break;
            
            
            
            
        // видео fancybox закрыто
        case 'video closed':
            
            // выключить режим Video у mPages
            mPages.isVideo = false;
            
            // перейти на Главную
            //mPages.showPage('0');
            break;
        default:
            alert('core: unknown event "'+e+'"');
        }
    };
 

    // обработка смены hash
    function HashHandler(newHash, initial) {
        if (initial) {
            
            if (mPages.topHas(newHash)) {
                topPanel.bounceOrange();
            } else {
                topPanel.bounceWhite();
            }
            
            // загрузка страницыs
            if (/\d{3}\/\w{4,5}/.test(newHash)) {
                // если страница в формате 005/left
                // показать страницу указанную в хеше
                var pageData = newHash.split('/');
                // TODO deprecated
                mPages.showPageNumber(pageData[0], pageData[1], scaled);
            } else if (/video\/(\d+)/.test(newHash)) {
                // если hash в формате video/id/userid
                // показать видео с id

                var videoId = newHash.match(/video\/(\d+)/)[1];
                // TODO хранить видео по ID
                /*var videoData = document.location.hash.match(/video\/(\d+)\/(\d+)/)
                 account.noAuthLogin(videoData[2], function() {
                 Video.showIfLogin('http://www.youtube.com/v/BrwUFBAJXOs', 'Мастер, часть1', videoData[1]);
                 });*/
                
                switch_to_one_page_mode();
                mPages.onePageMode();
                topPanel.onePageMode();
                //mPages.showPage('0');
                mPages.showPage(newHash);
                //Video.show(videoId);

            } else if (/\d{3}/.test(newHash) || /\d{1,3}-\d{2,3}/.test(newHash)) {
                // если страница в формате 005 или 004-005
                // показать страницу указанную в хеше
                // если в формате 001 - перевести в режим одной страницы
                // если в формате 000-001 - перевести в режим двух страниц

                mPages.current = newHash;
                if (/\d{1,3}-\d{2,3}/.test(newHash)) {
                    // хак, чтобы переход к 2м страницам выполнился
                    scaled = true;

                    switch_to_two_page_mode();

                    mPages.twoPageMode();
                    topPanel.twoPageMode();
                    //page_001_load(false);
                } else {
                    //page_001_load(true);
                    switch_to_one_page_mode();
                    mPages.onePageMode();
                    topPanel.onePageMode();
                }

                // mPages.showPage(newHash);
            } else if (newHash.match(/video/)) {
                // если hash в формате старого видео #video_1@from_70
                switch_to_one_page_mode();
                mPages.onePageMode();
                topPanel.onePageMode();

                var splits = newHash.split('@');
                if (splits[1].match(/from/)) {
                    var _userid = splits[1].split('from_').join('');

                    //account.noAuthLogin(_userid, function() {
                    Video.show(1787184);
                    //});
                }
            } else  if (/buy/.test(newHash)) {
                // перейти к странице "купить"
                //if (start_scale) {
                switch_to_one_page_mode();
                mPages.onePageMode();
                topPanel.onePageMode();
                //}
                mPages.showPage('buy');
            } else if (/community\/\d{1,4}/.test(newHash))  {
                mCommunity.show(+newHash.split('/')[1]);
                mOverlay.show();

                switch_to_one_page_mode();
                mPages.onePageMode();
                topPanel.onePageMode();
            } else if (mPages.topHas(newHash)) {
                switch_to_one_page_mode();
                mPages.onePageMode();
                topPanel.onePageMode();
                //mVoting.show();
                mPages.showPage(newHash);
               
            } else {
                // on init
                /* global start_scale */
                //if (start_scale) {
                switch_to_one_page_mode();
                mPages.onePageMode();
                topPanel.onePageMode();
                //}

                // показать главную
                mPages.showPage('0');
            }
        } else {
            if (/\d{3}/.test(newHash) || /\d{1,3}-\d{2,3}/.test(newHash) || mPages.topHas(newHash) || /video\/(\d+)/.test(newHash)) {
                // если страница в формате 005 или 004-005
                if (mPages.current !== newHash) {
                    mPages.showPage(newHash);

                }
                mPreview.lasyLoad();
            }
            // показать какие статьи есть на страницах
            mPagesContent.showWidgets( get_current('page') );
        }
    }


    // инициализация обыработки смены Hash
    Hash.init(HashHandler);

   
    coreNotice('document ready');
});          
