
var pageInit = {
    passwordReset: function(){
        var page_options = arguments[0];
        var _form_password_reset = $('#password_reset_form'),
        validator = _form_password_reset.validate(formActions.passwordResetForm);
        _form_password_reset.submitAjaxIndikator();
        $('#password_reset_form_password', _form_password_reset).passStrengthener();
        $('a[href="#form_reset"]',_form_password_reset).bind('click',function(event){
            event.preventDefault();
            validator.resetForm();
            $('.passStrengthener').remove();
        });

    },
    restrictionPasswordConfirmation: function(){
        var page_options = arguments[0];
        var _form_password_rc = $('#password_rc_form'),
        validator = _form_password_rc.validate(formActions.restrictionPasswordConfirmationForm);
        _form_password_rc.submitAjaxIndikator();
        $('a[href="#form_reset"]',_form_password_rc).bind('click',function(event){
            event.preventDefault();
            validator.resetForm();
        });

    },
    passwordRecovery: function(){
        var page_options = arguments[0];
        var _form_password_recovery = $('#password_recovery_form'),
        validator = _form_password_recovery.validate(formActions.passwordRecoveryForm);
        _form_password_recovery.submitAjaxIndikator();
        $('a[href="#form_reset"]',_form_password_recovery).bind('click',function(event){
            event.preventDefault();
            validator.resetForm();
        });
    /*$('a[href="#captcha_reload"]').bind('click',function(event){
            event.preventDefault();
            alert('captcha_reload')
        });*/
    },
    confirmEmail: function(){
        var page_options = arguments[0];
        var _form_password_recovery = $('#confirm_email_form'),
        validator = _form_password_recovery.validate(formActions.confirmEmailForm);
        _form_password_recovery.submitAjaxIndikator();
        $('a[href="#form_reset"]',_form_password_recovery).bind('click',function(event){
            event.preventDefault();
            validator.resetForm();
        });
    /*$('a[href="#captcha_reload"]').bind('click',function(event){
            event.preventDefault();
            alert('captcha_reload')
        });*/
    },
    login: function() {

        var page_options = arguments[0];
        if (page_options.showError) {
            var message = i18n.m357;
            $.ajaxAlert({
                title: '',
                text: message,
                styleClass: 'error',
                buttonClose: true,
                speedClose: 5000
            });
        }

        var _form_login = $('#login_form'),
        validator = _form_login.validate(formActions.loginForm);
        _form_login.submitAjaxIndikator();
        $('a[href="#form_reset"]',_form_login).bind('click',function(event){
            event.preventDefault();
            validator.resetForm();
        });
        var sbmsoccon = $('#sbmsoccon');
        if(sbmsoccon.attr('id')){
            var social_login_menu = $('> div > ul', sbmsoccon).clone(true).appendTo('#social_login_menu');

            $('>li>a',social_login_menu).one('mouseover',function(){
                sbmsoccon.trigger('mouseover');
            }).each(function(){
                var _this = $(this),
                class_name = _this.attr('class');
                _this.removeClass(class_name).addClass('iconServB iconServB-' + class_name);
            });
        }
    },
    join: function(){
        var page_options = arguments[0];

        var m_current = 0;

        if(page_options.tabmjoin == null)
        {
            store.get('tabmjoin', function(ok, val) {
                m_current = val || 0;
            });
        }
        else
        {
            m_current = page_options.tabmjoin;
        }
        
        var _form_free = $('#join_form_free'),
        _form_plus = $('#join_form_plus'),
        _form_pro = $('#join_form_pro'),
        validator_free = _form_free.validate(formActions.joinForm),
        validator_plus = _form_plus.validate(formActions.joinForm),
        validator_pro = _form_pro.validate(formActions.joinForm);

        $('#join_form_free_password', _form_free).passStrengthener({
            userid: '#join_form_free_login'
        });
        $('a[href="#form_reset"]',_form_free).bind('click',function(event){
            event.preventDefault();
            validator_free.resetForm();
            $('.passStrengthener').remove();
        });
        $('#join_form_plus_password', _form_plus).passStrengthener({
            userid: '#join_form_plus_login'
        });
        $('a[href="#form_reset"]',_form_plus).bind('click',function(event){
            event.preventDefault();
            validator_plus.resetForm();
            $('.passStrengthener').remove();
        });
        $('#join_form_pro_password', _form_pro).passStrengthener({
            userid: '#join_form_pro_login'
        });
        $('a[href="#form_reset"]',_form_pro).bind('click',function(event){
            event.preventDefault();
            validator_pro.resetForm();
            $('.passStrengthener').remove();
        });



        function statesChecker(el)
        {
            var frm = global.formAction;
            // US
            if($(el).val() == 228)
            {
                $('#join_form_' + frm + '_state_fieldset').show();
                $('#join_form_' + frm + '_states_us').show();
                $('#join_form_' + frm + '_states_ca').hide();
            }
            // CA
            else if($(el).val() == 39)
            {
                $('#join_form_' + frm + '_states_ca').show();
                $('#join_form_' + frm + '_state_fieldset').show();
                $('#join_form_' + frm + '_states_us').hide();
            }
            // another country
            else
            {
                $('#join_form_' + frm + '_state_fieldset').hide();
            }
        }
        

        $('#join_form_pro_country').bind("change", function(e){
            statesChecker(this)
        });
        $('#join_form_plus_country').bind("change", function(e){
            statesChecker(this)
        });

        global.formAction = (m_current == '2' ? 'pro' : (m_current == '1' ? 'plus' : 'free' ));
        country = $('#join_form_' + global.formAction + '_country');
        statesChecker(country);



        $('#tabmjoin').tabsMenu({
            current:m_current,
            store: user.uistore,
            action: function(){
                $('#charging').trigger('position',arguments[2]);
                validator_free.resetForm();
                validator_plus.resetForm();
                validator_pro.resetForm();
                $('.passStrengthener').remove();

                global.formAction = (arguments[2] == '2'? 'pro' : (arguments[2] == '1' ? 'plus' : 'free' ));

                // switch states
                country = $('#join_form_' + global.formAction + '_country');
                statesChecker(country);
            }
        }).lastLIWidthCorrect();

        /*$('a[href="#captcha_reload"]').bind('click',function(event){
            event.preventDefault();
            alert('captcha_reload')
        });*/


        $('#charging').charging({
            items: [
            {
                'label':i18n.m246,
                'width':'20%',
                'href':'#0'
            },

            {
                'label':i18n.m247,
                'width':'49%',
                'href':'#1'
            },

            {
                'label':i18n.m248,
                'width':'31%',
                'href':'#2'
            }
            ],
            current: m_current,
            action: function(){
                $('#tabmjoin>li').eq(arguments[2]).find('a').trigger('click');
            }
        })
        $('.collapseBoxes').collapceMenu({
            toggleButton:true
        });
        $('.buttonPremiumServicesChart').colorbox({
            width:'80%',
            inline:true,
            href:'#premium_services_chart'
        });
    },
    unsubscribe: function() {
        var _form_unsubscribe = $('#unsubscribe_form'),
        unsubscribe_validator = _form_unsubscribe.validate(formActions.unsubscribeForm);

        _form_unsubscribe.submitAjaxIndikator();
        $('a[href="#form_reset"]',_form_unsubscribe).bind('click',function(event){
            event.preventDefault();
            unsubscribe_validator.resetForm();
        });
    },
    videosBrowse: function(){
        var page_options = arguments[0];
        page_options.videosList.view_id = 'view-vfl';

        var flashvars = {
            parameters: page_options.playerData.videoAsJson,
            link: 'videos'
        };

        swfobject.embedSWF("/design/flash/accordion_banner.swf", "promo_box_player", "980", "325", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams);

        page_options.videosList.filters = true;
        page_options.videosList.filtersScroll = {
            items:{
                'filter-languages':{
                    width:140,
                    height:250
                }
            }
        }
        var videos_box = $('#videos_box');
        blockInit.videosFullList(videos_box, page_options.videosList);
        videos_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu',videos_box).clickMenu({
            current: global.search_status ? false : page_options.videosList.currentSort || 0,
            action:function(){
                actions.selection(videos_box, arguments, 'videosFullList', page_options.videosList);
            }
        });
    },
    musicBrowse: function(){
        var page_options = arguments[0];
        page_options.musicList.view_id = 'view-mfl';

        var flashvars = {
            parameters: page_options.playerData.videoAsJson
        };

        swfobject.embedSWF("/design/flash/accordion_banner.swf", "promo_box_player", "980", "325", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams);

        page_options.musicList.filters = true;
        page_options.musicList.filtersScroll = {
            items:{
                'filter-languages':{
                    width:140,
                    height:250
                }
            }
        }
        var music_box = $('#music_box');
        blockInit.videosFullList(music_box, page_options.musicList);
        music_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });
        $('.sortingMenu',music_box).clickMenu({
            current: global.search_status ? false : page_options.musicList.currentSort || 0,
            action:function(){
                actions.selection(music_box, arguments, 'videosFullList', page_options.musicList);
            }
        });
    },
    blogsPostsBrowse: function(){
        var page_options = arguments[0];
        
        $('#content_menu').lastLIWidthCorrect();
        
        page_options.blogsPostsList.filters = true;
        page_options.blogsPostsList.filtersScroll = {
            items:{
                'filter-archives':{
                    width:100,
                    height:160
                }
            }
        }
        var blogs_posts_box = $('#blogs_posts_box');
        blockInit.blogsPostsList(blogs_posts_box, page_options.blogsPostsList);
        blogs_posts_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });
    },
    blogPostsBrowse: function(){
        var page_options = arguments[0];
        var left_panel_group = {};

        global.blog_about = $('#blog_about');
        global.blog_title_box = $('.blogTitle',global.blog_about).detach();
        global.blog_about_box = $('.blogAbout',global.blog_about).detach();
        global.blog_about_description = $('.blogDescription',global.blog_about).detach();

        global.blog_about.remove();
        left_panel_group.aboutBlogPanel = $.slidePanel({
            title: i18n.m99,
            width: 350,
            styleClass: 'verticalText panelName-aboutBlog',
            topBar: global.blog_title_box.add(global.blog_about_box),
            bottomBar: '<div id="toolbox"></div>&nbsp;',
            content: global.blog_about_description,
            jScrollPane: true
        });
        if(typeof addthis == 'object'){
            addthis.init();
            $('#toolbox').addThisBox({
                info:page_options.shareInfo
            });
        }
        $('.fbLikeButton').fbLikeButton({
            title:page_options.shareInfo.title
        });
        if(typeof page_options.donate == 'object' && page_options.donate.email != ''){
            $('#paypal_button').paypalButton({
                user: page_options.donate.user,
                email: page_options.donate.email
            });
        }
        $('a.userThumb',global.blog_about_box).thumbLoadControl();
        
        page_options.blogPostsList.filters = true;
        page_options.blogPostsList.filtersScroll = {
            items:{
                'filter-archives':{
                    width:100,
                    height:160
                }
            }
        }
        var blog_posts_box = $('#blog_posts_box');
        blockInit.blogsPostsList(blog_posts_box, page_options.blogPostsList);
        blog_posts_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });
        $(document.body).bind('recalc_panels',function(){
            $.lineBoxPos({
                elements: left_panel_group,
                selector: '.slidePanelTitle',
                dimension: 'width',
                start: 115,
                separator: ie(7) ? 5 : 0,
                msieFilter: true
            });
        });
        $(document.body).trigger('recalc_panels');
    },
    blogsBrowse: function(){
        var page_options = arguments[0];
        $('#content_menu').lastLIWidthCorrect();
        var blogs_box = $('#blogs_box');

        blockInit.blogsList(blogs_box, page_options.blogsList);
        blogs_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });
    },
    blogPost: function(){
        var page_options = arguments[0];
        var left_panel_group = {};

        global.blog_about = $('#blog_about');
        global.blog_title_box = $('.blogTitle',global.blog_about).detach();
        global.blog_about_box = $('.blogAbout',global.blog_about).detach();
        global.blog_about_description = $('.blogDescription',global.blog_about).detach();
        global.blog_about.remove();
        
        left_panel_group.aboutBlogPanel = $.slidePanel({
            title: i18n.m99,
            width: 350,
            styleClass: 'verticalText panelName-aboutBlog',
            topBar: global.blog_title_box.add(global.blog_about_box),
            bottomBar: '<div id="toolbox_blog"></div>&nbsp;',
            content: global.blog_about_description,
            jScrollPane: true
        });
        
        global.commentsBox = $('#comments');
        if(ie(6)){
            global.commentsBox.hide();
        }
        left_panel_group.commentsPanel = $.slidePanel({
            /*orientation:  'right',*/
            title: i18n.m102.supplant({
                number:page_options.commentsList.count
            }),
            titleChange: true,
            width: 650,
            styleClass: 'verticalText panelName-comments ovfBottomBar',
            topBar: '<h3>' + i18n.m101 + '</h3><div class="slideForm"><a href="#" class="buttonComment">&#160;</a></div>',
            bottomBar: '&nbsp;',
            content: global.commentsBox,
            jScrollPane: true
        });

        blockInit.commentsList(left_panel_group.commentsPanel, page_options.commentsList);
        left_panel_group.commentsPanel.ajaxIndikator({
            orientation:'center',
            title:i18n.m56
        });

        global.button_comment = $('.buttonComment', left_panel_group.commentsPanel);

        global.button_comment.toggleButton(buttons.commentsBlock.displayForm);

        
        
        if(typeof addthis == 'object'){
            addthis.init();
            $('#toolbox_blog').addThisBox({
                info:page_options.blogShareInfo
            });
            $('.toolboxPost').addThisBox({
                info:page_options.postShareInfo
            });
        }
        $('.fbLikeButton').fbLikeButton({
            title:page_options.postShareInfo.title
        });
        if(typeof page_options.donate == 'object' && page_options.donate.email != ''){
            $('#paypal_button').paypalButton({
                user: page_options.donate.user,
                email: page_options.donate.email
            });
        }
        
        $(document.body).bind('recalc_panels',function(){
            $.lineBoxPos({
                elements: left_panel_group,
                selector: '.slidePanelTitle',
                dimension: 'width',
                start: 115,
                separator: ie(7) ? 5 : 0,
                msieFilter: true
            });
        });
        $(document.body).trigger('recalc_panels');
        
    },
    channelReviewDetail: function() {
        var page_options = arguments[0];
        var left_panel_group = {};

        $('.ratingValue', page_options[0]).initStars();

        global.channel_about = $('#channel_about');
        global.channel_about_channel_box = $('.channelAbout',global.channel_about).detach();
        //global.video_about_video_box = $('.channelAbout',global.channel_about).detach();
        global.channel_about_addinfo_box = $('.addInfo',global.channel_about).detach();
        global.channel_about.remove();

        left_panel_group.aboutChannelPanel = $.slidePanel({
            title: i18n.m99,
            width: 350,
            styleClass: 'verticalText panelName-aboutVideo',
            topBar: $('<h3>' + i18n.m116 + '</h3>').add(global.channel_about_channel_box),
            bottomBar: global.channel_about_addinfo_box,
            content: global.channel_about_channel_box,
            jScrollPane: true
        });
        
        global.commentsBox = $('#comments');
        if(ie(6)){
            global.commentsBox.hide();
        }

        left_panel_group.commentsPanel = $.slidePanel({
            title: i18n.m102.supplant({
                number:page_options.commentsList.count
            }),
            titleChange: true,
            width: 650,
            styleClass: 'verticalText panelName-comments ovfBottomBar',
            topBar: '<h3>' + i18n.m101 + '</h3><div class="slideForm"><a href="#" class="buttonComment">&#160;</a></div>',
            bottomBar: '&nbsp;',
            content: global.commentsBox,
            jScrollPane: true
        });

        blockInit.commentsList(left_panel_group.commentsPanel, page_options.commentsList);
        left_panel_group.commentsPanel.ajaxIndikator({
            orientation:'center',
            title:i18n.m56
        });

        global.button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        global.button_comment.toggleButton(buttons.commentsBlock.displayForm);


        if(typeof addthis == 'object'){
            addthis.init();
            $('#toolbox').addThisBox({
                info:page_options.videoShareInfo
            });
            $('.toolboxReviewVideo').addThisBox({
                info:page_options.reviewShareInfo
            });
        }

        $('.fbLikeButton').fbLikeButton({
            title:page_options.channelShareInfo.title,
            width: 120
        });
        
        if(typeof page_options.donate == 'object' && page_options.donate.email != ''){
            $('#paypal_button').paypalButton({
                user: page_options.donate.user,
                email: page_options.donate.email
            });
        }
      
        $(document.body).bind('recalc_panels',function(){
            $.lineBoxPos({
                elements: left_panel_group,
                selector: '.slidePanelTitle',
                dimension: 'width',
                start: 115,
                separator: ie(7) ? 5 : 0,
                msieFilter: true
            });
        });
        $('a.channelThumb', global.channel_about_channel_box).thumbLoadControl();
        $(document.body).trigger('recalc_panels');
        
        global.button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        
        $('.panelCenter .info .comments .label').addClass('actionTextLink').wrap('<a href="#"></a>').bind('click',function(event){
            event.preventDefault();
            left_panel_group.commentsPanel.trigger('toggle');
            if(global.button_comment.attr('href') != '#close'){
                global.button_comment.trigger('click');
            }
        })

    },
    videoReviewDetail: function() {
        var page_options = arguments[0];
        var left_panel_group = {};

        $('.ratingValue', page_options[0]).initStars();

        global.video_about = $('#video_about');
        global.video_about_channel_box = $('.channelAbout',global.video_about).detach();
        global.video_about_video_box = $('.videoAbout',global.video_about).detach();
        global.video_about_addinfo_box = $('.addInfo',global.video_about).detach();
        global.video_about.remove();

        left_panel_group.aboutVideoPanel = $.slidePanel({
            title: i18n.m99,
            width: 350,
            styleClass: 'verticalText panelName-aboutVideo',
            topBar: $('<h3>' + i18n.m100 + '</h3>').add(global.video_about_channel_box),
            bottomBar: global.video_about_addinfo_box,
            content: global.video_about_video_box,
            jScrollPane: true
        });
        global.stillsBox = $('#stills');
        $('a.pictureThumb[rel="user-pictures"]',global.stillsBox).thumbLoadControl().colorbox({
            slideshow:true,
            slideshowAuto:false,
            slideshowSpeed: 2000,
            current: i18n.m105,
            slideshowStart: i18n.m106,
            slideshowStop: i18n.m107
        });

        left_panel_group.stillsPanel = $.slidePanel({
            title: i18n.m168,
            width: 190,
            styleClass: 'verticalText panelName-stills',
            topBar: '<h3>' + i18n.m168 + '</h3>',
            bottomBar: '&nbsp;',
            content: global.stillsBox,
            jScrollPane: true
        });

        global.commentsBox = $('#comments');
        if(ie(6)){
            global.commentsBox.hide();
            global.stillsBox.hide();
        }

        left_panel_group.commentsPanel = $.slidePanel({
            title: i18n.m102.supplant({
                number:page_options.commentsList.count
            }),
            titleChange: true,
            width: 650,
            styleClass: 'verticalText panelName-comments ovfBottomBar',
            topBar: '<h3>' + i18n.m101 + '</h3><div class="slideForm"><a href="#" class="buttonComment">&#160;</a></div>',
            bottomBar: '&nbsp;',
            content: global.commentsBox,
            jScrollPane: true
        });

        blockInit.commentsList(left_panel_group.commentsPanel, page_options.commentsList);
        left_panel_group.commentsPanel.ajaxIndikator({
            orientation:'center',
            title:i18n.m56
        });

        global.button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        global.button_comment.toggleButton(buttons.commentsBlock.displayForm);

        if(typeof addthis == 'object'){
            addthis.init();
            $('#toolbox').addThisBox({
                info:page_options.videoShareInfo
            });
            $('.toolboxReviewVideo').addThisBox({
                info:page_options.reviewShareInfo
            });
        }

        $('.fbLikeButton').fbLikeButton({
            title:page_options.videoShareInfo.title,
            width: 120
        });
        if(typeof page_options.donate == 'object' && page_options.donate.email != ''){
            $('#paypal_button').paypalButton({
                user: page_options.donate.user,
                email: page_options.donate.email
            });
        }

        $(document.body).bind('recalc_panels',function(){
            $.lineBoxPos({
                elements: left_panel_group,
                selector: '.slidePanelTitle',
                dimension: 'width',
                start: 115,
                separator: ie(7) ? 5 : 0,
                msieFilter: true
            });
        });
        $('a.channelThumb', global.video_about_channel_box).thumbLoadControl();
        $(document.body).trigger('recalc_panels');
        
        
         global.button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        
        $('.panelCenter .info .comments .label').addClass('actionTextLink').wrap('<a href="#"></a>').bind('click',function(event){
            event.preventDefault();
            left_panel_group.commentsPanel.trigger('toggle');
            if(global.button_comment.attr('href') != '#close'){
                global.button_comment.trigger('click');
            }
        })
        
    },
    reviewsChannelBrowse: function(){
        var page_options = arguments[0],
        reviews_channel_box = $('#reviews_channel_box');

        $('#content_menu').lastLIWidthCorrect();

        blockInit.reviewsChannelList(reviews_channel_box, page_options.reviewsChannelList);
        reviews_channel_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });
        $('#title_info li').first().html(i18n.m74);

        var flashvars = {
            parameters: page_options.playerData.bannerAsJson
        };

        swfobject.embedSWF("/design/flash/review_banner.swf", "promo_box_banner", "980", "280", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams);
    },
    reviewsVideoBrowse: function(){
        var page_options = arguments[0],
        reviews_video_box = $('#reviews_video_box');

        $('#content_menu').lastLIWidthCorrect();

        blockInit.reviewsVideoList(reviews_video_box, page_options.reviewsVideoList);
        reviews_video_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        var flashvars = {
            parameters: page_options.playerData.bannerAsJson
        };

        swfobject.embedSWF("/design/flash/review_banner.swf", "promo_box_banner", "980", "280", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams);
    },
    usersBrowse: function(){
        var page_options = arguments[0];

        var flashvars = {
            parameters: page_options.playerData.bannerDataAsJson,
            link: 'users'
        };

        swfobject.embedSWF("/design/flash/accordion_banner.swf", "promo_box_player", "980", "325", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams);

        page_options.usersList.filters = true;
        page_options.usersList.filtersScroll = {
            items:{
                'filter-country':{
                    width:170,
                    height:250
                }
            }
        }
        
        var users_box = $('#users_box');
        blockInit.usersList(users_box, page_options.usersList);
        users_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu',users_box).clickMenu({
            current: global.search_status ? false : 0,
            action:function(){
                actions.selection(users_box, arguments, 'usersList', page_options.usersList); 
            }
        });
    },
    userDetails: function(){
        var page_options = arguments[0];

        var left_panel_group = {};

        global.commentsBox = $('#comments');
        if(ie(6)){
            global.commentsBox.hide();
        }
        left_panel_group.commentsPanel = $.slidePanel({
            orientation:  'right',
            title: i18n.m102.supplant({
                number:page_options.commentsList.count
            }),
            titleChange: true,
            width: 650,
            styleClass: 'verticalText panelName-comments ovfBottomBar',
            topBar: '<h3>' + i18n.m101 + '</h3><div class="slideForm"><a href="#" class="buttonComment">&#160;</a></div>',
            bottomBar: '&nbsp;',
            content: global.commentsBox,
            jScrollPane: true
        });

        blockInit.commentsList(left_panel_group.commentsPanel,page_options.commentsList);
        left_panel_group.commentsPanel.ajaxIndikator({
            orientation:'center',
            title:i18n.m56
        });

        global.button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        
        var comments_add_par = buttons.commentsBlock.displayForm;
        if(page_options.userProfile.viewerBlockState == 1){
            comments_add_par.lockAction = function(){
                buttons.mustUnBlock(arguments[0]);
                left_panel_group.commentsPanel.trigger('hide');
                return;
            }
        }
        global.button_comment.toggleButton(comments_add_par);
        
        var user_images = $('#user_images');
        
        left_panel_group.userImagesPanel = $.slidePanel({
            orientation:  'right',
            title: i18n.m168 + ' ('+page_options.userPhotosList.count+')',
            width: 190,
            styleClass: 'verticalText panelName-userImages ovfBottomBar',
            topBar: '<h3>' + i18n.m168 + '</h3>',
            bottomBar: '&nbsp;',
            content: user_images,
            jScrollPane: true
        });

        
        blockInit.userPhotosList(left_panel_group.userImagesPanel, page_options.userPhotosList);
        left_panel_group.userImagesPanel.ajaxIndikator({
            orientation:'center',
            title:i18n.m98
        });
        
        $(document.body).bind('recalc_panels',function(){
            $.lineBoxPos({
                elements: left_panel_group,
                selector: '.slidePanelTitle',
                dimension: 'width',
                start: 60,
                separator: ie(8) ? (ie(7) ? 5 : 30) : 0,
                msieFilter: true
            });
        }).trigger('recalc_panels');


        var sendMessageForm = $(templates.sendMessageForm({
            action: '',
            styleClass: 'formSendMessages',
            buttonTitle: i18n.m178
        }));

        var validator = sendMessageForm.validate(formActions.messageForm);
        var textarea_message = sendMessageForm.find('.textareaMessage');
        
        textarea_message.remainingCharacterCount({
            characterCount:config.messageCharacterCount
        });
        sendMessageForm.find('a[href="#form_reset"]').bind('click',function(event){
            event.preventDefault();
            validator.resetForm();
            textarea_message.trigger('recalcCharacterCount');
        });

        global.sendMessagePanel = $.slidePanel({
            title: i18n.m178,
            titleHidden: true,
            styleClass: 'panelName-sendMessage formGray panelBgGray',
            content: sendMessageForm,
            orientation:'top',
            position: 'right',
            offset: $('#header_top').offset().left,
            height: 255,
            width: 390,
            topBar: '<h3>' + i18n.m178 + '</h3>'
        });
        global.sendMessagePanel.find('.slidePanelContent').css('overflow','hidden');
        sendMessageForm.submitAjaxIndikator();

        var _user_descr = $('#user_about_description .description');
        if(_user_descr.height() > 300){
            _user_descr.height(300).jScrollPane();
            _user_descr.parent().bind('mousewheel',function(event){
                event.stopPropagation();
                return false;
            });
        }
        
        

        global.user_about = $('#user_about');
        $('a.userThumb',global.user_about).thumbLoadControl();

        global.header_promo_box = $('#header_promo_box');
        $('.buttonSendMessage',global.header_promo_box).bind('click',function(event){
            event.preventDefault();
            if(page_options.userProfile.viewerBlockState == 1){
                buttons.mustUnBlock((event));
                return;
            }
            if(page_options.userProfile.isFriend == 0){
                $.ajaxAlert({
                    title: '',
                    text:i18n.m495,
                    styleClass: 'message',
                    buttonClose: true,
                    speedClose: 3000
                });
                return;
            }
            if(mustLogin('user-send-message')){
                buttons.mustLogin(event);
                return;
            }
            global.sendMessagePanel.trigger('toggle');
        });
        $('.buttonPhotos',global.header_promo_box).bind('click',function(event){
            event.preventDefault();
            left_panel_group.userImagesPanel.trigger('toggle');
        });
        $('.buttonAddComment',global.header_promo_box).bind('click',function(event){
            event.preventDefault();
            left_panel_group.commentsPanel.trigger('toggle');
            if(global.button_comment.attr('href') != '#close'){
                global.button_comment.trigger('click');
            }
        });
        
        //TODO: allow user remove as friend from blocked
        $('.buttonAddAsFriend',global.header_promo_box).bind('click', 
            page_options.userProfile.viewerBlockState == 1 ? buttons.mustUnBlock : mustConfirm('user-add-as-friend') ? buttons.mustLogin : actions.addAsFriend
        );
        $('.buttonBlockUser',global.header_promo_box).bind('click', actions.blockUser);

        /* Stream LIST with pager */
        var activity_box = $('#activity_box');

        blockInit.activityList(activity_box, page_options.activityList);
        activity_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu',activity_box).clickMenu({
            current:0,
            action:function(){
                actions.selection(activity_box, arguments, 'activityList', page_options.activityList); 
            }
        });
        
        /* CHANNEL LIST with pager */
        var channels_box = $('#channels_box');

        blockInit.channelsList(channels_box, page_options.channelsList);
        channels_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu',channels_box).clickMenu({
            current:0,
            action:function(){
                actions.selection(channels_box, arguments, 'channelsList', page_options.channelsList); 
            }
        });


        var users_box = $('#users_box');
        page_options.usersList.scrollTo = $('#users_doc');
        blockInit.usersList(users_box, page_options.usersList);
        users_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });


        var videos_box = $('#videos_box');
        blockInit.videosList(videos_box, page_options.videosList);
        videos_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu',videos_box).clickMenu({
            current:0,
            action:function(){
                actions.selection(videos_box, arguments, 'videosList', page_options.videosList);
            }
        });

        $(window).resize(function(){
            global.sendMessagePanel.css('right',$('#header_top').offset().left);
        });
        
        var m_current = 0;
        store.get('tabmuprf' ,function(ok, val) {
            m_current = val || 0;
        });
        $('#tabmuprf').tabsMenu({current:m_current, store: user.uistore, speed:0}).lastLIWidthCorrect();
        
        if(typeof addthis == 'object'){
            addthis.init();
            $('#toolbox').addThisBox({
                info:page_options.shareInfo
            });
        }
        $('.fbLikeButton').fbLikeButton({
            title:page_options.shareInfo.title,
            width: 120,
            image: page_options.shareInfo.image
        });
        if(typeof page_options.donate == 'object' && page_options.donate.email != ''){
            $('#paypal_button').paypalButton({
                user: page_options.donate.user,
                email: page_options.donate.email
            });
        }
        /*filmfestifal list with pager*/
        var ff_box = $('#film_festivals_box');
        blockInit.filmfestivalIndexList(ff_box, page_options.filmfestivalIndexList);
        ff_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });
    },
    channelDetails: function(){
        var page_options = arguments[0];

        // player include
        var flashvars = {
            parameters: page_options.playerData.videoAsJson,
            topbar: page_options.playerData.topbar,
            playlist: true,
            menu: false,
            related: false,
            controlbar: 'over',
            acudeo: true,
            autostart: false,
            repeat: 'list',
            isbacklight: true
        };

        var attributes = {
            name: 'video_player_content'
        };

        swfobject.embedSWF("/design/flash/player.swf", "video_player_content", "914", "360", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams, attributes);

        $(window).load(function(){
            $('#video_player_content').live('mousewheel',function(event){
                var delta = 0;
                if(event.wheelDelta) delta = -event.wheelDelta/120;
                if(event.detail) delta = event.detail/3;
                var player = swfobject.getObjectById('video_player_content');
                player.sendEvent('mouse_wheel',{delta: delta});
                return false;
            }).boundsBacklight({
                hideAction: function(){
                    var player = swfobject.getObjectById('video_player_content');
                    player.sendEvent('backlight', true);
                }
            });
        });

        // $('#video_player_content').ready(function(){
            // $('#video_player_content').live('mousewheel',function(event){
                // var delta = 0;
                // if(event.wheelDelta) delta = -event.wheelDelta/120;
                // if(event.detail) delta = event.detail/3;
                // var player = swfobject.getObjectById('video_player_content');
                // player.sendEvent('mouse_wheel',{delta: delta});
                // return false;
            // }).boundsBacklight({
                // hideAction: function(){
                    // var player = swfobject.getObjectById('video_player_content');
                    // player.sendEvent('backlight', true);
                // }
            // });
        // });

        $('#title_info .ratingValue').initStars();

        var left_panel_group = {},
        right_panel_group = {};
            
        global.channel_about = $('#channel_about');
        global.channel_about_box = $('.channelAbout',global.channel_about).detach();
        global.channel_about_description = $('.channelDescription',global.channel_about).detach();
        global.channel_about_addinfo_box = $('.addInfo',global.channel_about).detach();
        global.channel_about.remove();
        
        
        left_panel_group.aboutChannelPanel = $.slidePanel({
            title: i18n.m99,
            width: 350,
            styleClass: 'verticalText panelName-aboutChannel',
            topBar: $('<h3>' + i18n.m116 + '</h3>').add(global.channel_about_box),
            bottomBar: global.channel_about_addinfo_box,
            content: global.channel_about_description,
            jScrollPane: true
        });
       
        $('a.channelThumb',global.channel_about_box).thumbLoadControl();
        global.commentsBox = $('#comments');
        if(ie(6)){
            global.commentsBox.hide();
        } 
        left_panel_group.commentsPanel = $.slidePanel({
            title: i18n.m102.supplant({
                number:page_options.commentsList.count
            }),
            titleChange: true,
            width: 650,
            styleClass: 'verticalText panelName-comments ovfBottomBar',
            topBar: '<h3>' + i18n.m101 + '</h3><div class="slideForm"><a href="#" class="buttonComment">&#160;</a></div>',
            bottomBar: '&nbsp;',
            content: global.commentsBox,
            jScrollPane: true
        });

        blockInit.commentsList(left_panel_group.commentsPanel,page_options.commentsList);
        left_panel_group.commentsPanel.ajaxIndikator({
            orientation:'center',
            title:i18n.m56
        });

        var button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        button_comment.toggleButton(buttons.commentsBlock.displayForm);

        global.addPanel = $.slidePanel({
            //title: i18n.m609,
            width: 320,
            height: 320,
            offset: 135,
            topBar: '<h3>' + i18n.m502 + '</h3>',
            styleClass: 'verticalText panelName-add',
            content: '<div id="companionBoard"></div>',
            title: false,
            orientation: 'right'
        });
       
        $(document.body).bind('recalc_panels',function(){
            $.lineBoxPos({
                elements: left_panel_group,
                selector: '.slidePanelTitle',
                dimension: 'width',
                start: 120,
                separator: ie(7) ? 5 : 0,
                msieFilter: true
            });
        });
        $(document.body).trigger('recalc_panels');

        var channels_box = $('#channels_box');

        blockInit.channelsListCarousel(channels_box, page_options.channelsList);
        channels_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu',channels_box).clickMenu({
            current:0,
            action:function(){
                actions.selection(channels_box, arguments, 'channelsListCarousel', page_options.channelsList); 
            }
        });
        if(typeof addthis == 'object'){
            addthis.init();
            $('#toolbox').addThisBox({
                info:page_options.shareInfo
            });
        }
        $('.fbLikeButton').fbLikeButton({
            title:page_options.shareInfo.title,
            width: 120,
            image: page_options.shareInfo.image
        });
        if(typeof page_options.donate == 'object' && page_options.donate.email != ''){
            $('#paypal_button').paypalButton({
                user: page_options.donate.user,
                email: page_options.donate.email
            });
        }
        
        var _subscribe_button = $('#subscribe_button');
        _subscribe_button.toggleButton({
            styleClass: 'sButton',
            state: _subscribe_button.is('.signed') ? 1 : 0,
            labelFirst: i18n.m474,
            labelSecond: i18n.m475,
            first: '#subscribe',
            second: '#unsubscribe',
            lockAction: mustLogin('channel-subscribe') ? function(){
                buttons.mustLogin(arguments[0]);
                return;
            } : mustConfirm('channel-subscribe') ? buttons.mustLogin : null,
            action: actions.channelSubscribe
        });
        
        global.button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        
        $('<a href="#" class="commentButton sButton">'+i18n.m145+'</a>').bind('click',function(event){
            event.preventDefault();
            left_panel_group.commentsPanel.trigger('toggle');
            if(global.button_comment.attr('href') != '#close'){
                global.button_comment.trigger('click');
            }
        }).insertAfter('#video_player').wrap('<div style="text-align: right;"></div>');
    },
    playlistDetails: function(){
        var page_options = arguments[0];
        // player include
        var flashvars = {
            parameters: page_options.playerData.videoAsJson,
            topbar: page_options.playerData.topbar,
            captions: false,
            playlist: true,
            menu: false,
            related: false,
            controlbar: 'over',
            timebar: true,
            autostart: false,
            repeat: 'list',
            isbacklight: true
        };

        var attributes = {
            name: 'video_player_content'
        };

        swfobject.embedSWF("/design/flash/player.swf", "video_player_content", "914", "360", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams, attributes);

        $('#video_player_content').ready(function(){
            $('#video_player_content').live('mousewheel',function(event){
                var delta = 0;
                if(event.wheelDelta) delta = -event.wheelDelta/120;
                if(event.detail) delta = event.detail/3;
                var player = swfobject.getObjectById('video_player_content');
                player.sendEvent('mouse_wheel',{delta: delta});
                return false;
            }).boundsBacklight({
                hideAction: function(){
                    var player = swfobject.getObjectById('video_player_content');
                    player.sendEvent('backlight', true);
                }
            });
        });
            
        var left_panel_group = {};
        global.playlist_about = $('#playlist_about');
        global.playlist_about_top_box = $('.playlistAboutTop',global.playlist_about).detach();
        global.playlist_about_box = $('.playlistAbout',global.playlist_about).detach();
        global.playlist_about_addinfo_box = $('.addInfo',global.playlist_about).detach();
        global.playlist_about.remove();
        
        left_panel_group.aboutVideoPanel = $.slidePanel({
            title: i18n.m99,
            width: 370,
            styleClass: 'verticalText panelName-aboutPlaylist',
            topBar: $('<h3>' + i18n.m632 + '</h3>').add(global.playlist_about_top_box),
            bottomBar: global.playlist_about_addinfo_box,
            content: global.playlist_about_box,
            jScrollPane: true
        });
        $('a.videoThumb', global.playlist_about_top_box).thumbLoadControl();
        
        global.addPanel = $.slidePanel({
            //title: i18n.m609,
            width: 320,
            height: 320,
            offset: 120,
            topBar: '<h3>' + i18n.m502 + '</h3>',
            styleClass: 'verticalText panelName-add',
            content: '<div id="companionBoard"></div>',
            title: false,
            orientation: 'right'
        });
        
        $(document.body).bind('recalc_panels',function(){
            $.lineBoxPos({
                elements: left_panel_group,
                selector: '.slidePanelTitle',
                dimension: 'width',
                start: 115,
                separator: ie(7) ? 5 : 0,
                msieFilter: true
            });
        });
        $(document.body).trigger('recalc_panels');
        
        if(typeof addthis == 'object'){
            addthis.init();
            $('#toolbox').addThisBox({
                info:page_options.shareInfo
            });
        }
        $('.fbLikeButton').fbLikeButton({
            title:page_options.shareInfo.title,
            width: 120,
            image: page_options.shareInfo.image
        });
        page_options.videosList.view_id = 'view-plvcl';
        /*page_options.videosList.play = function (event){
            event.preventDefault();
            var _this = $(this),
                video_id = _this.parents('.item').attr('id').replace(/.*_/,'');
            $('#video_player_content').ready(function(){
                var player = swfobject.getObjectById('video_player_content');
                player.sendEvent('load', '/videos/a/load/' + video_id);
                player.sendEvent('play');
                box_fx.boxScrollToTop('#video_player_content', 30);
            });
        }*/
        var videos_box = $('#videos_box');
        blockInit.videosListCarousel(videos_box,page_options.videosList);
        videos_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu', videos_box).clickMenu({
            current:0,
            action:function(){
                actions.selection(videos_box, arguments, 'videosListCarousel', page_options.videosList);
            }
        });

    },
    videoDetails: function(){
        var page_options = arguments[0];
        page_options.videosList.view_id = 'view-vcl';

        // add to cart
        if(user.role > global.user.role.viewer) {
            if (page_options.cost.full) {
                $('#video_full_cost').click(function(){
                    actions.addToCart(page_options.cost.object_id, config.shoppingTypes.full)
                });
            }
            if (page_options.cost.iphone) {
                $('#video_iphone_cost').click(function(){
                    actions.addToCart(page_options.cost.object_id, config.shoppingTypes.iphone)
                });
            }
        }else{
            if (page_options.cost.full) {
                $('#video_full_cost').click(function(event){
                    buttons.mustLogin(event)
                });
            }
            if (page_options.cost.iphone) {
                $('#video_iphone_cost').click(function(event){
                   buttons.mustLogin(event)
                });
            }
            
        }

        var flashvars = {
            parameters: page_options.playerData.videoAsJson,
            anchor: page_options.playerData.anchor,
            ts: page_options.playerData.ts,
            menu: true,
            captions: true,
            isbacklight: true,
            acudeo: true
        };

        var attributes = {
            name: 'video_player_content'
        };

        swfobject.embedSWF("/design/flash/player.swf", "video_player_content", "920", "545", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams, attributes);
        
        $(window).load(function(){
            $('#video_player_content').boundsBacklight({
                hideAction: function(status){
                    var player = swfobject.getObjectById('video_player_content');
                    player.sendEvent('backlight',true);
                }
            });
        });

        // $('#video_player_content').ready(function(){
            // $('#video_player_content').boundsBacklight({
                // hideAction: function(status){
                    // var player = swfobject.getObjectById('video_player_content');
                    // player.sendEvent('backlight',true);
                // }
            // });
        // });

        var left_panel_group = {};
        global.stillsBox = $('#stills');
        $('a.pictureThumb[rel="user-pictures"]',global.stillsBox).thumbLoadControl().colorbox({
            slideshow:true,
            slideshowAuto:false,
            slideshowSpeed: 2000,
            current: i18n.m105,
            slideshowStart: i18n.m106,
            slideshowStop: i18n.m107
        });

        $('#title_info .ratingValue').initStars({
            action: actions.rating,
            lockAction: mustLogin('video-rating') ? buttons.mustLogin : mustConfirm('video-rating') ? buttons.mustLogin : null
        });

        global.video_about = $('#video_about');
        global.video_about_channel_box = $('.channelAbout',global.video_about).detach();
        global.video_about_video_box = $('.videoAbout',global.video_about).detach();
        global.video_about_addinfo_box = $('.addInfo',global.video_about).detach();
        global.video_about.remove();
        left_panel_group.aboutVideoPanel = $.slidePanel({
            title: i18n.m99,
            width: 350,
            styleClass: 'verticalText panelName-aboutVideo',
            topBar: $('<h3>' + i18n.m100 + '</h3>').add(global.video_about_channel_box),
            bottomBar: global.video_about_addinfo_box,
            content: global.video_about_video_box,
            jScrollPane: true
        });
        $('a.channelThumb', global.video_about_channel_box).thumbLoadControl();

        global.commentsBox = $('#comments');
        if (ie(6)) {
            global.commentsBox.hide();
        }
        left_panel_group.commentsPanel = $.slidePanel({
            title: i18n.m102.supplant({
                number:page_options.commentsList.count
            }),
            titleChange: true,
            width: 650,
            styleClass: 'verticalText panelName-comments ovfBottomBar',
            topBar: '<h3>' + i18n.m101 + '</h3><div class="slideForm"><a href="#" class="buttonComment">&#160;</a></div>',
            bottomBar: '&nbsp;',
            content: global.commentsBox,
            jScrollPane: {
                animateTo:true
            }
        });

        blockInit.commentsList(left_panel_group.commentsPanel,page_options.commentsList);
        left_panel_group.commentsPanel.ajaxIndikator({
            orientation:'center',
            title:i18n.m56
        });

        var button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        button_comment.toggleButton(buttons.commentsBlock.displayForm);

        left_panel_group.stillsPanel = $.slidePanel({
            title: i18n.m103,
            width: 190,
            styleClass: 'verticalText panelName-stills',
            topBar: '<h3>' + i18n.m103 + '</h3>',
            bottomBar: '&nbsp;',
            content: global.stillsBox,
            jScrollPane: true
        });
        
        global.addPanel = $.slidePanel({
            //title: i18n.m609,
            width: 320,
            height: 320,
            offset: 120,
            topBar: '<h3>' + i18n.m502 + '</h3>',
            styleClass: 'verticalText panelName-add',
            content: '<div id="companionBoard"></div>',
            title: false,
            orientation: 'right'
        });

        $(document.body).bind('recalc_panels',function(){
            $.lineBoxPos({
                elements: left_panel_group,
                selector: '.slidePanelTitle',
                dimension: 'width',
                start: 115,
                separator: ie(7) ? 5 : 0,
                msieFilter: true
            });
        });
        $(document.body).trigger('recalc_panels');

        var videos_box = $('#videos_box');
        blockInit.videosListCarousel(videos_box,page_options.videosList);
        videos_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu', videos_box).clickMenu({
            current:0,
            action:function(){
                actions.selection(videos_box, arguments, 'videosListCarousel', page_options.videosList);
            }
        });

        var channels_box = $('#channels_box');
        blockInit.channelsListCarousel(channels_box, page_options.channelsList);
        channels_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu',channels_box).clickMenu({
            current:0,
            action:function(){
                actions.selection(channels_box, arguments, 'channelsListCarousel', page_options.channelsList); 
            }
        });
        if(typeof addthis == 'object'){
            
            /*addthis.addEventListener('addthis.menu.share', function(evt){
                if (evt.type == 'addthis.menu.share') { 
                    console.log(evt.data.service); // service name
                    console.log(page_options.video_id);
                    //ajax
                }
            });*/
            addthis.init();
            $('#toolbox').addThisBox({
                info:page_options.shareInfo
            });
        }
        $('.fbLikeButton').fbLikeButton({
            title:page_options.shareInfo.title,
            width: 120,
            image: page_options.shareInfo.image
        });
        if(typeof page_options.donate == 'object' && page_options.donate.email != ''){
            $('#paypal_button').paypalButton({
                user: page_options.donate.user,
                email: page_options.donate.email
            });
        }
        
        global.button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        
        $('<a href="#" class="commentButton sButton">'+i18n.m145+'</a>').bind('click',function(event){
            event.preventDefault();
            left_panel_group.commentsPanel.trigger('toggle');
            if(global.button_comment.attr('href') != '#close'){
                global.button_comment.trigger('click');
            }
        }).insertAfter('#video_player').wrap('<div style="text-align: right;"></div>');
    },
    home: function(){
        var page_options = arguments[0];
        page_options.videosList.view_id = 'view-hvcl';
        var videos_box = $('#videos_box');
        blockInit.videosListCarousel(videos_box,page_options.videosList);
        videos_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu', videos_box).clickMenu({
            current:0,
            action:function(){
                actions.selection(videos_box, arguments, 'videosListCarousel', page_options.videosList);
            }
        });
        /*var news_box = $('#news_box'),
        news_list = $('.corporateNewsList', news_box),
        sorting_menu = $('.sortingMenu', news_box);
        if(news_list.innerHeight() < $('.wrapper',news_list).innerHeight()){
            news_box.bind('mousewheel', function(event){
                event.stopPropagation();
                return false;
            });    
            news_list.css('overflow','auto').jScrollPane({
                scrollbarMargin: 15
            });
        }*/
        
        var news_box = $('#news_box');
            
        $('.corporateNewsList', news_box).css('overflow','auto').jScrollPane({
            scrollbarMargin: 15
        });
        
        $('.sortingMenu', news_box).tabsMenu({current:0, speed: 0});
        
        $('.fbLikeButton').fbLikeButton({
            width: 70
        });
        $('.twitterLikeButton').twitterLikeButton({});
        
        //alert(page_options.playerData.bannerDataAsJson);
        var flashvars = {
            paging: true,
            parameters: page_options.playerData.bannerDataAsJson
        /*link: 'users'*/
        };

        swfobject.embedSWF("/design/flash/home_banner.swf", "promo_box_player", "980", "190", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams);
    },
    error: function(){
        var page_options = arguments[0];
        page_options.videosList.view_id = 'view-hvcl';
        var videos_box = $('#videos_box');
        blockInit.videosListLineCarousel(videos_box,page_options.videosList);
        videos_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu', videos_box).clickMenu({
            current:0,
            action:function(){
                actions.selection(videos_box, arguments, 'videosListLineCarousel', page_options.videosList);
            }
        });
       
    },
    channelsBrowse: function(){
        var page_options = arguments[0];

        var flashvars = {
            parameters: page_options.playerData.videoAsJson
        };

        swfobject.embedSWF("/design/flash/channel_banner.swf", "promo_box_player", "980", "325", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams);

        page_options.channelsList.filters = true;
        var channels_box = $('#channels_box');
        blockInit.channelsList(channels_box, page_options.channelsList);
        channels_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu',channels_box).clickMenu({
            current: global.search_status ? false : 0,
            action:function(){
                actions.selection(channels_box, arguments, 'channelsList', page_options.channelsList);
            }
        });
    },
    contestsBrowse: function() {
        var contests_box = $('#contests_promo_box');
        blockInit.contestsListCarousel(contests_box);
        $('#header_promo').css('position','relative').ajaxIndikator({
            orientation:'center',
            title:i18n.m98
        });
    },
    filmFestivalDetails: function() {
        var page_options = arguments[0],
        filmFestivalDetails = $('#film_festivals_detail'),
        left_panel_group = {};
        
        global.filmfestival_about = $('#filmfestivals_about');
        
        if($('#filmfestivals_about').is('div')) {
            global.filmfestival_news = $('.filmfestivalNews', global.filmfestival_about).detach();
            global.filmfestival_twitter = $('.filmfestivalTwitter', global.filmfestival_about).detach();
            global.filmfestival_rss = $('.filmfestivalRss', global.filmfestival_about).detach();
            global.filmfestival_about.remove();
            
            left_panel_group.filmfestival_news = $.slidePanel({
                title: i18n.m543,
                width: 350,
                styleClass: 'verticalText panelName-news',
                topBar: $('<h3>' + i18n.m543 + '</h3>').add(global.filmfestival_twitter),
                content: global.filmfestival_news,
                bottomBar: global.filmfestival_rss,
                jScrollPane: true
            });
        } else {
            global.filmfestival_about.remove();
        }    
         
        global.commentsBox = $('#comments');
        if(ie(6)){
            global.commentsBox.hide();
        }

        left_panel_group.commentsPanel = $.slidePanel({
            title: i18n.m102.supplant({
                number:page_options.commentsList.count
            }),
            titleChange: true,
            width: 650,
            styleClass: 'verticalText panelName-comments ovfBottomBar',
            topBar: '<h3>' + i18n.m101 + '</h3><div class="slideForm"><a href="#" class="buttonComment">&#160;</a></div>',
            bottomBar: '&nbsp;',
            content: global.commentsBox,
            jScrollPane: true
        });

        blockInit.commentsList(left_panel_group.commentsPanel, page_options.commentsList);
        left_panel_group.commentsPanel.ajaxIndikator({
            orientation:'center',
            title:i18n.m56
        });

        global.button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        global.button_comment.toggleButton(buttons.commentsBlock.displayForm);

        $(document.body).bind('recalc_panels',function(){
            $.lineBoxPos({
                elements: left_panel_group,
                selector: '.slidePanelTitle',
                dimension: 'width',
                start: 115,
                separator: ie(7) ? 5 : 0,
                msieFilter: true
            });
        });

        $(document.body).trigger('recalc_panels');
        
        /*******
        
        var _subscribe_button = $('a[href="#subscrible"]');
        _subscribe_button.toggleButton({
            styleClass: 'icon48 icon48-subscribe',
            state: _subscribe_button.is('.signed') ? 1 : 0,
            labelFirst: i18n.m474,
            labelSecond: i18n.m475,
            first: '#ff-subscrible',
            second: '#ff-unSubscrible',
            lockAction: mustLogin('filmfestival-subscribe') ? function(){
                buttons.mustLogin(arguments[0]);
                return;
            } : mustConfirm('filmfestival-subscribe') ? buttons.mustLogin : null,
            action: actions.festivalSubscribe
        });
        /******/
        
        $('#ff-subscrible').bind('click', actions.festivalSubscribe);
        $('#ff-favorite').bind('click', 
            mustConfirm('filmfestival-favorite') ? buttons.mustLogin : actions.festivalFavorite
        );
        
        
        
        var options_send_email = {
                width: 500,
                height: false,
                content: templates.ffSendEmail({
                    ff_id: page_options.filmfestivalID
                }),
                onCleanup: false,
                title: page_options.filmfestivalShareInfo.title,
                onComplete: function () {
                    var _form = $('#ff_email_form'),
                    validator  = _form.validate(formActions.ffSendEmail);
                    
                    $('a[href="#form_reset"]', _form).bind('click', function(event){
                        event.preventDefault();
                        //$('#colorbox').colorbox.resize();
                        validator.resetForm(); 
                        
                    });
                }
            };
        
        if($('#send_email').length) {
            $('#send_email').bind('click', function(event){
                event.preventDefault();
                $.modalDialog(options_send_email);
            })
        }
        
        blockInit.FestivalDetails(filmFestivalDetails ,page_options);
        
         global.button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        
        $('.buttonAddComment',global.header_promo_box).bind('click',function(event){
            event.preventDefault();
            left_panel_group.commentsPanel.trigger('toggle');
            if(global.button_comment.attr('href') != '#close'){
                global.button_comment.trigger('click');
            }
        });
    },
    filmfestivalBrowse: function () {
        var page_options = arguments[0];
        page_options.filmfestivalBrowse.filters = true;
        page_options.filmfestivalBrowse.filtersScroll = {
            items:{
                'filter-country':{
                    width:170,
                    height:250
                }
            }
        }
			
        var film_festival_box = $('#film_festivals_box');

        blockInit.filmfestivalListBrowse(film_festival_box, page_options.filmfestivalBrowse);
        film_festival_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.sortingMenu', film_festival_box).clickMenu({
            current: 0,
            action:function(){
                actions.selection(film_festival_box, arguments, 'filmfestivalListBrowse', page_options.filmfestivalBrowse);
            }
        });
    },
    filmfestivalIndex: function() {
        var page_options = arguments[0],
        film_festival_box = $('#film_festivals_box');
        
        var flashvars = {
            parameters: page_options.playerData.bannerAsJson,
            loggedIn: (user.role == global.user.role.guest ? 0 : 1),
            baseUrl: '/film-festivals'
        };

        var params = global.flashParams;
        params.scale = "showAll";

        swfobject.embedSWF("/design/flash/festivals_calendar.swf", "promo_box_banner", "980", "496", "9.0.0","/design/flash/expressInstall.swf", flashvars, params);
        
        blockInit.filmfestivalIndexList(film_festival_box, page_options);
        
        film_festival_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });

        $('.filmfestivalIndexBrowse .description a').attr('target', '_blank');
    },
    chatIndex: function() {
        
        var page_options = arguments[0],
        chat_box = $('#chats_box'),
        left_panel_chats = $('#left_panel_chats');
        
        
        /* Раскоментить при необходимости слайдера
        $('#anythingSlider', left_panel_chats).anythingSlider({
            nextBackButtons: false
        })
        */
        
        chat_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });
        
        $('.collapseBoxes').collapceMenu({
            toggleButton:true,
            header: true
        });
        $('.sortingMenu', chat_box).clickMenu({
            current: 0,
            action:function(){
                actions.selection(chat_box, arguments, 'chatIndexList', page_options.chatIndex);
            }
        });
        
        blockInit.chatIndexList(chat_box, page_options);
    },
    chatDetail: function() {
        var page_options = arguments[0],
        detail_chat_box = $('#chat_list'),
        left_panel_group = {},
        carousel = $('#chat_list_browse');
        
        $('a.userThumb', detail_chat_box).thumbLoadControl();
        $('a.videoThumb', carousel).thumbLoadControl();
        $('a.userThumb', carousel).thumbLoadControl();
        
        blockInit.chatFutureCarousel($('#chat_upcoming_box'), page_options);
        blockInit.chatArchiveCarousel($('#chat_archive_box'), page_options);
        $('#tab_chat').tabsMenu({
            current:0,
            store: false,
            speed: 0
        }).lastLIWidthCorrect();
        
        $('.voteValue', detail_chat_box).initVote({
            action: actions.chatVote
        });
        
        global.commentsBox = $('#comments');
        if (ie(6)) {
            global.commentsBox.hide();
        }
        
        left_panel_group.commentsPanel = $.slidePanel({
            title: i18n.m102.supplant({
                number: page_options.commentsList.count
            }),
            titleChange: true,
            width: 650,
            styleClass: 'verticalText panelName-comments ovfBottomBar',
            topBar: '<h3>' + i18n.m101 + '</h3><div class="slideForm"><a href="#" class="buttonComment">&#160;</a></div>',
            bottomBar: '&nbsp;',
            content: global.commentsBox,
            jScrollPane: {
                animateTo:true
            }
        });
        
        blockInit.commentsList(left_panel_group.commentsPanel, page_options.commentsList);
        left_panel_group.commentsPanel.ajaxIndikator({
            orientation:'center',
            title:i18n.m56
        });

        global.button_comment = $('.buttonComment', left_panel_group.commentsPanel);
        global.button_comment.toggleButton(buttons.commentsBlock.displayForm);

        $(document.body).bind('recalc_panels',function(){
            $.lineBoxPos({
                elements: left_panel_group,
                selector: '.slidePanelTitle',
                dimension: 'width',
                start: 115,
                separator: ie(7) ? 5 : 0,
                msieFilter: true
            });
        });

        $(document.body).trigger('recalc_panels');
        
        if(typeof addthis == 'object'){
            addthis.init();
            $('.toolboxChatdetail').addThisBox({
                info:page_options.chatShareInfo
            });
        }

        $('.fbLikeButton').fbLikeButton({
            title:page_options.chatShareInfo.title,
            width: 120
        });

        var _form_question = $('#chats-form-question'),
        validator = _form_question.validate(formActions.chatQuestionForm);
        _form_question.submitAjaxIndikator();
        
        $('#askQuestionButton').bind('click', function(event){
            if(user.role == global.user.role.guest){
                event.preventDefault();
                buttons.mustLogin(event);
            }
        });
        
        var chat_list_box = $('#chatListBox'),
            chat_list = $('.listAnswer', chat_list_box);
            
        chat_list_box.bind('mousewheel', function(event){
            event.stopPropagation();
            return false;
        });    
        chat_list.jScrollPane({
            scrollbarMargin: 15
        });
        $('#box_list_questions .listQuestions').css('overflow', 'auto').jScrollPane({
            scrollbarMargin: 15
        });
        
        if(page_options.playerData) {
            var flashvars = {
                parameters: page_options.playerData.videoAsJson,
                menu: false,
                captions: true
            };
            var attributes = {
                name: 'video_player_content'
            };

            swfobject.embedSWF("/design/flash/player.swf", "video_player_content", "612", "347", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams, attributes);
            
            $('#video_player_content').ready(function(){
                $('#video_player_content').boundsBacklight({
                    hideAction: function(status){
                        var player = swfobject.getObjectById('video_player_content');
                        player.sendEvent('backlight',true);
                    }
                });
            });
        }
        
        carousel.css('position','relative').ajaxIndikator({
            orientation:'center',
            title:i18n.m98
        });
    },
    gimSubmit: function () {
        var page_options = arguments[0],
        gim_submit = $('#gim_submit_box'),
        _form = $('#gim_form_submission'),
        validator  = _form.validate(formActions.gimSubmitForm);
        
        $('#gim_submit_box').css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m56
        });
        
        /*_form.submitAjaxIndikator();*/
        
        
        $('.collapseBoxes').collapceMenu({
            toggleButton: false,
            expandCurrent: false,
            header: true
        });
            
        $('#lang_format').hide(); 
        $('#states_box').hide();
        $('#states_box select').hide();
        
        $('#film_dialog_language').change(function(){
            $('#film_dialog_language option:selected').each(function() {
                if($(this).text() != 'English'){
                    $('#lang_format').show();
                } else {
                    $('#lang_format').hide();
                    $('#film_dialog_language_info_1').attr('checked', 'checked');
                }
            })
        }).trigger('change');
            
        $('#country').change(function(){
            $('#country option:selected').each(function(){
                var _this= $(this)
                if(_this.text() == 'United States') {
                    $('#states_box').show();
                    $('#states_box select').hide();
                    $('#states_us').show();   
                    
                } else if(_this.text() == 'Canada') {
                    $('#states_box').show();
                    $('#states_box select').hide();
                    $('#states_ca').show();   
                    
                } else {
                    $('#states_box select').hide();
                    $('#states_box').hide();   
                }
            })
        }).trigger('change');
        
        
        /*click label*/
        /*
        $('.collapseBoxes span').click(function(event){
            var _this = $(this);
            $(_this).not('.icon16').prev().trigger('click');
        })
        */
        
        $('.datepicker',_form).datepicker({
            changeYear: true,
            minDate: new Date(1900, 1 - 1, 1),
            maxDate: 0,
            yearRange: '1900:c'
        });

        if ($('#film').val()) {
            $('#film_title').val(videos_info[$('#film').val()].title);
            $('#film_type').val(videos_info[$('#film').val()].type);
            $('#film_categories').val(videos_info[$('#film').val()].categories);
            $('#film_description').val(videos_info[$('#film').val()].description);
            $('#film').change(function(){
                $('#film_title').val(videos_info[$(this).val()].title);
                $('#film_type').val(videos_info[$(this).val()].type);
                $('#film_categories').val(videos_info[$(this).val()].categories);
                $('#film_description').val(videos_info[$(this).val()].description);
            });
        }
        
        $('#payment_type_without_a_box').hide();
        $("input[name='payment_type']").change(function(){
            if ($(this).val() == 1) {
                $('#payment_type_credit_card').show();
                $('#payment_type_without_a_box').hide();
            } else {
                $('#payment_type_credit_card').hide();
                $('#payment_type_without_a_box').show();
            }
        });
        

        blockInit.gimSubmit(gim_submit, page_options);
    },
    studioIndexDetail: function () {
        var page_options = arguments[0];
        page_options.videosList.view_id = 'view-hvcl';

        var news_box = $('#gim_news');
        if(news_box.length){
            page_options.videosList.view_id = '';
        }

        var studio_box = $('#studio_box');
        //left_panel_group = {};
        
        
        var videos_box = $('#videos_box');
        blockInit.videosListCarousel(videos_box, page_options.videosList);
        videos_box.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });
         
        $('.sortingMenu', videos_box).clickMenu({
            current:0,
            action:function(){
                actions.selection(videos_box, arguments, 'videosListCarousel', page_options.videosList);
            }
        });
        
        if(typeof addthis == 'object'){
            addthis.init();
            $('#toolbox').addThisBox({
                info:page_options.studioShareInfo
            });
        }

        $('.fbLikeButton').fbLikeButton({
            title:page_options.studioShareInfo.title,
            width: 125
        });
        
        $('.button',studio_box).bind('click', function(event){
            if(user.role == global.user.role.guest){
                event.preventDefault();
                buttons.mustLogin(event);
            }
        });

         /*   
        global.studio_about = $('#studio_about');
        global.studio_about_box = $('.studioAbout', global.studio_about).detach();
        global.studio_about.remove();
            
            
        left_panel_group.aboutStudioPanel = $.slidePanel({
            title: i18n.m99,
            width: 350,
            styleClass: 'verticalText panelName-aboutVideo',
            topBar: $('<h3>' + i18n.m100 + '</h3>'),
            bottomBar: 'swcwc',//global.video_about_addinfo_box,
            content: global.studio_about_box,
            jScrollPane: true
        });
            
            
        $(document.body).bind('recalc_panels',function(){
            $.lineBoxPos({
                elements: left_panel_group,
                selector: '.slidePanelTitle',
                dimension: 'width',
                start: 115,
                separator: ie(7) ? 5 : 0,
                msieFilter: true
            });
        })
            
        $(document.body).trigger('recalc_panels');
          */  
        if(news_box.length){
            //actions.selection(videos_box, ["/videos/a/reload/?gim=1&v=7&gim-finalist=2", "Winner (1) ", 0, $('.sortingMenu', videos_box)[0]], 'videosListCarousel', page_options.videosList);
            $('.corporateNewsList', news_box).css('overflow','auto').jScrollPane({
                scrollbarMargin: 15
            });
            $('.press_tab', news_box).css('height','auto');
            $('.sortingMenu', news_box).tabsMenu({current:0, speed: 0});

            var flashvars = {
                //parameters: '%7B%22video_id%22%3A%2227530%22%2C%22title%22%3A%22Openfilm+1st+Get+It+Made+winner+celebration%22%2C%22alias%22%3A%22openfilm-1st-get-it-made-winner-celebration%22%2C%22activity%22%3A%221%22%2C%22user_id%22%3A%2217742%22%2C%22dt_published%22%3A%222010-12-17+05%3A07%3A20%22%2C%22description%22%3A%22Openfilm+Chairman+celebrates+the+1st+Get+It+Made+winner+Val+Lauren+at+SoHo+House+LA.%22%2C%22crew%22%3A%22%22%2C%22main_thumb%22%3A%22%5C%2Fdata%5C%2Fimg%5C%2Fvmt%5C%2F27500%5C%2F27530%5C%2Fs1_2.jpg%22%2C%22privacy_type_id%22%3A%221%22%2C%22age_limit%22%3A%220%22%2C%22quality%22%3A%222%22%2C%22rating%22%3A%220.0000%22%2C%22rating_count%22%3A%220%22%2C%22views_count%22%3A%2215%22%2C%22favorites_count%22%3A%220%22%2C%22library_id%22%3Anull%2C%22library_meta%22%3Anull%2C%22is_music%22%3A%220%22%2C%22is_short%22%3A%221%22%2C%22is_trailer%22%3A%220%22%2C%22is_animation%22%3A%220%22%2C%22tags%22%3A%22james+caan%22%2C%22ads_settings%22%3A%7B%22overlay_id%22%3A0%2C%22preroll_id%22%3A0%2C%22disable_banner%22%3A1%7D%2C%22duration%22%3A%22538%22%2C%22is_embeddable%22%3A0%2C%22categories%22%3A%5B%7B%22category_id%22%3A%223%22%2C%22lang%22%3A%22documentary%22%2C%22video_id%22%3A%2227530%22%7D%5D%2C%22location%22%3A%22http%3A%5C%2F%5C%2Fstatic.openfilm.com%5C%2Fs%5C%2Fdata%5C%2Fvid%5C%2F27500%5C%2F27530%5C%2F%22%2C%22viewer%22%3A%7B%22viewer_id%22%3A%221%22%2C%22is_authorised%22%3A1%2C%22has_favorited%22%3A1%7D%7D',
                anchor: 0,
                ts: 0,
                menu: true,
                captions: true,
                isbacklight: true,
                acudeo: false,
                related: false
            };
            
            if (page_options.gim_quarter_id == 1) {
                flashvars.parameters = '%7B%22video_id%22%3A%2227530%22%2C%22title%22%3A%22Openfilm+1st+Get+It+Made+winner+celebration%22%2C%22alias%22%3A%22openfilm-1st-get-it-made-winner-celebration%22%2C%22activity%22%3A%221%22%2C%22user_id%22%3A%2217742%22%2C%22dt_published%22%3A%222010-12-17+05%3A07%3A20%22%2C%22description%22%3A%22Openfilm+Chairman+celebrates+the+1st+Get+It+Made+winner+Val+Lauren+at+SoHo+House+LA.%22%2C%22crew%22%3A%22%22%2C%22main_thumb%22%3A%22%5C%2Fdata%5C%2Fimg%5C%2Fvmt%5C%2F27500%5C%2F27530%5C%2Fs1_2.jpg%22%2C%22privacy_type_id%22%3A%221%22%2C%22age_limit%22%3A%220%22%2C%22quality%22%3A%222%22%2C%22rating%22%3A%220.0000%22%2C%22rating_count%22%3A%220%22%2C%22views_count%22%3A%2215%22%2C%22favorites_count%22%3A%220%22%2C%22library_id%22%3Anull%2C%22library_meta%22%3Anull%2C%22is_music%22%3A%220%22%2C%22is_short%22%3A%221%22%2C%22is_trailer%22%3A%220%22%2C%22is_animation%22%3A%220%22%2C%22tags%22%3A%22james+caan%22%2C%22ads_settings%22%3A%7B%22overlay_id%22%3A0%2C%22preroll_id%22%3A0%2C%22disable_banner%22%3A1%7D%2C%22duration%22%3A%22538%22%2C%22is_embeddable%22%3A0%2C%22categories%22%3A%5B%7B%22category_id%22%3A%223%22%2C%22lang%22%3A%22documentary%22%2C%22video_id%22%3A%2227530%22%7D%5D%2C%22location%22%3A%22http%3A%5C%2F%5C%2Fstatic.openfilm.com%5C%2Fs%5C%2Fdata%5C%2Fvid%5C%2F27500%5C%2F27530%5C%2F%22%2C%22viewer%22%3A%7B%22viewer_id%22%3A%221%22%2C%22is_authorised%22%3A1%2C%22has_favorited%22%3A1%7D%7D';
            } else if (page_options.gim_quarter_id == 2) {
                flashvars.parameters = '%7B%22video_id%22%3A%224291%22%2C%22title%22%3A%22Le+Queloune%22%2C%22alias%22%3A%22le-queloune%22%2C%22activity%22%3A%221%22%2C%22user_id%22%3A%2212%22%2C%22dt_published%22%3A%222011-06-16+11%3A53%3A39%22%2C%22description%22%3A%22Everybody%27s+afraid+of+zombies...+But+try+to+imagine+your+self+waking+up+from+the+dead...+How+would+you+feel%3F%22%2C%22crew%22%3A%22Music+by%3Cbr+%5C%2F%3EMich%5Cu00e8le+Motard%3Cbr+%5C%2F%3Eand%3Cbr+%5C%2F%3EAlexis+LeMay%22%2C%22main_thumb%22%3A%22http%3A%5C%2F%5C%2Fimg1.openfilm.com%5C%2Fstatic%5C%2Fdata%5C%2Fimg%5C%2Fvmt%5C%2F4200%5C%2F4291%5C%2Fs1_1.jpg%22%2C%22privacy_type_id%22%3A%220%22%2C%22age_limit%22%3A%220%22%2C%22quality%22%3A%221%22%2C%22rating%22%3A%224.0882%22%2C%22rating_count%22%3A%2234%22%2C%22views_count%22%3A%2218882%22%2C%22favorites_count%22%3A%220%22%2C%22library_id%22%3Anull%2C%22library_meta%22%3Anull%2C%22is_music%22%3A%220%22%2C%22is_short%22%3A%221%22%2C%22is_trailer%22%3A%220%22%2C%22is_animation%22%3A%220%22%2C%22tags%22%3A%22patrick%2Cboivin%2Cdominique%2Cpinon%2Cclown%2Czombie%2Cliving%2Cdead%22%2C%22ads_settings%22%3A%7B%22preroll_id%22%3A%22%22%2C%22disable_banner%22%3A0%2C%22disable_embedded_overlay%22%3A1%7D%2C%22duration%22%3A%22666%22%2C%22has_mobile_version%22%3A%221%22%2C%22is_embeddable%22%3A1%2C%22categories%22%3A%5B%7B%22category_id%22%3A%222%22%2C%22lang%22%3A%22comedy%22%2C%22video_id%22%3A%224291%22%7D%2C%7B%22category_id%22%3A%224%22%2C%22lang%22%3A%22drama%22%2C%22video_id%22%3A%224291%22%7D%2C%7B%22category_id%22%3A%2216%22%2C%22lang%22%3A%22horror%22%2C%22video_id%22%3A%224291%22%7D%5D%2C%22location%22%3A%22http%3A%5C%2F%5C%2Fstatic.openfilm.com%5C%2Fs%5C%2Fdata%5C%2Fvid%5C%2F4200%5C%2F4291%5C%2F%22%2C%22viewer%22%3A%7B%22is_authorised%22%3A0%2C%22has_favorited%22%3A0%7D%7D';
            }
            
            var attributes = {
                name: 'video_player_content'
            };
            swfobject.embedSWF("/design/flash/player.swf", "video_player_content", "460", "285", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams, attributes);
            $('#video_player_content').ready(function(){
                $('#video_player_content').boundsBacklight({
                    hideAction: function(status){
                        var player = swfobject.getObjectById('video_player_content');
                        player.sendEvent('backlight',true);
                    }
                });
            });
        }

        blockInit.studioIndex(studio_box, page_options)
    },
    thewallManage: function() {
        var page_options = arguments[0],
            studio_box = $('#thewall_manage'),
             _form = $('#form_film_festival'),
             validator  = _form.validate(formActions.thewallManageFilmFestival);
             
        _form.css('position','relative').ajaxIndikator({
            orientation:'scroll center',
            title:i18n.m98
        });
        _form.submitAjaxIndikator();
        
        $('#states_box').hide();
        $('#states_box select').hide();
        $('#country').change(function(){
            $('#country option:selected').each(function(){
                var _this= $(this)
                if(_this.text() == 'United States') {
                    $('#states_box').show();
                    $('#states_box select').hide();
                    $('#states_us').show();   
                    
                } else if(_this.text() == 'Canada') {
                    $('#states_box').show();
                    $('#states_box select').hide();
                    $('#states_ca').show();   
                    
                } else {
                    $('#states_box select').hide();
                    $('#states_box').hide();   
                }
            })
        }).trigger('change');
        
        $('.datepicker',_form).datepicker({
            changeYear: true,
            minDate: new Date(1900, 1 - 1, 1),
            yearRange: '1900:c+2'
        });

        $('button.remove').bind('click', function(event){
            event.preventDefault();
            link = $(this).attr('rel');
            $.dialog.confirm('Remove this Film Festival?', 'Film Festival', function(response) {
                if (response) {
                    document.location = link;
                }
            });
        });

        // form upload logo
        $('.formFestivalLogo').each(function(){
            var _form_festival_logo = $(this);

            validator = _form_festival_logo.validate(formActions.festivalLogoForm);
            _form_festival_logo.submitAjaxIndikator();
            $('a[href="#form_reset"]',_form_festival_logo).bind('click',function(event){
                event.preventDefault();
                validator.resetForm();
                _form_festival_logo.find('.fileInput').val('');
                _form_festival_logo.find('.fileText').text('');
            });

            $('input[type="file"]',_form_festival_logo).stylizedInputFile();

        });

        //$('a.channelThumb').thumbLoadControl();
        //$('a.previewChannelB').thumbLoadControl();

        global.imageCrop = new Image();
    },
    thewallFestivalList: function() {
        var page_options = arguments[0];

        $('button.remove').bind('click', function(){
            link = $(this).attr('rel');
            $.dialog.confirm('Remove this Film Festival?', 'Film Festival', function(response) {
                if (response) {
                    document.location = link;
                }
            });
        });
    },
    thewallSpotlight: function() {
        var page_options = arguments[0],
            studio_box = $('#openfilm_spotlight'),
             _form = $('#form_openfilm_spotlight'),
             validator  = _form.validate(formActions.thewallOpenfilmSpotlight);

            $('.datepicker',_form).datepicker({
                        changeYear: true,
                        minDate: new Date(1900, 1 - 1, 1),
                        maxDate: 0,
                        yearRange: '1900:c'
            });

            _form.css('position','relative').ajaxIndikator({
                orientation:'scroll center',
                title:i18n.m98
            });
            _form.submitAjaxIndikator();
    },
    thewallNews: function() {
        var page_options = arguments[0],
            studio_box = $('#inthenews'),
             _form = $('#form_inthenews'),
             validator  = _form.validate(formActions.thewallInTheNews);

            $('.datepicker',_form).datepicker({
                        changeYear: true,
                        minDate: new Date(1900, 1 - 1, 1),
                        maxDate: 0,
                        yearRange: '1900:c'
            });

            _form.css('position','relative').ajaxIndikator({
                orientation:'scroll center',
                title:i18n.m98
            });
            _form.submitAjaxIndikator();
    },
    surveyMembership: function() {
        _form = $('#survey_membership_form');
        validator = _form.validate(formActions.surveyMembershipForm);

        $('a[href="#form_reset"]',_form).bind('click',function(event){
            event.preventDefault();
            validator.resetForm();
        });
    }
};

var blockInit = {
    studioIndex: function() {
        var studio_box = arguments[0],
        block_options = arguments[1];
        
        
    },
    gimSubmit: function () {
        var gim_submit = arguments[0],
        block_options = arguments[1];
    },
    chatIndexList: function () {
        var chat_box = arguments[0],
        block_options = arguments[1];
        $('a.userThumb').thumbLoadControl();
    },
    filmfestivalIndexList: function() {
        var ff_box = arguments[0],
        block_options = arguments[1],
        channelList = $('.channelListFilmfestival');
        blogList = $('.blogListFilmfestival')
        
        
        $('a.festivalThumb', ff_box).thumbLoadControl();
        $('a.channelThumb', channelList).thumbLoadControl();
        $('a.blogPostThumb', blogList).thumbLoadControl();
        
        $('.pager', ff_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(ff_box, arguments, 'filmfestivalIndexList', block_options); 
            }
        });
    },
    filmfestivalListBrowse: function() {
        var ff_box = arguments[0],
        block_options = arguments[1];
            
        $('a.festivalThumb', ff_box).thumbLoadControl();

        $('.pager', ff_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(ff_box, arguments, 'filmfestivalListBrowse', block_options); 
            }
        });

        if(block_options.filters){
            var filters_menu = $('.filtersMenu',ff_box)
            filters_menu.dropDownMenu();
            filters_menu.blockClick();
            $('ul', filters_menu).clickMenu({
                current:false,
                action:function(){
                    actions.filtering(ff_box, arguments, 'filmfestivalListBrowse', block_options);
                }
            });
            
            if($.isPlainObject(block_options.filtersScroll)){
                filters_menu.dropDownMenuItemScroll(block_options.filtersScroll);
            }
        }
        global.search_panel = $('#content_search_box');
        
    //return ff_box;
    },
    FestivalDetails: function() {
        var FestivalDetails = arguments[0],
        block_options = arguments[1];
		
        $('a.festivalThumb', FestivalDetails).thumbLoadControl();
    },
    reviewsChannelList: function(){
        var reviewsChannelList = arguments[0],
        block_options = arguments[1];

        $('a.channelThumb', reviewsChannelList).thumbLoadControl();
        $('a.userThumb', reviewsChannelList).thumbLoadControl();

        $('.pager',reviewsChannelList).clickMenu({
            current:false,
            action:function(){
                actions.paging(reviewsChannelList, arguments, 'reviewsChannelList', block_options);
            }
        });

        $('.sortToggleMenu ', reviewsChannelList).sortToggleMenu({
            current:false,
            action:function(){
                actions.sorting(reviewsChannelList, arguments, 'reviewsChannelList', block_options);
            }
        });
        $('.ratingValue', reviewsChannelList).initStars();

        return reviewsChannelList;
    },
    reviewsVideoList: function(){
        var reviewsVideoList = arguments[0],
        block_options = arguments[1];

        $('a.videoThumb', reviewsVideoList).thumbLoadControl();
        $('a.userThumb', reviewsVideoList).thumbLoadControl();

        $('.pager',reviewsVideoList).clickMenu({
            current:false,
            action:function(){
                actions.paging(reviewsVideoList, arguments, 'reviewsVideoList', block_options);
            }
        });

        $('.sortToggleMenu ', reviewsVideoList).sortToggleMenu({
            current:false,
            action:function(){
                actions.sorting(reviewsVideoList, arguments, 'reviewsVideoList', block_options);
            }
        });
        // $('a.thumbRoll', reviewsVideoList).thumbRoll();
        $('.ratingValue', reviewsVideoList).initStars();

        return reviewsVideoList;
    },
    blogsPostsList: function(){

        var blogs_posts_box = arguments[0],
        block_options = arguments[1];

        $('a.blogPostThumb',blogs_posts_box).thumbLoadControl();

        $('.pager',blogs_posts_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(blogs_posts_box, arguments, 'blogsPostsList', block_options);
            }
        });

        if(block_options.filters){
            var filters_menu = $('.filtersMenu',blogs_posts_box);
            filters_menu.dropDownMenu();
            filters_menu.blockClick();
            $('ul',filters_menu).clickMenu({
                current:false,
                action:function(){
                    actions.filtering(blogs_posts_box, arguments, 'blogsPostsList', block_options);
                }
            });

            if($.isPlainObject(block_options.filtersScroll)){
                filters_menu.dropDownMenuItemScroll(block_options.filtersScroll);
            }
        }
        return blogs_posts_box;
    },
    blogsList: function(){

        var blogs_box = arguments[0],
        block_options = arguments[1];

        $('a.userThumb',blogs_box).thumbLoadControl();

        $('.pager',blogs_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(blogs_box, arguments, 'blogsList', block_options);
            }
        });

        if(block_options.filters){
            var filters_menu = $('.filtersMenu',blogs_box);
            filters_menu.dropDownMenu();
            filters_menu.blockClick();
            $('ul',filters_menu).clickMenu({
                current:false,
                action:function(){
                    actions.filtering(blogs_box, arguments, 'blogsList', block_options);
                }
            });

            if($.isPlainObject(block_options.filtersScroll)){
                filters_menu.dropDownMenuItemScroll(block_options.filtersScroll);
            }
        }
        return blogs_box;
    },
    usersList: function(){

        var users_box = arguments[0],
        block_options = arguments[1];

        $('a.userThumb',users_box).thumbLoadControl();

        /*var thumb_panel_options = {
            buttons: [buttons.thumbPanel.addAsFriend]
        }
        $('a.userThumb',users_box).thumbPanel(thumb_panel_options);*/

        $('.pager',users_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(users_box, arguments, 'usersList', block_options, global.users_box_tmp_content); // global.users_box_tmp_content - DEL - для эмуляции
            }
        });

        if(block_options.filters){
            var filters_menu = $('.filtersMenu',users_box);
            filters_menu.dropDownMenu();
            filters_menu.blockClick();
            $('ul',filters_menu).clickMenu({
                current:false,
                action:function(){
                    actions.filtering(users_box, arguments, 'usersList', block_options, global.users_box_tmp_content); // global.users_box_tmp_content - DEL - для эмуляции
                }
            });

            if($.isPlainObject(block_options.filtersScroll)){
                filters_menu.dropDownMenuItemScroll(block_options.filtersScroll);
            }
        }
        return users_box;
    },
    activityList: function(){

        var activity_box = arguments[0],
        block_options = arguments[1];

        $('a.userThumb, a.videoThumb, a.channelThumb, a.pictureThumb',activity_box).thumbLoadControl();
        
        $('.pager',activity_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(activity_box, arguments, 'activityList', block_options);
            }
        });

        return activity_box;
    },
    channelsList: function(){

        var channels_box = arguments[0],
        block_options = arguments[1];

        $('a.channelThumb',channels_box).thumbLoadControl();

        var thumb_panel_options = {
            buttons: [buttons.thumbPanel.channelInfo]
        }
        $('a.channelThumb',channels_box).thumbPanel(thumb_panel_options);
        //$('span.moreText',channels_box).moreTextHide();
        $('.ratingValue',channels_box).initStars();

        $('.pager',channels_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(channels_box, arguments, 'channelsList', block_options);
            }
        });

        if(block_options.filters){
            $('.filtersMenu',channels_box).dropDownMenu();
            $('.filtersMenu',channels_box).blockClick();
            $('.filtersMenu ul',channels_box).clickMenu({
                current:false,
                action:function(){
                    actions.filtering(channels_box, arguments, 'channelsList', block_options);
                }
            });
        }
        return channels_box;
    },
    channelsListCarousel: function(){

        var channels_box = arguments[0],
        block_options = arguments[1],
        _block_init_method = arguments[2],
        _block_options =  arguments[3],
        channels_list_wrapper = $('.channelsList>.wrapper',channels_box);
        channels_box.addClass('channelsThumbCarouselView');

        $('a.channelThumb', channels_box).thumbLoadControl();

        var thumb_panel_options = {
            buttons: [buttons.thumbPanel.channelInfoFull]
        }
        channels_list_wrapper.carousel({
            visible:5,
            scroll:5
        });
        $('a.channelThumb',channels_box).thumbPanel(thumb_panel_options);
        //$('span.moreText',channels_box).moreTextHide();
        $('.ratingValue',channels_box).initStars();
        
        $('.pager',channels_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(channels_box, arguments, 'channelsListCarousel', block_options); 
            }
        });
        return channels_box;

    },
    commentsList:function(){
        var comments_box = arguments[0],
        block_options = arguments[1];

        var pager = $('.reloadContent .pagerBottom', comments_box);

        if(pager.length){
            var new_pager = pager.clone();  /* detach() freez browser */
            $('.slidePanelBottomBar .block', comments_box).html(new_pager);
            pager.remove();
            new_pager.clickMenu({
                current:false,
                action:function(){
                    actions.paging(comments_box, arguments, 'commentsList', block_options);
                }
            });
        } else {
            $('.slidePanelBottomBar .block', comments_box).empty();
        }

        $('a.userThumb',comments_box).thumbLoadControl();
        $('.voteValue', comments_box).initVote({
            action: actions.vote
        });
        var comments = $('.commentsList li .comment',comments_box);
        if(ie(7)){
            var number = comments.length + 1;
            comments.css('z-index',function(){
                return number--;
            })
        }
        if(user.role > global.user.role.viewer){
            $('<a href="#" class="buttonShortcutMenu"></a>').appendTo(comments).toggleButton({
                labelFirst: '<span class="pointerLeft"/>',
                labelSecond: '<span class="pointerRight"/>',
                tooltipFirst: i18n.m153,
                tooltipSecond: i18n.m144,
                first: '#open',
                second: '#close',
                action: function(){
                    var obj = arguments[4];
                    var menu = obj.parent().find('.shortcutMenuBox').clone().css('display','block');
                    $('.buttonSpam',menu).bind('click',function(event){
                        actions.reportSpam({
                            'href':$(this).attr('href'),
                            'obj':$(this)
                        }, event);
                        event.stopPropagation();
                        return false;
                    });
                    $('.buttonDelete',menu).bind('click',function(event){
                        actions.deleteComment({
                            'href':$(this).attr('href'),
                            'obj':$(this),
                            'block': comments_box
                        });
                        event.stopPropagation();
                        return false;
                    });
                    obj.toggleNextBox({
                        styleClass: 'shortcutMenu',
                        content: menu,
                        slide: 'right'
                    });
                }
            });
        }
        var button_answer = $('.buttonAnswer', comments_box);
        button_answer.toggleButton({
            labelFirst: i18n.m147,
            labelSecond: i18n.m144,
            first: '#answer',
            second: '#close',
            lockAction: ( mustLogin('comment-answer') || mustConfirm('comment-answer'))? function(){
                buttons.mustLogin(arguments[0]);
            } : null,
            action: function(){
                var obj = arguments[4];
                var form = $(templates.commentsForm({
                    action: '',
                    styleClass: 'formAddComment',
                    buttonTitle: i18n.m145
                }));

                var textarea = form.find('.textareaComment');

                form.validate(formActions.commentForm);
                textarea.remainingCharacterCount({
                    characterCount:config.commentsCharacterCount
                });
                textarea.bind('keydown',function(event){
                    event.stopPropagation();
                });
                obj.toggleNextBox({
                    styleClass: 'commentForm commentFormAnsver',
                    content: form,
                    afterShow: function(){
                        $('.textareaComment').select();
                    }
                });
            }
        });

        $('.buttonEdit', comments_box).toggleButton({
            labelFirst: i18n.m148,
            labelSecond: i18n.m144,
            first: '#edit',
            second: '#close',
            action: function(){
                var obj = arguments[4];
                var form = $(templates.commentsForm({
                    action: '',
                    styleClass: 'formEditComment',
                    buttonTitle: i18n.m149
                }));

                var textarea = form.find('.textareaComment');

                form.validate(formActions.commentForm);
                textarea.remainingCharacterCount({
                    characterCount:config.commentsCharacterCount
                });
                var post = obj.parent().parent().find('>.comment .post p').text();
                textarea.val(post);
                textarea.trigger('keyup');
                textarea.bind('keydown',function(event){
                    event.stopPropagation();
                });
                obj.toggleNextBox({
                    styleClass: 'commentForm commentFormEdit',
                    content: form,
                    afterShow: function(){
                        $('.textareaComment').select();
                    }
                });
            }
        });

        $(window).trigger('resize.'+comments_box.attr('id')+'_recalc');

        return comments_box;
    },
    videosListLineCarousel: function(){
        var videos_box = arguments[0],
        block_options = arguments[1],
        videos_list_wrapper = $('.videosList>.wrapper',videos_box);

        $('a.videoThumb',videos_box).thumbLoadControl();
        videos_list_wrapper.carousel();
        var thumb_panel_options = {
            stopRollImage: true,
            buttons: [buttons.thumbPanel.videoInfo,buttons.thumbPanel.playlist]
        }
        $('a.thumbRoll',videos_box).thumbPanel(thumb_panel_options).thumbRoll();

        $('.ratingValue',videos_box).initStars();
            
        $('.pager',videos_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(videos_box, arguments, 'videosListLineCarousel', block_options);
            }
        });
        $('.sortToggleMenu',videos_box).sortToggleMenu({
            current:false,
            action:function(){
                actions.sorting(videos_box, arguments, 'videosListLineCarousel', block_options);
            }
        });

        return videos_box;
    },
    videosListCarousel: function(){
        var videos_box = arguments[0],
        block_options = arguments[1],
        videos_list = $('.videosList',videos_box),
        videos_reload_content = $('.reloadContent',videos_box),
        videos_reload_content_height = videos_reload_content.height(),
        videos_list_wrapper = $('.videosList>.wrapper',videos_box),
        videos_list_items = $('.item', videos_list_wrapper),
        videos_reload_content_height_s = videos_list_wrapper.find('.item:eq(0)').outerHeight(true) + $('.sortToggleMenu',videos_box).outerHeight(true),
        videos_list_content = videos_list_wrapper.detach()
        videos_list_page_count = $('.pagerTop .pageCount', videos_box);
        
        var p = false;
        if(videos_list_page_count.length && parseInt(videos_list_page_count.text()) > 0){
            p = true;
        }
        if(!block_options.view_id){
            block_options.view_id = 'view-vcl';
        }
        var df_view = block_options.view;
        store.get(block_options.view_id ,function(ok, val) {
            block_options.view = val || df_view;
        });

        videos_box.removeClass('quickLineFullView quickLineCarouselView').addClass(videos_list_items.length > 3 || p ? block_options.view : 'quickLineFullView');
        

        
        $(videos_box.selector + '.quickLineFullView').die().live('initBox',function(){
            //$(this).css('background','pink');
            videos_list_content.removeAttr('style');
            videos_list.html(videos_list_content);
            $('a.videoThumb',videos_box).thumbLoadControl();
            if(typeof block_options.play == 'function'){
                $('a.videoThumb',videos_box).bind('click', block_options.play)
            }
            
            var thumb_panel_options = {
                stopRollImage: true,
                buttons: [buttons.thumbPanel.videoInfo,buttons.thumbPanel.playlist]
            }
            $('a.thumbRoll',this).thumbPanel(thumb_panel_options).thumbRoll();
            //$('span.moreText',this).moreTextHide();
            $('.ratingValue',this).initStars(); 
        });

        $(videos_box.selector + '.quickLineCarouselView').die().live('initBox',function(){
            //$(this).css('background','blue');
            videos_list.html(videos_list_content);
            $('a.videoThumb',videos_box).thumbLoadControl();
            if(typeof block_options.play == 'function'){
                $('a.videoThumb',videos_box).bind('click', block_options.play)
            }
            videos_list_content.carousel();
            var thumb_panel_options = {
                stopRollImage: true,
                buttons: [buttons.thumbPanel.videoInfo,buttons.thumbPanel.playlist]
            }
            $('a.thumbRoll',this).thumbPanel(thumb_panel_options).thumbRoll();
            //$('span.moreText',this).moreTextHide();
            $('.ratingValue',this).initStars();
            videos_reload_content_height_s = videos_reload_content.height();
        });

        videos_box.trigger('initBox');
        
        if(videos_list_items.length > 3){
            $('.reloadContent',videos_box).append('<a id="' + block_options.view_id + '" class="listViewMode"></a>');
            $('.listViewMode',videos_box).toggleButton({
                state: block_options.view == 'quickLineCarouselView' ? 0 : 1,
                labelFirst: i18n.m112,
                labelSecond: i18n.m113,
                first: '#quickLineFullView',
                second: '#quickLineCarouselView',
                bodyClick: true,
                store: user.uistore,
                action: function(){
                    videos_box.toggleClass(arguments[0].replace(/.*#/,'') + ' ' + arguments[1].replace(/.*#/,''));
                    block_options.view = arguments[0].replace(/.*#/,'');
                    $('.videosList .videoThumb .panel', videos_box).remove();
                    $('.videosList .item *', videos_box).unbind();
                    box_fx.listViewModeSlide(videos_box, arguments[0], '#quickLineCarouselView', '#quickLineFullView', videos_reload_content, videos_reload_content_height, videos_reload_content_height_s);
                }
            }).backgroundBlink({from: '#323232', to: '#4a4a4a'});
        }
        $('.pager',videos_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(videos_box, arguments, 'videosListCarousel', block_options);
            }
        });
        $('.sortToggleMenu',videos_box).sortToggleMenu({
            current:false,
            action:function(){
                actions.sorting(videos_box, arguments, 'videosListCarousel', block_options);
            }
        });

        return videos_box;
    },
    videosFullList: function(){

        var videos_box = arguments[0],
        block_options = arguments[1];


        var df_view = block_options.view;
        store.get(block_options.view_id ,function(ok, val) {
            block_options.view = val || df_view;
        });

        videos_box.removeClass('detailedView quickView').addClass(block_options.view);

        $('a.videoThumb',videos_box).thumbLoadControl();
        $('a.channelThumb',videos_box).thumbLoadControl();

        $(videos_box.selector + '.quickView').die().live('initBox',function(){
            //$(this).css('background','red');
            var thumb_panel_options = {
                stopRollImage: true,
                buttons: [buttons.thumbPanel.videoInfo,buttons.thumbPanel.playlist]
            }

            $('a.thumbRoll',this).thumbPanel(thumb_panel_options).thumbRoll();
            //$('span.moreText',this).moreTextHide();
            $('.ratingValue',this).initStars();
        });

        $(videos_box.selector + '.detailedView').die().live('initBox',function(){
            //$(this).css('background','blue');
            $('#target_box').trigger('targetBoxHide');

            var thumb_panel_options = {
                stopRollImage: true,
                buttons: [buttons.thumbPanel.playlist]
            }

            $('a.thumbRoll',this).thumbPanel(thumb_panel_options).thumbRoll();
            //$('span.moreText',this).moreTextShowHide();
            $('.ratingValue',this).initStars();
        });

        videos_box.trigger('initBox');

        $('.pager',videos_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(videos_box, arguments, 'videosFullList', block_options, global.videos_box_tmp_content); /* global.videos_box_tmp_content - DEL - для эмуляции*/
            }
        });
        
        if(block_options.filters){
            var filters_menu = $('.filtersMenu',videos_box)
            filters_menu.dropDownMenu();
            filters_menu.blockClick();
            $('ul',filters_menu).clickMenu({
                current:false,
                action:function(){
                    actions.filtering(videos_box, arguments, 'videosFullList', block_options);
                }
            });
            
            if($.isPlainObject(block_options.filtersScroll)){
                filters_menu.dropDownMenuItemScroll(block_options.filtersScroll);
            }
        }
        var view_mod_menu = $(templates.linksList(links.video_full_list_view, 'listViewMode', block_options.view_id, 16));
        $('.reloadContent', videos_box).prepend(view_mod_menu);

        videos_box[0].currentView = 0;
        if(block_options.view == 'detailedView'){
            videos_box[0].currentView = 1;
        }

        view_mod_menu.clickMenu({
            current:videos_box[0].currentView,
            store: user.uistore,
            action:function(){
                videos_box.toggleClass('detailedView quickView');
                block_options.view = arguments[0].replace(/.*#/,'');
                $('.videosList .videoThumb .panel', videos_box).remove();
                $('.videosList .item *', videos_box).unbind();
                videos_box.trigger('initBox');
                return true;
            }
        });

    //return videos_box;
    },
    videosList: function(){

        var videos_box = arguments[0],
        block_options = arguments[1];

        $('a.videoThumb',videos_box).thumbLoadControl();

        var thumb_panel_options = {
            stopRollImage: true,
            buttons: [buttons.thumbPanel.videoInfo, buttons.thumbPanel.playlist]
        }
        $('a.thumbRoll',videos_box).thumbPanel(thumb_panel_options).thumbRoll();
        //$('span.moreText',videos_box).moreTextHide();
        $('.ratingValue',videos_box).initStars();

        $('.pager',videos_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(videos_box, arguments, 'videosList', block_options);
            }
        });

        if(block_options.filters){
            $('.filtersMenu',videos_box).dropDownMenu();
            $('.filtersMenu',videos_box).blockClick();
            $('.filtersMenu ul',videos_box).clickMenu({
                current:false,
                action:function(){
                    actions.filtering(videos_box, arguments, 'videosList', block_options);
                }
            });
        }

        return videos_box;
    },
    contestsListCarousel: function(){
        var contests_box = arguments[0],
        contests_list_wrapper = $('.contestsList>.wrapper',contests_box);
        contests_box.addClass('contestsTumbsCarouselView');

        contests_list_wrapper.carousel({
            visible:3,
            scroll:1
        });
            
            insertAds($("div.ap"));
        
        $('.pager', contests_box).clickMenu({
            current: false,
            action: function(){
                
                actions.paging(contests_box, arguments, 'contestsListCarousel','');
            }
        });
        
        return contests_box;
    },
    chatFutureCarousel: function () {
        var chat_box = arguments[0],
            chat_box_wrapper = $('.wrapper',chat_box);
        
        chat_box_wrapper.carousel({
            visible:3,
            scroll:1
        });
    /*
        $('.pager',chat_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(chat_box, arguments, 'chatFutureCarousel','');
            }
        });*/
    },
    chatArchiveCarousel: function () {
        var chat_box = arguments[0],
            chat_box_wrapper = $('.wrapper',chat_box);
        
        chat_box_wrapper.carousel({
            visible:2,
            scroll:1
        });
    /*
        $('.pager',chat_box).clickMenu({
            current:false,
            action:function(){
                actions.paging(chat_box, arguments, 'chatArchiveCarousel','');
            }
        });
        */
    },
    userPhotosList : function(){

        var users_photos_box = arguments[0],
            block_options = arguments[1];

        var pager = $('.reloadContent .pagerBottom', users_photos_box);

        if(pager.length){
            var new_pager = pager.clone();  /* detach() freez browser */
            
            $('.slidePanelBottomBar .block', users_photos_box).html(new_pager);
            pager.remove();
            new_pager.clickMenu({
                current:false,
                action:function(){
                    actions.paging(users_photos_box, arguments, 'userPhotosList', block_options);
                }
            });
        } else {
            $('.slidePanelBottomBar .block', users_photos_box).empty();
        }
        
        $('a.pictureThumb[rel="user-pictures"]', users_photos_box).colorbox({
            slideshow:true,
            slideshowAuto:false,
            slideshowSpeed: 2000,
            current: i18n.m105,
            slideshowStart: i18n.m106,
            slideshowStop: i18n.m107
        });
        
        $('a.pictureThumb').thumbLoadControl();
        $(window).trigger('resize.'+users_photos_box.attr('id')+'_recalc');
        return users_photos_box;
    }
};

var actions = {
    paging: function(_block, _action_arguments, _block_init_method, _block_options){
        var href = _action_arguments[0],
        text = _action_arguments[1],
        index = _action_arguments[2],
        menu = _action_arguments[3],
        count = $('li:last',menu).prev().text();

        if($('li',menu).length == 2){
            _block.trigger('ajaxIndikatorShow',{
                title:i18n.m244,
                titleData:{
                    number:text,
                    count:count
                }
            });
        }
        else{
            _block.trigger('ajaxIndikatorShow',{
                title:i18n.m57,
                titleData:{
                    number:text,
                    count:count
                }
            });
        }

        $.ajax({
            url: href,
            cache: false,
            complete: function() {
                _block.trigger('ajaxIndikatorHide');
            },
            success: function(data) {
                if(data)
                {
                    $('.reloadContent',_block).html(data.html);
                }
                blockInit[_block_init_method](_block, _block_options); // reinit
                /* скролим вверх если все хорошо */
                //var pageTracker = _gat._getTracker("UA-4509200-1");
                   // pageTracker._trackEvent('pager', 'ajax_reload', href);
                    
                if(_block_options.scrollTo){
                    box_fx.boxScrollToTop(_block_options.scrollTo);
                }else{
                    box_fx.boxScrollToTop(_block);
                }
            },
            error: function() {
                $(menu).trigger('currentBack');
            },
            dataType:'json'
        });


        return;
    },
    selection: function(_block, _action_arguments, _block_init_method, _block_options){
        var href = _action_arguments[0],
        text = _action_arguments[1],
        menu = _action_arguments[2];

        _block.trigger('ajaxIndikatorShow',{
            titleData:{
                text:text.replace(/\(.*\)/,'')
            }
        });

        $.ajax({
            url: href,
            cache: false,
            complete: function() {
                _block.trigger('ajaxIndikatorHide');
            },
            success: function(data) {
                $('.reloadContent',_block).html(data.html);
                blockInit[_block_init_method](_block,_block_options); // reinit
               //var pageTracker = _gat._getTracker("UA-4509200-1");
                   // pageTracker._trackEvent('selection', 'ajax_reload', href);
            },
            error: function() {
                $(menu).trigger('currentBack');
            },
            dataType:'json'
        });

    },
    filtering: function(_block, _action_arguments, _block_init_method, _block_options){
        var href = _action_arguments[0],
        text = _action_arguments[1],
        menu = _action_arguments[2];

        _block.trigger('ajaxIndikatorShow',{
            titleData:{
                text:text
            }
        });

        $.ajax({
            url: href,
            cache: false,
            complete: function() {
                _block.trigger('ajaxIndikatorHide');
            },
            success: function(data) {
                $('.reloadContent',_block).html(data.html);
                blockInit[_block_init_method](_block,_block_options); // reinit
                //var pageTracker = _gat._getTracker("UA-4509200-1");
                   // pageTracker._trackEvent('filtering', 'ajax_reload', href);
            },
            error: function() {
                $(menu).trigger('currentBack');
            },
            dataType:'json'
        });

    },
    sorting: function(_block, _action_arguments, _block_init_method, _block_options){
        var href = _action_arguments[0],
        sort = _action_arguments[1],
        text = _action_arguments[2],
        menu = _action_arguments[3];

        _block.trigger('ajaxIndikatorShow',{
            titleData:{
                text: ' - ' + i18n.m110 + ': ' + text
            }
        });

        $.ajax({
            url: href,
            cache: false,
            complete: function() {
                _block.trigger('ajaxIndikatorHide');
            },
            success: function(data) {
                _block.trigger('ajaxIndikatorHide');
                $('.reloadContent',_block).html(data.html);
                blockInit[_block_init_method](_block,_block_options); // reinit
                
               // var pageTracker = _gat._getTracker("UA-4509200-1");
                   // pageTracker._trackEvent('sorting', 'ajax_reload', href);
            },
            error: function() {
                $(menu).trigger('currentBack');
            },
            dataType: 'json'
        });
    },
    rating: function(){
        //alert(1);
        var id = arguments[0].id,
        rating = arguments[0].rating,
        //href = arguments[0].href + arguments[0].rating,
        status = arguments[0].status,
        obj = arguments[0].obj;
        //alert(id);
        //status = 1;

        //var last_rating = obj.prev().text().replace('\.','-');
        obj.empty().css('cursor', 'default');

        if (status) {
            /*типа посылаем запрос и если все гуд*/
            $.ajax({
                type: 'POST',
                url: '/videos/a/rate/',
                cache: false,
                data: ({
                    rating: rating,
                    video_id: id
                }),
                complete: function() {},
                error: function() {},
                success: function(data) {
                    var res = data.response;
                    if (res) {
                        $.ajaxAlert({
                            title: i18n.m117,
                            text:i18n.m118.supplant({
                                number:rating
                            }),
                            styleClass: 'message',
                            buttonClose: true,
                            speedClose: 2000
                        });
                    } else {
                        $.ajaxAlert({
                            title: i18n.m117,
                            text:i18n.m119,
                            styleClass: 'notice',
                            buttonClose: true,
                            speedClose: 2000
                        });
                    }
                },
                dataType:'json'
            });
            setTimeout(function(){
                },1000);
        } else {
            $.ajaxAlert({
                title: i18n.m117,
                text:i18n.m119,
                styleClass: 'notice',
                buttonClose: true,
                speedClose: 2000
            });
        }
    },
    reportSpam : function() {
    
        if (mustLogin('comment-report-spam') || mustLogin('comment-report-spam')){
            buttons.mustLogin(arguments[1]);
            return;
        }
    
        var href = arguments[0].href,
        obj = arguments[0].obj;

        var objType = $('#objType').val();
        var item = obj.parent().parent().parent().parent().parent();

        var id = item.attr('id').replace(/.*_/,'');

        obj.parent().text(i18n.m157);

        $.ajax({
            type: 'GET',
            url: '/comments/spam/' + objType + '/' + id,
            cache: false,
            async: false,
            success: function(){
                $.ajaxAlert({
                    title: i18n.m157,
                    text:i18n.m156,
                    styleClass: 'message',
                    buttonClose: true,
                    speedClose: 3000
                });
            },
            dataType:'json'
        });
    },
    deleteComment : function(){
        var _block = arguments[0].block,
        href = arguments[0].href,
        obj = arguments[0].obj;

        var objType = $('#objType').val();
        var item = obj.parent().parent().parent().parent().parent();
        var id = item.attr('id').replace(/.*_/,'');
        var item_offset = item.position().top;

        var cp = $('.pagerBottom li.current a',_block).text();

        if (cp == '') {
            cp = 1
        }

        _block.trigger('ajaxIndikatorShow',{
            title: i18n.m158
        });

        $.ajax({
            type: 'GET',
            url: '/comments/delete/' + objType + '/' + id + '?cp=' + cp,
            cache: false,
            async: false,
            success: function(data) {
                $('.reloadContent',_block).html(data.html);
                blockInit.commentsList(_block,page_options.commentsList);
                
                _block.trigger('ajaxIndikatorHide');

                _block.trigger('titleChange',{
                    title: i18n.m102.supplant({
                        number:data.count
                    })
                });

                $('.slidePanelContent', _block)[0].scrollTo(item_offset);
            },
            dataType:'json'
        });

    },
    vote: function(){
 
        if( mustLogin('comment-vote') || mustConfirm('comment-vote')){
            buttons.mustLogin(arguments[1]);
            return;
        }

        var href = arguments[0].href,
        vote = arguments[0].vote,
        obj = arguments[0].obj,
        value = arguments[0].value;

        //vote = (vote < 0) ? 0 : vote;

        var objType = $('#objType').val();
        var item = obj.parent().parent().parent();

        var id = item.attr('id').replace(/.*_/,'');

        $.ajax({
            type: 'POST',
            url: '/comments/rate/' + objType + '/' + id,
            data: ({
                rating : vote
            }),
            cache: false,
            async: false,
            success: function(data) {

                if (data.result == 0) {
                    messageText = i18n.m119;
                }
                else {
                    obj.find('i').text(parseInt(value) + (vote > 0 ? vote : 0));
                    messageText = i18n.m118.supplant({
                        number:vote
                    });
                }

                $.ajaxAlert({
                    title: i18n.m117,
                    text: messageText,
                    styleClass: 'message',
                    buttonClose: true,
                    speedClose: 2000
                });

            },
            dataType:'json'
        });
        
    },
    addAsFriend: function(event){
        event.preventDefault();
        
        if(mustLogin('user-add-as-friend')){
            buttons.mustLogin(arguments[0]);
            return;
        }
        
        var _this = $(this),
        _href = _this.attr('href').replace(/.*#/,''),
        _id = _this.attr('rel'),
        _label = _this.find('.label'),
        _icon = _this.find('.icon48');

        if(_href == 'addAsFriend')
        {
            $.ajax({
                type: 'POST',
                url: '/users/a/friends/create/',
                cache: false,
                data: ({
                    'friend_id': _id
                }),
                success: function(data) {
                    if (data.status == true) {
                        _this.attr('href','#userInvited');
                        _label.text(i18n.m187);
                        _icon.removeClass('icon48-addAsFriend').addClass('icon48-userInvited');
                        $.ajaxAlert({
                            title: '',
                            text:i18n.m186,
                            styleClass: 'message',
                            buttonClose: true,
                            speedClose: 3000
                        });
                    }else {
                        $.ajaxAlert({
                            title: '',
                            text:i18n.m723,
                            styleClass: 'message',
                            buttonClose: true,
                            speedClose: 3000
                        });
                    }
                },
                dataType:'json'
            });

        }
        else if( _href == 'addAsFriend-accept')
        {
            
            _this.attr('href','#removeFriend');
            _label.text(i18n.m188);
            _icon.removeClass('icon48-addAsFriend').addClass('icon48-removeFriend');

            $.ajax({
                type: 'POST',
                url: '/users/a/friends/accept/',
                cache: false,
                data: ({
                    'friend_id': _id
                }),
                success: function(data) {

                    $.ajaxAlert({
                        title: '',
                        text:i18n.m186,
                        styleClass: 'message',
                        buttonClose: true,
                        speedClose: 3000
                    });
                },
                dataType:'json'
            });
            
        }
        else if(_href == 'removeFriend')
        {
            _this.attr('href','#addAsFriend');
            _label.text(i18n.m185);
            _icon.removeClass('icon48-removeFriend').addClass('icon48-addAsFriend');

            $.ajax({
                type: 'POST',
                url: '/users/a/friends/delete/',
                cache: false,
                data: ({
                    'friend_id': _id
                }),
                success: function(data) {

                    $.ajaxAlert({
                        title: '',
                        text:i18n.m189,
                        styleClass: 'message',
                        buttonClose: true,
                        speedClose: 3000
                    });

                },
                dataType:'json'
            });
            
        }else{
            $.ajaxAlert({
                title: '',
                text:i18n.m190,
                styleClass: 'message',
                buttonClose: true,
                speedClose: 3000
            });
        }
    },
    blockUser: function(event){
        event.preventDefault();
        
        if(mustLogin('user-block-user')){
            buttons.mustLogin(arguments[0]);
            return;
        }
        
        var _this = $(this),
        _href = _this.attr('href').replace(/.*#/,''),
        _id = _this.attr('rel'),
        _label = _this.find('.label'),
        _icon = _this.find('.icon48');
        if(_href == 'blockUser'){
            _this.attr('href','#unblockUser');
            _label.text(i18n.m193);
            _icon.removeClass('icon48-blockUser').addClass('icon48-unblockUser');
            
            
            $.ajax({
                type: 'POST',
                url: '/users/a/block/',
                cache: false,
                data: ({
                    'user_id': _id
                }),

                success: function(data) {
                    $.ajaxAlert({
                        title: '',
                        text:i18n.m192,
                        styleClass: 'message',
                        buttonClose: true,
                        speedClose: 3000
                    });
                },
                dataType:'json'
            });
            
        }else if(_href == 'unblockUser'){
            _this.attr('href','#blockUser');
            _label.text(i18n.m191);
            _icon.removeClass('icon48-unblockUser').addClass('icon48-blockUser');

            $.ajax({
                type: 'POST',
                url: '/users/a/unblock/',
                cache: false,
                data: ({
                    'user_id': _id
                }),

                success: function(data) {
                    
                    $.ajaxAlert({
                        title: '',
                        text:i18n.m194,
                        styleClass: 'message',
                        buttonClose: true,
                        speedClose: 3000
                    });
                },
                dataType:'json'
            });

        }
    },
    captchaLoad: function(captchaForm, captchaValidator){


        $('#captcha_string', captchaForm).attr('src', '/design/images/1px_t.gif');
        captchaForm.trigger('submitDisable');
        // captchaValidator.resetForm();
        if($('#captcha_field')[0]){
            $('#captcha_field').val('');
        }

        var cd = $.ajax({
            type: 'POST',
            url: '/generate-captcha/',
            async: false,
            dataType: 'json'
        }).responseText;
        // TODO: fix me
        eval('cd='+cd);

        $('#captcha_string', captchaForm).attr('src', cd.url + cd.code + '.png');
        $('#captcha_id', captchaForm).val(cd.code);
        captchaForm.trigger('submitEnable');
        return cd.code;
    },
    channelSubscribe: function(){
        var href = arguments[0].replace(/.*#/,''),
        id = arguments[3];
            
        if (href == 'subscribe') {
            $.ajax({
                type: 'POST',
                url: '/channels/a/subscription/add/',
                cache: false,
                data: ({
                    'channel_id': id
                }),

                success: function(data) {
                    $.ajaxAlert({
                        title: '',
                        text: i18n.m476,
                        styleClass: 'message',
                        buttonClose: true,
                        speedClose: 3000
                    });
                },
                dataType:'json'
            });
        } else if (href == 'unsubscribe') {
            $.ajax({
                type: 'POST',
                url: '/channels/a/subscription/remove/',
                cache: false,
                data: ({
                    'channel_id': id
                }),

                success: function(data) {
                    $.ajaxAlert({
                        title: '',
                        text: i18n.m477,
                        styleClass: 'message',
                        buttonClose: true,
                        speedClose: 3000
                    });
                },
                dataType:'json'
            });
        }
    },
    festivalSubscribe: function(event){
        event.preventDefault();
        
        if(mustLogin('filmfestival-subscribe')){
            buttons.mustLogin(arguments[0]);
            return;
        }
        
        var _this = $(this),
        _href = _this.attr('href').replace(/.*#/,''),
        _id = _this.attr('rel'),
        _label = _this.find('.label'),
        _icon = _this.find('.icon48');
        if(_href == 'subscrible'){
            _this.attr('href','#unSubscrible');
            _label.text(i18n.m475);
            _icon.removeClass('icon48-subscribe').addClass('icon48-unSubscribe');
            
            
            $.ajax({
                type: 'POST',
                url: '/film-festivals/a/subscription/add/',
                cache: false,
                data: ({
                    'ff_id': _id
                }),

                success: function(data) {
                    $.ajaxAlert({
                        title: '',
                        text:i18n.m192,
                        styleClass: 'message',
                        buttonClose: true,
                        speedClose: 3000
                    });
                },
                dataType:'json'
            });
            
        }else if(_href == 'unsubscrible'){
            _this.attr('href','#subscrible');
            _label.text(i18n.m474);
            _icon.removeClass('icon48-unSubscribe').addClass('icon48-subscribe');

            $.ajax({
                type: 'POST',
                url: '/film-festivals/a/subscription/remove/',
                cache: false,
                data: ({
                    'ff_id': _id
                }),

                success: function(data) {
                    
                    $.ajaxAlert({
                        title: '',
                        text:i18n.m194,
                        styleClass: 'message',
                        buttonClose: true,
                        speedClose: 3000
                    });
                },
                dataType:'json'
            });

        }
    },
    festivalFavorite: function(event){
		event.preventDefault();
        
        if(mustLogin('filmfestival-favorite')){
            buttons.mustLogin(arguments[0]);
            return;
        }
        
		var _this = $(this),
        _href = _this.attr('href').replace(/.*#/,''),
        _id = _this.attr('rel'),
        _label = _this.find('.label'),
        _icon = _this.find('.icon48');

        if(_href == 'favorite'){
            _this.attr('href','#unfavorite');
            _label.text(i18n.m1301);
            _icon.removeClass('icon48-favorite').addClass('icon48-unfavorite');

            $.ajax({
                type: 'POST',
                url: '/film-festivals/a/favorite/add/',
                cache: false,
                data: ({
                    'ff_id': _id
                }),

                success: function(data) {
                    $.ajaxAlert({
                        title: '',
                        text:i18n.m1302,
                        styleClass: 'message',
                        buttonClose: true,
                        speedClose: 3000
                    });
                },
                dataType:'json'
            });

        }else if(_href == 'unfavorite'){
            _this.attr('href','#favorite');
            _label.text(i18n.m1300);
            _icon.removeClass('icon48-unfavorite').addClass('icon48-favorite');

            $.ajax({
                type: 'POST',
                url: '/film-festivals/a/favorite/remove/',
                cache: false,
                data: ({
                    'ff_id': _id
                }),

                success: function(data) {

                    $.ajaxAlert({
                        title: '',
                        text:i18n.m1303,
                        styleClass: 'message',
                        buttonClose: true,
                        speedClose: 3000
                    });
                },
                dataType:'json'
            });
        }
    },
    chatVote: function() {
        if(mustLogin('comment-vote')){
            buttons.mustLogin(arguments[1]);
            return;
        }

        var href = arguments[0].href,
        vote = arguments[0].vote,
        obj = arguments[0].obj,
        value = arguments[0].value;
        
        //vote = (vote < 0) ? 0 : vote;

        var objType = $('#objTypeChat').val();
        var item = obj;

        var id = item.attr('id').replace(/.*_/,'');

        $.ajax({
            type: 'POST',
            url: '/chats/rate/' + id,
            data: ({
                rating : vote
            }),
            cache: false,
            async: false,
            success: function(data) {

                if (data.result == 0) {
                    messageText = i18n.m119;
                }
                else {
                    obj.find('i').text(parseInt(value) + (vote > 0 ? vote : 0));
                    messageText = i18n.m118.supplant({
                        number:vote
                    });
                }

                $.ajaxAlert({
                    title: i18n.m117,
                    text: messageText,
                    styleClass: 'message',
                    buttonClose: true,
                    speedClose: 2000
                });

            },
            dataType:'json'
        });
    },
    addToCart: function(objectId, objectTypeId){
        $.ajax({
            type: 'POST',
            url: '/dashboard/shopping/a/cart/add',
            cache: false,
            data: ({
                object_id: objectId,
                object_type_id: objectTypeId
            }),
            success: function(response) {

                if (response && response.status) {
                    $.ajaxAlert({
                        title: i18n.m207,
                        text:i18n.m809,
                        styleClass: 'message',
                        buttonClose: true,
                        speedClose: 2000
                    });
                    user.shoppingCart++;
                    userStatusBar.shoppingCart.trigger('updateStatus');
                }
                else
                {
                    $.ajaxAlert({
                        title: i18n.m207,
                        text:i18n.m1002,
                        styleClass: 'error',
                        buttonClose: true,
                        speedClose: 2000
                    });

                }
            },
            dataType:'json'
        });
    }
};

var buttons = {
    mustUnBlock: function(event){
        event.preventDefault();
        $.ajaxAlert({
            title: '',
            text:i18n.m468,
            styleClass: 'message',
            buttonClose: true,
            speedClose: 3000
        });
        return false;
    },
    mustLogin: function(event){
        event.preventDefault();
        // if user viewer
        if(user.role == global.user.role.viewer){
            $.ajaxAlert({
                title: '',
                text:i18n.m478,
                styleClass: 'notice',
                buttonClose: true,
                orientation: 'center',
                speedClose: 3000
            });
            return false;
        }
        else if(user.role > global.user.role.viewer){
            return true;
        }
        $.ajaxAlert({
            title: '',
            text:i18n.m473,
            styleClass: 'notice',
            buttonClose: true,
            orientation: 'center',
            speedClose: 3000
        });
        global.login_panel.trigger('slideIn');
        return false;
    },
    commentsBlock: {
        displayForm: {
            labelFirst: i18n.m145,
            labelSecond: i18n.m144,
            first: '#add',
            second: '#close',
            lockAction: ( mustLogin('comment-add') || mustConfirm('comment-add') ) ? function(){
                buttons.mustLogin(arguments[0]);
            } : null,
            action: function(){

                var obj = arguments[4];
                var form = $(templates.commentsForm({
                    action: '',
                    styleClass: 'formAddComment',
                    buttonTitle: i18n.m146
                }));

                form.validate(formActions.commentForm);
                form.find('.textareaComment').remainingCharacterCount({
                    characterCount:config.commentsCharacterCount
                });

                obj.toggleNextBox({
                    styleClass: 'commentForm',
                    content: form,
                    afterShow: function(){
                        $('.textareaComment').focus();
                    }
                });
            }
        }
    },
    thumbPanel: {
        playlist: {
            styleClass: 'icon16-plus',
            title: function() {
                return $(this).parents('.videoThumb').is('.inPlaylist') ? i18n.m59 : i18n.m58;
            },
            actions:{
                click: function(event) {
                    if (mustLogin('video-quicklist')) {
                        buttons.mustLogin(event);
                        return;
                    }

                    var _this = $(this);
                    $('#target_box').trigger('targetBoxHide');

                    var inPlaylist = _this.parents('.videoThumb').is('.inPlaylist');

                    _this.parents('.videoThumb').toggleClass('inPlaylist');
                    var msg_title = inPlaylist ? i18n.m350 : i18n.m349;
                    var tt_title = inPlaylist ?  i18n.m58 : i18n.m59;
                    _this.attr('title', tt_title);
                    var id = _this.parents('.item').attr('id').replace(/.*_/,''); /* идентификатор видео */

                    $.ajax( {
                        type: 'POST', // TODO: change to POST
                        url: '/playlists/a/video/' + (inPlaylist ? 'remove' : 'add') + '/quicklist/',
                        data: ({
                            video_id: id
                        }),
                        cache: false,
                        async: false,
                        success: function(data) {
                            //alert(data.response); return;
                            $.ajaxAlert({
                                title: '',
                                styleClass: 'message',
                                text: msg_title
                            });
                        },
                        dataType:'json'
                    });

                    event.stopPropagation();
                    return false;
                }
            }
        },
        playlistInfo: {
            styleClass: 'icon16-info',
            actions: {
                click: function(event){
                    $(event.target).targetBox({
                        orientation:'right',
                        styleClass:'targetBoxPlaylistInfo',
                        zIndex: 7777,
                        content:$($(event.target).parents('.item')).cloneInfo({
                            items: ['duration', 'videos']
                        })
                    });

                    event.stopPropagation();
                    return false;
                }
            }
        },
        tivoPlaylistInfo: {
            styleClass: 'icon16-info',
            actions: {
                click: function(event){
                    $(event.target).targetBox({
                        orientation:'right',
                        styleClass:'targetBoxPlaylistInfo',
                        zIndex: 7777,
                        content:$($(event.target).parents('.item')).cloneInfo()
                    });

                    event.stopPropagation();
                    return false;
                }
            }
        },
        videoInfo: {
            styleClass: 'icon16-info',
            actions:{
                click: function(event) {
                    $(event.target).targetBox( {
                        orientation:'right',
                        styleClass:'targetBoxVideoInfo',
                        zIndex: 7777,
                        content:$($(event.target).parents('.item')).cloneInfo( {
                            items: ['duration','rating','channel','added','views','quality','subtitles']
                        })
                    });

                    event.stopPropagation();
                    return false;
                }
            }
        },
        channelInfo: {
            styleClass: 'icon16-info',
            actions: {
                click: function(event){
                    $(event.target).targetBox({
                        orientation:'right',
                        styleClass:'targetBoxChannelInfo',
                        zIndex: 7777,
                        content:$($(event.target).parents('.item')).cloneInfo({
                            items: ['averageRank','by','subscribers','categories']
                        })
                    });

                    event.stopPropagation();
                    return false;
                }
            }
        },
        channelInfoFull: {
            styleClass: 'icon16-info',
            actions:{
                click: function(event){
                    $(event.target).targetBox({
                        orientation:'right',
                        styleClass:'targetBoxChannelInfo',
                        zIndex: 7777,
                        content:$($(event.target).parents('.item')).cloneInfo({
                            items: ['averageRank','by','videos','channelViews','subscribers','categories']
                        })
                    });

                    event.stopPropagation();
                    return false;
                }
            }
        },
        addAsFriend: {
            styleClass: 'icon16-addAsFriend', /*icon16-addAsFriend icon16-userInvited icon16-removeFriend*/
            title: function(){
                var _thumb = $(this).parents('.userThumb');
                return _thumb.is('.myFriend') ? i18n.m188 : _thumb.is('.invitedFriend') ? i18n.m187 : i18n.m185;
            },
            actions:{
                click: function(event){
                    /* users id */
                    var id = $(this).parents('.item').attr('id');

                    var _thumb = $(this).parents('.userThumb');
                    if(_thumb.is('.myFriend')){
                        /* удаляем из друзей */
                        $(this).attr('title', i18n.m185);
                        _thumb.removeClass('myFriend');
                        /*типа посылаем запрос и если все гуд*/
                        setTimeout(function(){
                            $.ajaxAlert({
                                title: '',
                                text:i18n.m189,
                                styleClass: 'message',
                                buttonClose: true,
                                speedClose: 3000
                            });
                        },1000);
                    }else if(_thumb.is('.invitedFriend')){
                        /* ждем поддтверждения*/
                        $.ajaxAlert({
                            title: '',
                            text:i18n.m190,
                            styleClass: 'message',
                            buttonClose: true,
                            speedClose: 3000
                        });
                    }else{
                        /* добавляем в друзья */
                        $(this).attr('title', i18n.m187);
                        _thumb.addClass('invitedFriend');
                        /*типа посылаем запрос и если все гуд*/
                        setTimeout(function(){
                            $.ajaxAlert({
                                title: '',
                                text:i18n.m186,
                                styleClass: 'message',
                                buttonClose: true,
                                speedClose: 3000
                            });
                        },1000);
                    }

                    event.stopPropagation();
                    return false;
                }
            }
        }
    }
};



var formActions = {
    loginPanelForm: {

        submitHandler: function(form)
        {
            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');
            var options = {
                success: function(response)
                {
                    _form.trigger('submitAjaxIndikatorHide');
                    var toPage = 'http://' + window.location.hostname + '/';

                    if(response.show_captcha)
                    {
                        //TODO: get it from const
                        page_options = {
                            captchaType: 1
                        };
                        $.captchaDialog({
                            action: function(){
                                /* отправляем эту фору _form */
                                _form.ajaxSubmit(options);
                            }
                        });
                        return;
                    }
                    else if(!response.status)
                    {
                        toPage = 'http://' + window.location.hostname + '/login/?login=' + _form.find('input[name="login"]').val();
                    }
                    // if success
                    else if(response.status)
                    {
                        toPage = 'http://' + document.location.hostname + document.location.pathname;
                    }

                    document.location.href = toPage;
                    $('body').trigger('ajaxIndikatorShow',{
                        title: '<a href="' + toPage +'">' + i18n.m279 + '</a>'
                    });
                },
                url: '/login/',
                dataType: "json",
                cache: false
            };
            _form.ajaxSubmit(options);
            return false;
        },
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            login: {
                required: true
            },
            password: {
                required: true
            }
        },
        messages: {
            login: {
                required: i18n.m197
            },
            password: {
                required: i18n.m197
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.prev('div.error'));
        }

    },
    unsubscribeForm: {
        submitHandler: function(form) {

            var _form = $(form);

            _form.trigger('submitAjaxIndikatorShow');

            _form.ajaxSubmit(
            {
                success: function(data) {
                    _form.trigger('submitAjaxIndikatorHide');
                    // выводим сообщение
                    if (data.status == true) {
                        $.ajaxAlert({
                            title: '',
                            text: i18n.m578,
                            styleClass: 'message',
                            buttonClose: true,
                            speedClose: 3000
                        });
                    }
                    else {
                        $.ajaxAlert({
                            title: i18n.m62,
                            text: i18n.m579,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 3000
                        });
                    }
                },
                dataType:'json',
                cache: false
            }
            );

        //return false;
        },
        invalidHandler: utils.formErrorAlert,
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            notification_settings: {
                required: true
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }

    },
    messageForm: {

        submitHandler: function(form) {
            //$(form).ajaxSubmit(options);
            

            //todo modify this
            _id = $('.buttonSendMessage').attr('rel');

            var _form = $(form);
            var _block = _form.parents('.panelName-sendMessage');

            _form.trigger('submitAjaxIndikatorShow');
            //console.log(user.userId);
            var options = {
                success: function(response)
                {
                    if(response.status)
                    {
                        /* закрываем панель */
                        _block.trigger('hide');
                        /* очищаем форму */
                        _form.find('a[href="#form_reset"]').trigger('click');
                        _form.trigger('submitAjaxIndikatorHide');
                        /* выводим сообщение */
                        $.ajaxAlert({
                            title: i18n.m183,
                            text:i18n.m184,
                            styleClass: 'message',
                            buttonClose: true,
                            speedClose: 2000
                        });
                    }

                },
                url: '/dashboard/inmails/send-message/',
                dataType: "json",
                cache: false,
                data: {
                    'recipient_id': _id
                }
            };
            _form.ajaxSubmit(options);

            return false;
        },
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            subject: {
                required: true,
                minlength: 2,
                maxlength: 140
            },
            message: {
                required: true,
                minlength: 2,
                maxlength: config.messageCharacterCount
            }
        },
        messages: {
            subject: {
                required: i18n.m182,
                minlength: i18n.m151.supplant({
                    number:2
                }),
                maxlength: i18n.m152.supplant({
                    number:140
                })
            },
            message: {
                required: i18n.m179,
                minlength: i18n.m151.supplant({
                    number:2
                }),
                maxlength: i18n.m152.supplant({
                    number:config.messageCharacterCount
                })
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.prev('div.error'));
        }

    },
    commentForm: {
        submitHandler: function(form) {
            //$(form).ajaxSubmit(options);

            var _form = $(form);
            var _block = _form.parents('.panelName-comments');
            _block.trigger('ajaxIndikatorShow',{
                title: i18n.m158
            });
            var _toggle_but = _form.parent().prev();

            /*типа посылаем запрос и если все гуд*/

            var item = _form.parent().parent().parent();
            var textarea = _form.find('.textareaComment');
            var objType = $('#objType').val();
            var objId = $('#objId').val();
            /* добавление или редактирование*/
            if(_form.is('.formAddComment')){
                /* новый или ответ*/
                if(_form.parent().parent().is('.slideForm')){
                    $.ajax({
                        type: 'POST',
                        url: '/comments/create/' + objType + '/' + objId,
                        data: ({
                            comment : textarea.val()
                        }),
                        cache: false,
                        async: false,
                        success: function(data) {
                            if (data.status == false) {

                                $.ajaxAlert({
                                    title: '',
                                    text: i18n.m468,
                                    styleClass: 'error',
                                    buttonClose: true,
                                    speedClose: 5000
                                });
                                return;
                            }
                            $('.reloadContent',_block).html(data.html);
                            blockInit.commentsList(_block,page_options.commentsList);
                            //page_options.commentsList.count+=1
                            /* меняем количество комментов в панели*/
                            _block.trigger('titleChange',{
                                title: i18n.m102.supplant({
                                    number: data.count
                                })
                            });
                        },
                        dataType:'json'
                    });
                }else{
                        
                    var id = item.attr('id').replace(/.*_/,'');
                    var item_offset = item.position().top;
                    var cp = $('.pagerBottom li.current a',_block).text();

                    if (cp == '') {
                        cp = 1
                    }
                        
                    $.ajax({
                        type: 'POST',
                        url: '/comments/create/' + objType + '/' + objId + '/' + id + '?cp=' + cp,
                        data: ({
                            comment : textarea.val()
                        }),
                        cache: false,
                        async: false,
                        success: function(data) {
                            if (data.status == false) {

                                $.ajaxAlert({
                                    title: '',
                                    text: i18n.m468,
                                    styleClass: 'error',
                                    buttonClose: true,
                                    speedClose: 5000
                                });
                                return;
                            }
                            $('.reloadContent',_block).html(data.html);
                            blockInit.commentsList(_block,page_options.commentsList);

                            $('.slidePanelContent', _block)[0].scrollTo = item_offset;

                            _block.trigger('titleChange',{
                                title: i18n.m102.supplant({
                                    number: data.count
                                })
                            });
                                    

                        },
                        dataType:'json'
                    });

                }

                /* пересчитываем панели */
                $(document.body).trigger('recalc_panels');
            }else if(_form.is('.formEditComment')){
                var id = item.attr('id').replace(/.*_/,'');

                item.find('>.comment .post p').text(textarea.val());

                $.ajax({
                    type: 'POST',
                    url: '/comments/update/' + objType + '/' + id,
                    data: ({
                        comment : textarea.val()
                    }),
                    cache: false,
                    async: false,
                    dataType:'json'
                });

            }

            _block.trigger('ajaxIndikatorHide');

            /* закрываем форму*/
            _toggle_but.trigger('click');
            /* убиваем форму */
            _form.parent().remove();
            /* передаем фокус панели */
            _block.focus();



            return false;
        },
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            comment: {
                required: true,
                minlength: 2,
                maxlength: config.commentsCharacterCount
            }
        },
        messages: {
            comment: {
                required: i18n.m150,
                minlength: i18n.m151.supplant({
                    number:2
                }),
                maxlength: i18n.m152.supplant({
                    number:config.commentsCharacterCount
                })
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.parent().find('div.error'));
        }
    },
    joinForm: {
        submitHandler: function(form){
            var _form = $(form);
            _form.trigger('ajaxIndikatorShow');

            var options = {
                success: function(response)
                {
                    _form.trigger('ajaxIndikatorHide');
                
                    //console.log(response);
                     //$.dialog.alert("<h3><h3><p>You will receive confirmation email shortly.</p><p>Sometimes confirmation emails may be sent into the Spam folder by your email system. If you do not see the confirmation email within a few minutes of registering, please thoroughly check your spam folder. If you don't locate it there, please contact us at info@openfilm.com.</p>");
                    
                    if(response && response.show_captcha)
                    {
                        $.captchaDialog({
                            action: function(){
                                _form.ajaxSubmit(options);
                            }
                        });
                    }
                    else if(response && response.status == false && response.message)
                    {
                        //common message
                        var message = eval('i18n.m' + response.message);
                        $.ajaxAlert({
                            title: '',
                            text: message,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 5000
                        });

                    }
                    // if success
                    else if(response.status)
                    {   
                    
                        /*alert: function(message, title, callback) {*/
                        //var pageTracker = _gat._getTracker("UA-4509200-1");
                        //pageTracker._trackPageview('join/'+$('#tabmjoin .current a').text()+'/thankyou');
                        if(typeof _gaq != 'undefined'){
                            _gaq.push(['_trackPageview', 'join/'+$('#tabmjoin .current a').text()+'/thankyou']);
                        }
                        $.dialog.alert("<p>You will receive confirmation email shortly.</p><p>Sometimes confirmation emails may be sent into the Spam folder by your email system. If you do not see the confirmation email within a few minutes of registering, please thoroughly check your spam folder. If you don't locate it there, please contact us at info@openfilm.com.</p>", "Thank you for registering.", function(){
                            document.location.href = 'http://' + document.location.hostname + '/';
                            $('body').trigger('ajaxIndikatorShow',{
                                title: '<a href="/">' + i18n.m279 + '</a>'
                            });
                        }); 
                    }

                },
                url: '/join/' + global.formAction,
                dataType: "json",
                cache: false
            };
            _form.ajaxSubmit(options);
            return false;
        },
        invalidHandler: utils.formErrorAlert,
        /*highlight: utils.formErorHighlight,*/
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            login: {
                required: true,
                minlength: config.loginMinLength,
                maxlength: config.loginMaxLength,
                customRemote: {
                    url: '/join/standalone-validate/',
                    type: 'post'
                }
            },
            email: {
                required: true,
                email: true,
                customRemote: {
                    url: '/join/standalone-validate/',
                    type: 'post'
                }
            },
            password: {
                required: true,
                minlength: config.passwordMinLength,
               	maxlength: config.passwordMaxgfLength
            },
            discount: {
                minlength: 16,
                maxlength: 16,
                customRemote: {
                    url: '/join/standalone-validate/',
                    type: 'post',
                    actionAfter: function(data)
                    {
                        // TODO: turn off validator and credit card part
                        if(data.status && data.credit_card == '0')
                        {
                            var elem = $('#join_form_' + $('div.tab:visible').attr('id') + '_billing_fieldset');
                            global.bilingForm = elem.detach();
                        }
                        else
                        if(!data.status && global.bilingForm)
                        {
                            elemafter = $('#join_form_' + $('div.tab:visible').attr('id') + '_discount_fieldset');
                            elemafter.after(global.bilingForm);
                        }
                    }
                }
            },

            cctype: {
                required: true
            },
            ccnumber: {
                required: true
            },
            exp_month: {
                required: true
            },
            exp_year: {
                required: true
            },
            first_name: {
                required: true
            },
            last_name: {
                required: true
            },
            street_address: {
                required: true
            },
            city: {
                required: true
            },
            zip: {
                required: true
            },
            country: {
                required: true
            },
            state: {
                required: false
            }
        },
        messages: {
            login: {
                required: i18n.m197,
                minlength: i18n.m151.supplant({
                    number: config.loginMinLength
                }),
                maxlength: i18n.m152.supplant({
                    number:config.loginMaxLength
                })
            },
            email: {
                required: i18n.m197,
                email: i18n.m286
            },
            password: {
                required: i18n.m197,
                minlength: i18n.m287.supplant({
                    min:config.passwordMinLength,
                    max:config.passwordMaxLength
                })
            },
            discount: {
                minlength: i18n.m151.supplant({
                    number:16
                }),
                customRemote: function (res){
                    if(res.status == false)
                    {
                        return i18n.m418;
                    }
                }
            },
            cctype: {
                required: i18n.m197
            },
            ccnumber: {
                required: i18n.m197
            },
            exp_month: {
                required: i18n.m197
            },
            exp_year: {
                required: i18n.m197
            },
            first_name: {
                required: i18n.m197
            },
            last_name: {
                required: i18n.m197
            },
            street_address: {
                required: i18n.m197
            },
            city: {
                required: i18n.m197
            },
            zip: {
                required: i18n.m197
            },
            country: {
                required: i18n.m197
            }
        },
        errorPlacement: function(error, element) {
            //error.appendTo(element.next('div.error'));
            error.appendTo(element.parents('form').find('.error-' + element.attr('name')));
        }

    },
    loginForm: {
        submitHandler: function(form) {
            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');
            var options = {
                success: function(response)
                {
                    _form.trigger('submitAjaxIndikatorHide');
                    if(!response)
                    {
                    // SHOW error message such us "Server is busy"
                    /*var message = i18n.m357;
                        $.ajaxAlert({
                            title: '',
                            text: message,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 5000
                        });*/

                    }
                    else if(response.show_captcha)
                    {
                        $.captchaDialog({
                            action: function(){
                                /* отправляем эту фору _form */
                                _form.ajaxSubmit(options);
                            }
                        });
                    }
                    else if(!response.status)
                    {
                        // SHOW error message such us "invalid password"
                        var message = i18n.m357;
                        $.ajaxAlert({
                            title: '',
                            text: message,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 5000
                        });

                    }
                    // if success
                    else
                    {
                        document.location.href = 'http://' + window.location.hostname + redirectToOnSuccessLogin;
                        $('body').trigger('ajaxIndikatorShow',{
                            title: '<a href="/">' + i18n.m279 + '</a>'
                        });
                    }
                },
                url: '/login/',
                dataType: "json",
                cache: false
            };
            _form.ajaxSubmit(options);


            return false;
        },
        invalidHandler: utils.formErrorAlert,
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            login: {
                required: true/*,
                minlength: config.loginMinLength,
                maxlength: config.loginMaxLength*/
            },
            password: {
                required: true/*,
                minlength: config.passwordMinLength*/
            }/*,
              captcha_string: {
                required: true
              }*/
        },
        messages: {
            login: {
                required: i18n.m197/*,
                minlength: i18n.m151.supplant({
                    number: config.loginMinLength
                }),
                maxlength: i18n.m152.supplant({
                    number: config.loginMaxLength
                })*/
            },
            password: {
                required: i18n.m197/*,
                minlength: i18n.m287.supplant({
                    min:config.passwordMinLength,
                    max:config.passwordMaxLength
                })*/
            }/*,
              captcha_string: {
                required: i18n.m288
              }*/
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }

    },
    passwordRecoveryPanelForm: {
        submitHandler: function(form) {
            //$(form).ajaxSubmit(options);

            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');

            /*типа посылаем запрос и если все гуд*/
            setTimeout(function(){
                _form.trigger('submitAjaxIndikatorHide');
                /* очищаем форму */
                _form.find('a[href="#form_reset"]').trigger('click');
                /* закрываем панель */
                global.password_recovery.trigger('hide');

                $.dialog.alert('<p>' + i18n.m297 + '</p>', i18n.m294);

            },5000);
            return false;
        },
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            login: {
                required: true,
                minlength: config.loginMinLength,
                maxlength: config.loginMaxLength
            }
        },
        messages: {
            login: {
                required: i18n.m197,
                minlength: i18n.m151.supplant({
                    number: config.loginMinLength
                }),
                maxlength: i18n.m152.supplant({
                    number: config.loginMaxLength
                })
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }

    },
    passwordRecoveryForm: {
        submitHandler: function(form) {
            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');

            var options = {
                success: function(response)
                {
                    _form.trigger('submitAjaxIndikatorHide');
                    if(!response || !response.status)
                    {
                        var message = i18n.m385;
                        $.ajaxAlert({
                            title: '',
                            text: message,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 5000
                        });

                    }
                    // if success
                    else
                    {
                        _form.find('a[href="#form_reset"]').trigger('click');
                        $.dialog.alert('<p>' + i18n.m297 + '</p>', i18n.m294);
                    /*
                        document.location.href = document.location.href;
                        $('body').trigger('ajaxIndikatorShow',{
                            title: '<a href="/">' + i18n.m279 + '</a>'
                        });
                         */
                    }
                },
                url: '/recovery-password/',
                dataType: "json",
                cache: false
            };
            _form.ajaxSubmit(options);

            return false;
        },
        invalidHandler: utils.formErrorAlert,
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            login: {
                required: true/*,
                minlength: config.loginMinLength,
                maxlength: config.loginMaxLength*/
            },
            captcha_string: {
                required: true
            }
        },
        messages: {
            login: {
                required: i18n.m197/*,
                minlength: i18n.m151.supplant({
                    number: config.loginMinLength
                }),
                maxlength: i18n.m152.supplant({
                    number: config.loginMaxLength
                })*/
            },
            captcha_string: {
                required: i18n.m288
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }

    },
    passwordResetForm: {
        submitHandler: function(form) {
            //$(form).ajaxSubmit(options);

            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');

            var options = {
                success: function(response)
                {
                    _form.trigger('submitAjaxIndikatorHide');
                    if(!response || !response.status)
                    {
                        var message = i18n.m391;
                        $.ajaxAlert({
                            title: '',
                            text: message,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 5000
                        });
                    }
                    // if success
                    else
                    {
                        _form.trigger('submitAjaxIndikatorHide');
                        /* очищаем форму */
                        _form.find('a[href="#form_reset"]').trigger('click');
                        /* блокируем все поля в форме*/
                        _form.find('input').attr('disabled','disabled');
                        /* убиваем кнопку Reset */
                        _form.find('a[href="#form_reset"]').remove();
                        /* блокируем кнопку в форме*/
                        _form.find('[type="submit"]').attr('disabled','disabled');

                        $.dialog.alert('<p>' + i18n.m307 + '</p><p>' + i18n.m308 + '</p>', i18n.m300, function(){
                            document.location.href = '/login/';
                        /* открываем панель логина */
                        /*global.login_panel.trigger('slideIn');*/
                        });
                    }
                },
                url: document.location.href,
                dataType: "json",
                cache: false
            };
            _form.ajaxSubmit(options);

            return false;
        },
        invalidHandler: utils.formErrorAlert,
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            password: {
                required: true,
                minlength: config.passwordMinLength,
                maxlength: config.passwordMaxLength
            },
            confirm_password: {
                required: true,
                minlength: config.passwordMinLength,
                maxlength: config.passwordMaxLength
            }
        },
        messages: {
            password: {
                required: i18n.m197,
                minlength: i18n.m151.supplant({
                    number:config.passwordMinLength
                }),
                maxlength: i18n.m152.supplant({
                    number:config.passwordMaxLength
                })
            },
            confirm_password: {
                required: i18n.m197,
                minlength: i18n.m151.supplant({
                    number:config.passwordMinLength
                }),
                maxlength: i18n.m152.supplant({
                    number:config.passwordMaxLength
                })
            }
        },
        errorPlacement: function(error, element) {
            //error.appendTo(element.next('div.error'));
            error.appendTo(element.parents('form').find('.error-' + element.attr('name')));
        }

    },
    restrictionPasswordConfirmationForm: {
        submitHandler: function(form) {
            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');

            var options = {
                success: function(response)
                {
                    _form.trigger('submitAjaxIndikatorHide');
                    if(!response.status)
                    {
                        var message = i18n.m557;
                        $.ajaxAlert({
                            title: '',
                            text: message,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 5000
                        });
                    }
                    else
                    {
                        document.location = response.url;
                    }
                 },
                dataType: "json",
                cache: false
            };
            _form.ajaxSubmit(options);            
            return false;
        },
        invalidHandler: utils.formErrorAlert,
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            password: {
                required: true,
                minlength: config.passwordMinLength,
                maxlength: config.passwordMaxLength//,
//                customRemote: {
//                    type: 'post'
//                }
            }
        },
        messages: {
            password: {
                required: i18n.m197,
                minlength: i18n.m151.supplant({
                    number:config.passwordMinLength
                }),
                maxlength: i18n.m152.supplant({
                    number:config.passwordMaxLength
                })
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }

    },
    confirmEmailForm: {
        submitHandler: function(form) {
            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');

            var options = {
                success: function(response)
                {
                    _form.trigger('submitAjaxIndikatorHide');
                    if(!response || !response.status) {
                        var message = i18n.m385;
                        $.ajaxAlert({
                            title: '',
                            text: message,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 5000
                        });

                    }else {
                        if (response.status == 1) {
                            $.dialog.alert('<p>' + i18n.m699 + '</p>', i18n.m698);
                        }
                    }
                },
                url: '/join/confirm-email/',
                dataType: "json",
                cache: false
            };
            _form.ajaxSubmit(options);

            return false;
        },
        invalidHandler: utils.formErrorAlert,
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            email: {
                email: true,
                required: true,
                customRemote: {
                    url: '/join/email-validate/',
                    type: 'post'
                }
            }
        },
        messages: {
            email: {
                email: i18n.m286
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }

    },
    captchaForm: {
        submitHandler: function(form) {

            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');
            _form.ajaxSubmit(
            {
                success: function(response)
                {
                    _form.trigger('submitAjaxIndikatorHide');
                    if(!response.status)
                    {
                        //var message = i18n.m357;
                        /*$.ajaxAlert({
                            title: '',
                            text: message,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 5000
                        });*/
                        $('a[href="#captcha_reload"]',_form).trigger('click');
                    }
                    // if success
                    else
                    {/* закрываем диалог */
                        $.fn.colorbox.close();
                        if($.isFunction(formActions.captchaForm.captchaAction)){
                            formActions.captchaForm.captchaAction();
                        }
                    }
                    _form.trigger('submitAjaxIndikatorHide');
                },
                url: '/check-captcha/' + page_options.captchaType,
                dataType: "json",
                cache: false
            });
            return false;
        },
        /*invalidHandler: utils.formErrorAlert,*/
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            captcha_input: {
                required: true
            }
        },
        messages: {
            captcha_input: {
                required: i18n.m288
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }
    },
    chatQuestionForm: {
        
        submitHandler: function (form) {
            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');
            _form.ajaxSubmit(
            {
                success: function(response)
                {
                    _form.trigger('submitAjaxIndikatorHide');
                    if(!response || !response.status)
                    {
                        var message = i18n.m62;
                        
                        $.ajaxAlert({
                            title: '',
                            text: message,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 5000
                        });
                    }
                    // if success
                    else
                    {
                        _form.trigger('submitAjaxIndikatorHide');

                        $.ajaxAlert({
                            title: i18n.m60,
                            text: i18n.m601,
                            styleClass: 'message',
                            buttonClose: true,
                            speedClose: 3000
                        });

                        //$('.listQuestions').html(response.html);
                        var api = $('.listQuestions').data('jsp');
                        api.getContentPane().html(response.html);
                        api.reinitialise();
                        $('#asc_question').val('');
                        $('#chat_list .voteValue').initVote({
                            action: actions.chatVote
                        });
                        $('#chat_list a.userThumb').thumbLoadControl();
                        $('#chat_list .box  h2 span').html(response.count);
                    }
                    _form.trigger('submitAjaxIndikatorHide');
                },
                url: _form.action,
                dataType: "json",
                cache: false
            });
            return false;
        },
        /*invalidHandler: utils.formErrorAlert,*/
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            question: {
                required: true,
                maxlength: 1000
            }
        },
        messages: {
            question: {
                required: i18n.m600,
                maxlength: i18n.m636
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }
    },
    gimSubmitForm: {
        submitHandler: function(form) {
            var _form = $(form);
            _form.trigger('ajaxIndikatorShow');
            
            var submitToServer = function(_form){
                _form.ajaxSubmit({
                    success: function(response) {
                        _form.trigger('submitAjaxIndikatorHide');
                        if(!response || !response.status) {
                            $.ajaxAlert({
                                title: '',
                                text: i18n.m62,
                                styleClass: 'error',
                                buttonClose: true,
                                speedClose: 5000
                            });
                        } else {
                            if(typeof _gaq != 'undefined'){
                                _gaq.push(['_trackPageview', '/studio/gim-submit']);
                            }

                            if (response.message == 1) {
                                message = i18n.m627 + ' <a href="http://' + window.location.hostname + '/studio/' + $('.transplants').html() + '">' + i18n.m628 + '</a>.';
                            } else {
                                message = i18n.m1404;
                            }

                            $.dialog.alert(message, i18n.m803, function(){
                                document.location.href = 'http://' + document.location.hostname + '/studio/' + $('.transplants').html();
                            });
                        }
                        _form.trigger('submitAjaxIndikatorHide');
                        _form.trigger('ajaxIndikatorHide');
                    },
                    url: '/studio/submit/',
                    dataType: "json",
                    cache: false
                });
            }
            
            if($("input[name='payment_type']:checked").val() == 1) {
                $.ajax({
                    url: '/studio/payment/',
                    type: 'POST',
                    data: {
                        video_id: $("select[name='film']").val(),
                        city: $("input[name='city']").val(),
                        country: $("select[name='country']").val(),
                        first_name: $("input[name='first_name']").val(),
                        last_name: $("input[name='last_name']").val(),
                        zip: $("input[name='zip']").val(),
                        street_address: $("input[name='billing_address']").val(),
                        ccnumber: $("input[name='ccnumber']").val(),
                        card_type: $("select[name='card_type']").val(),
                        exp_month: $("select[name='exp_month']").val(),
                        exp_year: $("select[name='exp_year']").val(),
                        state: $("select[name='states_us']").val(),
                        state_ca: $("select[name='states_ca']").val()
                    },
                    dataType: 'json',
                    success: function(data){
                        if (data.error == 1)
                        {
                            _form.trigger('ajaxIndikatorHide');
                            $('#cybersource_error em.error').html(eval('i18n.m' + data.message)).css('display','block');
                        } else if (data.error == 2) {
                            _form.trigger('ajaxIndikatorHide');
                            $.ajaxAlert({
                                title: i18n.m62,
                                text:i18n.m1404,
                                styleClass: 'error',
                                buttonClose: true,
                                speedClose: 4000
                            });
                        }
                        else
                        {
                            //var pageTracker = _gat._getTracker("UA-4509200-1");
                            //pageTracker._trackPageview('/studio/gim-submit');
                            submitToServer(_form); 
                        }
                    },
                    error: function() {
                        $.ajaxAlert({
                            title: i18n.m62,
                            text:i18n.m518,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 4000
                        });
                        _form.trigger('ajaxIndikatorHide');
                    },
                    beforeSend: function(){
                        _form.trigger('ajaxIndikatorShow');
                    }
                });
            } else {
                submitToServer(_form);
            }
        },
        invalidHandler: utils.formErrorAlert,
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            name: {
                required: true,
                maxlength: 100
            },
            film: {
                required: true
            },
            company: {
                maxlength: 255
            },
            address: {
                maxlength: 255
            },
            phone: {
                required: true,
                maxlength: 50
            },
            /* Credit Card Data */
            card_type: {
                required: function(){
                    return $("input[name='payment_type']:checked").val() == 1
                }
            },
            ccnumber: {
                required: function(){
                    return $("input[name='payment_type']:checked").val() == 1
                },
                creditcard: true
            },
            exp_year: {
                required: function(){
                    return $("input[name='payment_type']:checked").val() == 1
                }
                /*expiration_date: true*/
            },
            first_name: {
                required: function(){
                    return $("input[name='payment_type']:checked").val() == 1
                },
                maxlength: 50
            },
            last_name: {
                required: function(){
                    return $("input[name='payment_type']:checked").val() == 1
                },
                maxlength: 50
            },
            billing_address: {
                required: function(){
                    return $("input[name='payment_type']:checked").val() == 1
                },
                maxlength: 255
            },
            city: {
                required: function(){
                    return $("input[name='payment_type']:checked").val() == 1
                },
                maxlength: 70
            },
            zip: {
                required: function(){
                    return $("input[name='payment_type']:checked").val() == 1
                },
                maxlength: 20
            },
            
            without_a_box: {
                required: function(){
                    return $("input[name='payment_type']:checked").val() == 2
                }
            },

            film_date_completion: {
                required: true,
                date: true
            },
            film_school_name: {
                required: function(){
                    return $("input[name='film_student']:checked").length > 0
                },
                maxlength: 100
            },
            film_festival_name: {
                maxlength: 150
            },
            film_screening_date: {
                date: true
            },
            director_name: {
                required: true,
                maxlength: 100
            },
            director_email: {
                required: true,
                email: true
            },
            distributor_first_name: {
                required: function(){
                    return $("input[name='distributor']:checked").length > 0
                },
                maxlength: 100
            },
            distributor_last_name: {
                required: function(){
                    return $("input[name='distributor']:checked").length > 0
                },
                maxlength: 100
            },
            distributor_email: {
                required: function(){
                    return $("input[name='distributor']:checked").length > 0
                },
                email: function(){
                    return $("input[name='distributor']:checked").length > 0
                }
            },
            distributor_title: {
                maxlength: 100
            },
            distributor_company: {
                maxlength: 100
            },
            distributor_country: {
                maxlength: 100
            },
            distributor_address: {
                maxlength: 200
            },
            distributor_phone: {
                maxlength: 100
            },
            distributor_fax: {
                maxlength: 100
            },
            sales_agent_first_name: {
                required: function(){
                    return $("input[name='sales_agent']:checked").length > 0
                },
                maxlength: 100
            },
            sales_agent_last_name: {
                required: function(){
                    return $("input[name='sales_agent']:checked").length > 0
                },
                maxlength: 100
            },
            sales_agent_email: {
                required: function(){
                    return $("input[name='sales_agent']:checked").length > 0
                },
                email: function(){
                    return $("input[name='sales_agent']:checked").length > 0
                }
            },
            sales_agent_title: {
                maxlength: 100
            },
            sales_agent_company: {
                maxlength: 100
            },
            sales_agent_country: {
                maxlength: 100
            },
            sales_agent_address: {
                maxlength: 200
            },
            sales_agent_phone: {
                maxlength: 100
            },
            sales_agent_fax: {
                maxlength: 100
            },
            producer_first_name: {
                required: function(){
                    return $("input[name='producer']:checked").length > 0
                },
                maxlength: 100
            },
            producer_last_name: {
                required: function(){
                    return $("input[name='producer']:checked").length > 0
                },
                maxlength: 100
            },
            producer_email: {
                required: function(){
                    return $("input[name='producer']:checked").length > 0
                },
                email: function(){
                    return $("input[name='producer']:checked").length > 0
                }
            },
            producer_title: {
                maxlength: 100
            },
            producer_company: {
                maxlength: 100
            },
            producer_country: {
                maxlength: 100
            },
            producer_address: {
                maxlength: 200
            },
            producer_phone: {
                maxlength: 100
            },
            producer_fax: {
                maxlength: 100
            },
            lead_actor: {
                maxlength: 100
            },
            supporting_actor: {
                maxlength: 100
            },
            voice_talent: {
                maxlength: 100
            },
            agent_first_name: {
                required: function(){
                    return $("input[name='agent']:checked").length > 0
                },
                maxlength: 100
            },
            agent_last_name: {
                required: function(){
                    return $("input[name='agent']:checked").length > 0
                },
                maxlength: 100
            },
            agent_email: {
                required: function(){
                    return $("input[name='agent']:checked").length > 0
                },
                email: function(){
                    return $("input[name='agent']:checked").length > 0
                }
            },
            agent_title: {
                maxlength: 100
            },
            agent_company: {
                maxlength: 100
            },
            agent_country: {
                maxlength: 100
            },
            agent_address: {
                maxlength: 200
            },
            agent_phone: {
                maxlength: 100
            },
            agent_fax: {
                maxlength: 100
            },
            manager_first_name: {
                required: function(){
                    return $("input[name='manager']:checked").length > 0
                },
                maxlength: 100
            },
            manager_last_name: {
                required: function(){
                    return $("input[name='manager']:checked").length > 0
                },
                maxlength: 100
            },
            manager_email: {
                required: function(){
                    return $("input[name='manager']:checked").length > 0
                },
                email: function(){
                    return $("input[name='manager']:checked").length > 0
                }
            },
            manager_title: {
                maxlength: 100
            },
            manager_company: {
                maxlength: 100
            },
            manager_country: {
                maxlength: 100
            },
            manager_address: {
                maxlength: 200
            },
            manager_phone: {
                maxlength: 100
            },
            manager_fax: {
                maxlength: 100
            },
            publicist_first_name: {
                required: function(){
                    return $("input[name='publicist']:checked").length > 0
                },
                maxlength: 100
            },
            publicist_last_name: {
                required: function(){
                    return $("input[name='publicist']:checked").length > 0
                },
                maxlength: 100
            },
            publicist_email: {
                required: function(){
                    return $("input[name='publicist']:checked").length > 0
                },
                email: function(){
                    return $("input[name='publicist']:checked").length > 0
                }
            },
            publicist_title: {
                maxlength: 100
            },
            publicist_company: {
                maxlength: 100
            },
            publicist_country: {
                maxlength: 100
            },
            publicist_address: {
                maxlength: 200
            },
            publicist_phone: {
                maxlength: 100
            },
            publicist_fax: {
                maxlength: 100
            }
        },
        
        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }
    },
    thewallManageFilmFestival: {
        submitHandler: function(form) {
            form.submit();
        },
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            film_festival_title: {
                required: true
            },
            alias: {
                required: true,
                customRemote: {
                    url: '/thewall/film-festivals/standalone-validate/',
                    type: 'post',
                    data: {
                        film_festival_id: function() {
                            return $('#film_festival_id').val();
                        }
                    }
                }
            },
            "film_festival_category[]": 'required',
            "film_festival_runtime[]": 'required',
            requirements: {
                required: true
            },
            awards: {
                required: true
            },
            user_id: {
                number: true,
                required: false,
                customRemote: {
                    url: '/thewall/film-festivals/standalone-validate/',
                    type: 'post',
                    data: {
                        user_id: function() {
                            return $('#user_id').val();
                        }
                    }
                }
            },
            channel_id: {
                number: true,
                required: false,
                customRemote: {
                    url: '/thewall/film-festivals/standalone-validate/',
                    type: 'post',
                    data: {
                        channel_id: function() {
                            return $('#channel_id').val();
                        }
                    }
                }
            },
            region: {
                required: true
            },
            country: {
                required: true
            },
            city: {
                required: true
            },
            post_address: {
                required: true
            },
            contact_person: {
                required: true
            },
            email: {
                required: true,
                email: true
            },
            phone: {
                required: true
            },
            website: {
                required: true
            },
            dt_begin: {
                required: true,
                date: true
            },
            dt_end: {
                required: true,
                date: true
            },
            dt_deadline: {
                required: true,
                date: true
            },
            description: {
                required: true
            },
            established: {
                number: true
            },
            attendance: {
                number: true
            }
        },
        
        errorPlacement: function(error, element) {
            if (element.parent('.group').parent('.groupBox').length > 0) {
                error.appendTo(element.parent('.group').parent('.groupBox').next('div.error'));
            } else {
                error.appendTo(element.next('div.error'));
            }
        }
    },
    thewallOpenfilmSpotlight: {
        submitHandler: function(form) {
            form.submit();
        },
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            spotlight_class: {
                required: true
            },
            spotlight_dt: {
                required: true
            },
            spotlight_title: {
                required: true
            },
            description: {
                required: true
            }
        },

        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }
    },
    thewallInTheNews: {
        submitHandler: function(form) {
            form.submit();
        },
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            spotlight_class: {
                required: true
            },
            spotlight_dt: {
                required: true
            },
            spotlight_title: {
                required: true
            },
            description: {
                required: true
            },
            link: {
                required: true
            }
        },

        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }
    },
    openfilmFeedbackForm:{
    
        submitHandler: function(form) {
            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');
            _form.ajaxSubmit(
                {
                    success: function() {
                        _form.trigger('submitAjaxIndikatorHide');
                        $.ajaxAlert({
                            title: i18n.m552,
                            text:i18n.m553,
                            styleClass: 'message',
                            buttonClose: true,
                            speedClose: 4000
                        });
                        $('#cboxClose').trigger('click');
                    },
                    dataType:'json',
                    cache: false
                }
           )
        },
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            email: {
                email: true
            },
            feedback: {
                maxlength: 1000,
                minlength: 2,
                required: true
            }
        },
        messages: {
             email: {
                email: i18n.m286
             },
             feedback: {
                
                maxlength: i18n.m151.supplant({
                    number:1000
                }),
                minlength: i18n.m151.supplant({
                    number:2
                }),
                required: i18n.m197
             }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }
    },
    ffSendEmail:{
		submitHandler: function(form) {
			var _form = $(form);
			page_options = {captchaType: 1};
			var film_festival_id = $('#id_filmfestival').val();
			
			$.captchaDialog({
				action: function(){
					_form.trigger('submitAjaxIndikatorShow');
					_form.ajaxSubmit({
							success: function() {
								_form.trigger('submitAjaxIndikatorHide');
								$.ajaxAlert({
									title: i18n.m552,
									text:i18n.m184,
									styleClass: 'message',
									buttonClose: true,
									speedClose: 4000
								});
								//$('#cboxClose').trigger('click');
							},
							dataType:'json',
							cache: false,
							url: '/film-festivals/message/' + film_festival_id + '/'
					})
                }
            });
            return;
        },
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            user_name: {
                required: true,
                maxlength: 100,
                minlength: 2
            },
            title: {
                required: true,
                maxlength: 100,
                minlength: 2
            },
            body: {
                maxlength: 10000,
                minlength: 2,
                required: true
            }
        },
        messages: {
            user_name: {
                 maxlength: i18n.m151.supplant({
                    number:100
                }),
                minlength: i18n.m151.supplant({
                    number:2
                }),
                required: i18n.m197
            },
             title: {
                maxlength: i18n.m151.supplant({
                    number:100
                }),
                minlength: i18n.m151.supplant({
                    number:2
                }),
                required: i18n.m197
             },
             body: {
                
                maxlength: i18n.m151.supplant({
                    number:10000
                }),
                minlength: i18n.m151.supplant({
                    number:2
                }),
                required: i18n.m197
             }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next('div.error'));
        }
    },
    festivalLogoForm: {
        submitHandler: function(form) {

            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');


            var options = {
                success: function(response)
                {
                    _form.trigger('submitAjaxIndikatorHide');

                    //alert(response.status);
                    if(response.status)
                    {
                        //_form.trigger('submitDisable');

                        // получить с сервера
                        var new_src = response.src + '?t=' + Math.random(); // для того что бы выполнялся onload и не кешировало

                        global.imageCrop.src = new_src;

                        var iWidth = _form.find('input[name="w"]').val(),
                        iHeight = _form.find('input[name="h"]').val();
                        var params = {
                            orientation: 'bottom right',
                            image: global.imageCrop,
                            form: _form,
                            previewNewSRC: new_src,
                            previewThumb: $('.previewThumb',_form),
                            previewBox: $('.previewBox',_form),
                            previewWidth: iWidth,
                            previewHeight: iHeight,
                            aspectRatio: iWidth/iHeight,
                            formActionURL: '/dashboard/images/crop/' + _form.attr('action') + '/' + _form.find('input[name="item_id"]').val()
                        }
                        global.imageCrop.onload = function(){
                            utils.cropThumbBox(params, formActions.festivalLogoCropForm);
                        }
                    //_form.trigger('submitEnable');
                    }
                    else
                    {
                        $.ajaxAlert({
                            title: '',
                            text: i18n.m534,
                            styleClass: 'error',
                            buttonClose: true,
                            speedClose: 3000
                        });
                    }

                },
                url: "/dashboard/images/upload/" + _form.attr('action'),
                dataType: "json",
                cache: false
            };

            _form.ajaxSubmit(options);
            return false;
        },
        invalidHandler: utils.formErrorAlert,
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            file: {
                required: true,
                accept: "jpeg|jpg|png|gif"

            }
        },
        messages: {
            file: {
                required: i18n.m346,
                accept: i18n.m340
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.parents('form').find('.error-' + element.attr('name')));
        }

    },
    festivalLogoCropForm: {
        submitHandler: function(form) {

            var _form = $(form);

            _box = $('#stick_box'),
            _thumb_box = _box[0].creator,
            _thumb = $('img',_thumb_box);
            _thumb_form = _thumb_box.parents('form');


            // закрываем слой
            _thumb_box.trigger('stickBoxHide');

            // устанавливаем флаг что бы не возвращала старую картинку
            _thumb[0].changed = true;
            // очищаем тамб
            _thumb[0].src = '/design/images/1px_t.gif';

            // скролим до формы загрузки
            box_fx.boxScrollToTop(_thumb_form, 40)


            var options = {
                success: function(response)
                {
                    if(response && response.status)
                    {
                        // получаем адрес к картинке
                        var new_src = response.src;
                        //'http://i1.openfilm.com/_data_files/creator_data/79/100x75_Openfilm.jpg';
                        // показываем новый тамб
                        _thumb.hide(function(){
                            _thumb[0].src = new_src;

                            _thumb.fadeIn(function(){
                                // разлочим кнопку на форме загрузки
                                _thumb_form.trigger('submitEnable');
                                // выводим сообщение
                                $.ajaxAlert({
                                    title: i18n.m341,
                                    text: i18n.m341,
                                    styleClass: 'message',
                                    buttonClose: true,
                                    speedClose: 5000,
                                    orientation: 'center'
                                });
                            });
                        });
                    }
                    else
                    {
                // TODO: set error
                //если жопа - возвращаем старую картинку
                //_thumb[0].src = _thumb[0].oldSRC;
                }

                },
                url: _form.attr('action'),
                dataType: "json",
                cache: false
            };

            _form.ajaxSubmit(options);

            return false;
        },
        invalidHandler: utils.formErrorAlert,
        ignoreTitle: true,
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            x1: {
                required: true,
                number: true
            },
            y1: {
                required: true,
                number: true
            },
            x2: {
                required: true,
                number: true
            },
            y2: {
                required: true,
                number: true
            },
            w: {
                required: true,
                number: true
            },
            h: {
                required: true,
                number: true
            }
        },
        errorPlacement: function(error, element) {}
    },
    surveyMembershipForm:{
    
        submitHandler: function(form) {
            var _form = $(form);
            _form.trigger('submitAjaxIndikatorShow');
            _form.ajaxSubmit(
                {
                    success: function(response) {
                        _form.trigger('submitAjaxIndikatorHide');

                        if(response && response.status) {
                            /*$.ajaxAlert({
                                title: i18n.m60,
                                text: i18n.m1614,
                                styleClass: 'message',
                                buttonClose: true,
                                speedClose: 4000
                            });*/

                            $.dialog.alert(i18n.m1614, i18n.m60, function(){
                                document.location.href = document.location.href;
                            });

                            _form.find('a[href="#form_reset"]').trigger('click');
                        } else {
                            $.ajaxAlert({
                                title: i18n.m62,
                                text: response.message,
                                styleClass: 'message',
                                buttonClose: true,
                                speedClose: 4000
                            });
                        }
                    },
                    dataType:'json',
                    cache: false
                }
           )
        },
        focusInvalid: false,
        focusCleanup: true,
        rules: {
            'industry_participation[]': {
                required: true
            },
            industry_participation_other: {
                required: function() {
                    return $("input[id='industry_participation_28']:checked").length > 0
                },
                minlength: 3
            },
            get_it_made: {
                required: true
            },
            webcam_chats: {
                required: true
            },
            spotlight: {
                required: true
            },
            premium_membership: {
                required: true
            },
            channel_customization: {
                required: true
            },
            quality_content: {
                required: true
            },
            'openfilm_participation[]': {
                required: true
            },
            openfilm_participation_other: {
                required: function() {
                    return $("input[id='openfilm_participation_13']:checked").length > 0
                },
                minlength: 3
            },
            'learn_about_openfilm[]': {
                required: true
            },
            learn_about_openfilm_other: {
                required: function() {
                    return $("input[id='learn_about_openfilm_11']:checked").length > 0
                },
                minlength: 3
            },
            often_visit: {
                required: true
            },
            'time_of_day[]': {
                required: true
            },
            'resources[]': {
                required: true
            },
            age: {
                required: true
            },
            education_level: {
                required: true
            },
            education_level_other: {
                required: function() {
                    return $("input[id='education_level_1602']:checked").length > 0
                },
                minlength: 3
            },
            annual_income: {
                required: true
            }
        },
        errorPlacement: function(error, element) {
            if (!element.parents('div.otherValue').length) {
                error.appendTo(element.nextAll('div.error'));
            } else {
                error.appendTo(element.parents('div.otherValue').nextAll('div.error'));
            }
        }
    }
};

function displayCompanionBanners(banners) {
    tmDisplayBanner(banners, "companionBoard", 300, 250);
    global.addPanel.trigger('slideIn');/*.show()*/
}
function openAddThisWindow(url, title){
    return addthis_open(document.body, "more", url, title);
}
jQuery.validator.addMethod("customRemote",
    function(value, element, param)
    {
        if (this.optional(element)) return "dependency-mismatch";

        var previous = this.previousValue(element);
        if (!this.settings.messages[element.name])
        {
            this.settings.messages[element.name] = {};
        }
        
        //previous.originalMessage = this.settings.messages[element.name].customRemote;
        
        function isInt(x)
        {
            var y=parseInt(x);
            if (isNaN(y)) return false;
            return x==y && x.toString()==y.toString();
        }
        // TODO: 
        if(isInt(previous.message))
        {
            str = 'i18n.m' + previous.message;
            previous.message = eval(str);
        }

        this.settings.messages[element.name].customRemote = previous.message;

        param = typeof param == "string" && {
            url:param
        } || param;
        
        if ( previous.old !== value )
        {
            previous.old = value;
            var validator = this;
            this.startRequest(element);
            var data = {};
            data[element.name] = value;

            $.ajax($.extend(true, {
                url: param,
                mode: "abort",
                port: "validate" + element.name,
                dataType: "json",
                data: data,
                success: function(response)
                {

                    //validator.settings.messages[element.name].customRemote = previous.originalMessage;
                    // var valid = response;// === true;

                    valid = response.status;
                    
                    if($.isFunction(param.actionAfter))
                    {
                        param.actionAfter(response);
                    }
                    //   var errors = {};
                    //  message = validator.defaultMessage( element, "customRemote" );
                    // errors[element.name] = $.isFunction(message) ? message(response) : message ;
                    //validator.showErrors(errors);
                    
                    
                    if (valid)
                    {
                        var submitted = validator.formSubmitted;
                        validator.prepareElement(element);
                        validator.formSubmitted = submitted;
                        validator.successList.push(element);
                        validator.showErrors();
                    }
                    else
                    {
                        var errors = {};
                        var message =  (previous.message = response.message || validator.defaultMessage( element, "customRemote" ));
                        str = 'i18n.m' + message;
                        mess = eval(str);
                        errors[element.name] = mess;


                        validator.showErrors(errors);
                    //return false;
                    }
                    //console.log(previous.valid);
                    
                    previous.valid = valid;
                    validator.stopRequest(element, valid);
                }
            }, param));
            return "pending";

        }
        else if( this.pending[element.name] )
        {
            return "pending";
        }

        return previous.valid;
    }
);

jQuery.validator.addMethod("ziprange", function(value, element) {
    return this.optional(element) || /^[a-zA-Z0-9\-\s]*$/.test(value);
}, eval('i18n.m520'));

jQuery.validator.addMethod("checkTags", function(value, element, params) {
    return this.optional(element) || /^(\s(?!\s)|-(?!-)|\*|[a-z0-9]){3,}(,\s?(\s(?!\s)|-(?!-)|\*|[a-z0-9]){3,})*$/i.test(value.replace(/^\s*(.*?)\s*$/, "$1"));
}, eval('i18n.m525'));
// ^[\-\*\w]{3,}( [\-\*\w]{3,})*(, ?[\-\*\w]{3,}( [\-\*\w]{3,})*)*$
