var Edit = function (elem,isedit) { 
	if(isedit==="True") {
		elem.className = "TrueOver";
	}
};
var Edit2 = function (elem,isedit) { 
	if(isedit==="True") {
		elem.className = "True";
	}
};

//Скрипт с главной
if (top!==self) {
 top.window.location.href=FullPrefix;
}

var jsddm_timeout    = 500;
var jsddm_closetimer = 0;
var jsddm_ddmenuitem = 0;

function jsddm_close() {
  if(jsddm_ddmenuitem) {
    jsddm_ddmenuitem.find('ul').hide();
    jsddm_ddmenuitem.find('img').hide();
    jsddm_ddmenuitem.children('a').css('background', '#C60C31');
  }
}


function jsddm_timer() {
  jsddm_closetimer = window.setTimeout(jsddm_close, jsddm_timeout);
}

function jsddm_canceltimer() {
  if(jsddm_closetimer) { 
    window.clearTimeout(jsddm_closetimer);
    jsddm_closetimer = null;
  }
}

function jsddm_open() {
  jsddm_canceltimer();
  jsddm_close();
  jsddm_ddmenuitem = $(this);
  jsddm_ddmenuitem.find('ul').show();
  jsddm_ddmenuitem.find('img').show();
  jsddm_ddmenuitem.children('a').css('background', '#006643');
}


$(document).ready(function(){
  $('ul.jsddm > li').bind('mouseover', jsddm_open);
  $('ul.jsddm > li').bind('mouseout',  jsddm_timer);
});

document.onclick = jsddm_close;
/////////////////////////
var printwindow = function () {
 $('#printContent').html($('.mainContent').html());
 $('.printUrl').html(document.location.href);
 $('.mainTable').hide();
 $('.printWindow').show();
};
var printWindow = printwindow;
var unprintwindow = function () {
 $('#printContent').html('');
 $('.mainTable').show();
 $('.printWindow').hide();			 
};


$.fx.speeds._default = 500;
//Диалоговые окна
var Dialogs = function () {
this.dialog_stack = [];
this.url_stack = [];
this.refresh_stack = [];
this.dialog_id = 0;
this.DialogToggleModal = function(modal)
{
    if (top.Dialogs.dialog_stack.length>0) {
        var d = top.Dialogs.dialog_stack[top.Dialogs.dialog_stack.length-1];
        top.$(d).dialog('option','modal',modal);
    }
};
this.OpenFrameDialog = function (url,title,width,height) {
    url = top.Dialogs.GetRefreshedUrl(url);
    top.Dialogs.DialogToggleModal(false);
    var dialog = top.document.createElement('div');
    var refresh = false;
    dialog.id = '_modaldialog'+top.Dialogs.dialog_id++;
    top.Dialogs.dialog_stack.push(dialog);
    top.Dialogs.url_stack.push(url);
    top.Dialogs.refresh_stack.push(refresh);
    top.$(dialog).dialog({
		autoOpen: true,
		width: width,
        height: height,
		modal: true,
		show: 'clip',
		hide: 'clip',
		title: title,
		stack: true,
		start: function() {
		    var d = top.Dialogs.dialog_stack[top.Dialogs.dialog_stack.length-1];
		    top.$(d).children('iframe')[0].style.display = 'none';
		},
		stop: function() {
		    var d = top.Dialogs.dialog_stack[top.Dialogs.dialog_stack.length-1];
		    top.$(d).children('iframe')[0].style.display = 'block';
		},
		beforeclose: function() { 
		    var dialog = top.Dialogs.dialog_stack[top.Dialogs.dialog_stack.length-1];		    
		    dialog.innerHTML='';
		    //top.$(dialog).contents().css('display:none');
		    return true;		
		},
		close: function() {
		    var dialog = top.Dialogs.dialog_stack.pop();
            //var url = top.Dialogs.url_stack.pop();
            var refresh = top.Dialogs.refresh_stack.pop();
            if (refresh) {
                top.Dialogs.RefreshDialog();
            }
            top.$(dialog).detach();
            top.Dialogs.DialogToggleModal(true);
		},
		open: function() {
		    top.window.setTimeout(function() {
                var h = "<table style='width:95%;height:95%;border:0;' title='Идёт загрузка, пожалуйста подождите.'><tr style='height:100%'><td style='width:100%;vertical-align:middle' align='center'><img src='img/progress.gif'/></td></tr></table>";
		        var i = top.Dialogs.dialog_stack.length-1;
                top.Dialogs.dialog_stack[i].innerHTML = h;
		        var frame = top.document.createElement('iframe');
		        frame.style.width = '100%';
		        frame.style.height = '100%';
		        frame.style.border = 0;
		        frame.style.borderWidth = 0;
		        frame.frameBorder = 0;
		        frame.setAttribute('frameBorder', 0);
		        frame.src = top.Dialogs.url_stack[i];
		        frame.style.display = 'none';
		        top.Dialogs.dialog_stack[i].appendChild(frame);
		        top.$(frame).load(function() {
		            top.$(this).parent().find('table').css('display','none');
		            top.$(this).contents().find('.juibutton',top.document).button();
		            top.$(this).css('display','block');		            
		            var $header = top.$(this).contents().find('.header');
		            var $content = top.$(this).contents().find('.content');
		            var $footer = top.$(this).contents().find('.footer');
		            $content.css('top',$header.height()+3+'px');
		            $content.css('bottom',$footer.height()+3+'px');
		            top.Dialogs.AddToPostBackAndSubmit(top.$(this).contents().find('form'),top.Dialogs.ShowReloadDialog);
		        });

		     },top.$.fx.speeds._default+100);
		    return true;
	    }
	});
};
this.ShowReloadDialog = function() {
  if ( top.Dialogs.dialog_stack.length > 0 ) {
    var d = top.Dialogs.dialog_stack[top.Dialogs.dialog_stack.length-1];
	top.$(d).children('iframe').css('display','none');
	top.$(d).children('table').css('display','');
	return true;
  }
};
this.GetRefreshedUrl = function (url) {
     var str = url;
     if ( str.indexOf('?') < 0 ) {
        str += '?refresh=' + Math.random();
     } else {
        var pos = str.indexOf('&refresh=');
        if (pos<0) {
            str += '&refresh=' + Math.random();
        } else {
            str = str.substring(0,pos) + '&refresh=' + Math.random();
        }
     }
     return str;
};
this.RefreshDialog = function () {
  if ( top.Dialogs.dialog_stack.length > 0 ) {
     var $frame = top.$(top.Dialogs.dialog_stack[top.Dialogs.dialog_stack.length-1]).children('iframe');
     var surl = $frame.attr('src');
     if ($frame.length>0){
        if ($frame[0].contentWindow){
            surl = $frame[0].contentWindow.location.href;
        }
     }
     $frame.attr('src', top.Dialogs.GetRefreshedUrl(surl)); 
  } else {
     window.setTimeout(function () {
         window.location.href = window.location.href;
     }, top.$.fx.speeds._default + 100);
  }
  top.Dialogs.ShowReloadDialog();
};

this.SetDialogRefresh = function(refresh, cascade) {
  var i = 0;
  if ( top.Dialogs.refresh_stack.length > 0 ) {
     if (!cascade) {
       top.Dialogs.refresh_stack[top.Dialogs.refresh_stack.length-1] = refresh; 
     } else {
        for (i=0;i<top.Dialogs.refresh_stack.length;i++) {
            top.Dialogs.refresh_stack[i] = refresh;
        }
     }
  }
};

this.CloseFrameDialog = function (refresh) {
 var i = 0;
 if (top.Dialogs.dialog_stack.length>0) {
    for(i=0;i<top.Dialogs.dialog_stack.length;i++) {
        if (top.Dialogs.refresh_stack[i]) {
            top.Dialogs.refresh_stack[i] = refresh || top.Dialogs.refresh_stack[i];
        } else {
            top.Dialogs.refresh_stack[i] = refresh;
        }
    } 
    top.$(top.Dialogs.dialog_stack[top.Dialogs.dialog_stack.length-1]).dialog('close');
 }
};
this.AddToPostBackAndSubmit = function($form, func) {
    $form.submit(func);
    var old__doPostBack = __doPostBack;
    if (typeof(__doPostBack) !== 'function') {
        __doPostBack = func;
    } else {
        __doPostBack = function(t, a) {
            if (func(t, a)) { 
                old__doPostBack(t, a); 
            }
        };
    }
};
};
//Dialogs
var Dialogs = new Dialogs();


//Модуль "комментарии", требует jquery, для работы необзодимо запустить Comments.Init() после загрузки страницы. 
//Также требует аттрибут FullPrefix установленный у страницы.
var Comments = {};
Comments.SetCommentAndReplyID = function ($hid, commentID, replyID) {
    var s = $hid.val();
    var avpos = s.indexOf('[');
    if (avpos >= 0) {
     s = commentID + ':' + replyID + s.substring(avpos); 
    } else {
     s = commentID + ':' + replyID; 
    }
    $hid.val(s);
};
Comments.AvatarSetLink = function ($hid, link){
    var s = $hid.val();
    if (s.indexOf(']') > 0) {
     s = s.replace( /\[[^\]]*\]/, '['+link+']' ); 
    } else {
     s = s + '[' + link + ']'; 
    }
    $hid.val(s);
};
Comments.AvatarLoaded = function (data){
    var i=0;
    for (i=0;i<data.length;i++) {
        $('.comments_avatarcontainer').html('<img alt="аватар" src="'+FullPrefix+data[i]+'"/>');
        Comments.AvatarSetLink($('input[name$=hidCommentInfo]'), data[i]);
    }    
};
Comments.AvatarSelected = function ()
{
    var i = 0;
    var $sel = $('.comments_avatarselect');
    for (i=0;i<$sel.length;i++) {
        var $container = $($sel[i]).closest('.comments_container');
        var link = $($sel[i]).val();
        $container.find('.comments_avatarcontainer').html('<img alt="аватар" src="'+FullPrefix+link+'"/>');
        Comments.AvatarSetLink($container.find('input[name$=hidCommentInfo]'), link);
    }        
};
Comments.CancelClick = function() {
    var $container = $(this).closest('.comments_container');
    $container.find('.comments_add').hide();
    $container.find('.comments_editablecontent').show();
    return false;
};
Comments.AddClick = function() {
    var $container = $(this).closest('.comments_container');
    Comments.SetCommentAndReplyID($container.find('input[name$=hidCommentInfo]'), 0, 0);    
    $container.find('.comments_add').show().appendTo($container.find('.comments_addcontainer'));
    return false;
};
Comments.DeleteClick = function() {
    if (confirm('Вы уверены, что хотите удалить комментарий?')) {
        var $container = $(this).closest('.comments_container');
        var arg = $(this).attr('href').substring(1);
        $container.find('input[name$=hidCommandInfo]').val("Delete:"+arg); 
        __doPostBack('','');
    }
    return false;
};
Comments.DeleteAllClick = function() {
    if (confirm('Вы уверены, что хотите удалить ветвь комментариев?\r\nЭто действие нельзя отменить.')) {
        var $container = $(this).closest('.comments_container');
        var arg = $(this).attr('href').substring(1);        
        $container.find('input[name$=hidCommandInfo]').val("DeleteAll:"+arg);
        __doPostBack('','');
    }
    return false;   
};
Comments.RestoreClick = function() {
    var $container = $(this).closest('.comments_container');
    var arg = $(this).attr('href').substring(1);
    $container.find('input[name$=hidCommandInfo]').val("Restore:"+arg);
    __doPostBack('','');
    return false;   
};
Comments.$FCKComment = null;
Comments.UpdateFCK = function () { 
    try {
        var $input = Comments.$FCKComment.closest('.comments_container').find('input[name$=fckCommentText]');
        if ($input.length === 0) {
         $input = Comments.$FCKComment.closest('.comments_container').find('input[name$=fckCommentTextReg]'); 
        }
        if ($input.length > 0) {
            var fck = FCKeditorAPI.GetInstance($input.attr('id'));
            if (fck){
                fck.SetHTML(Comments.$FCKComment.find('.comments_commenttext').html());
                return true;
            }
        }        
        window.setTimeout(Comments.UpdateFCK, 1000);
    } catch(err) {
        window.setTimeout(Comments.UpdateFCK, 1000);
    }

};
Comments.ShowEdit = function() {
    var $comment = $(this).closest('.comments_comment');
    var $container = $comment.closest('.comments_container');
    $container.find('.comments_editablecontent').show();
    $comment.find('.comments_editablecontent').hide();
    $container.find('input[name$=txbName]').val($comment.find('.comments_authorname').text());    
    var $email = $comment.find('.comments_authoremail');
    if ($email.length>0) {
     $container.find('input[name$=txbEmail]').val($email.text()); 
    }
    $container.find('.comments_add').show().appendTo($comment.find('.comments_edit'));
    
    var link = $comment.find('.comments_avatar').attr('data-shortlink');    
    $comment.find('.comments_avatarcontainer').html('<img alt="аватар" src="'+link+'"/>');
    Comments.AvatarSetLink($container.find('input[name$=hidCommentInfo]'), link);
    
    Comments.$FCKComment = $comment;
    Comments.UpdateFCK();
    Comments.SetCommentAndReplyID($container.find('input[name$=hidCommentInfo]'), $(this).attr('href'), 0);
    return false;
};
Comments.ShowReply = function() {
    var $comment = $(this).closest('.comments_comment');
    var $container = $comment.closest('.comments_container');
    $container.find('.comments_add').show().appendTo($comment.find('.comments_edit'));
    Comments.SetCommentAndReplyID($container.find('input[name$=hidCommentInfo]'), 0, $(this).attr('href'));
    return false;
};
Comments.Trim = function(str) {
    return str.replace(/(^\s+)|(\s+$)/g, "");
};
Comments.ValidateCaptcha = function(code){
    var captchaValid = false;
    $.ajax({url: FullPrefix + 'Modules/Captcha/Check.ashx?c=' + code, 
                async: false, 
                cache: false,
                error: function() {
                    captchaValid = false;
                },
                success: function(data){
                    if (data==='OK') {
                        captchaValid = true;
                    } else if (data==='WRONG') {
                        captchaValid = false;
                    } else if (data==='BLOCKEDIP') {
                        alert('Ваш IP адрес был заблокирован в связи с многократными попытками подбора кода.').css('color','red');
                        captchaValid = false;
                    } else {
                       captchaValid = false; 
                    }
                }
    });
    return captchaValid;
};
Comments.AddCommentCheck = function() {
    var $container = $(this).closest('.comments_container');
    if (Comments.Trim($container.find('input[name$=txbName]').val())===''){
        alert('Вы не представились.');
        return false;
    }
    var code = $container.find('input[name$=txbCode]').val();
    if (Comments.Trim(code)===''){
        alert('Вы не указали изображённое число.');
        return false;
    }
    if (!Comments.ValidateCaptcha(code)){
        var $img = $container.find('img.imgCaptcha');
        $img.attr('src', $img.attr('src') + '2');
        alert('Вы ввели неправильное число подстверждения, попробуйте ещё раз.');
        return false;
    }
    var text = FCKeditorAPI.GetInstance($container.find('input[name$=fckCommentText]').attr('id')).GetXHTML(true);
    if (Comments.Trim(text)===''){        
        alert('Вы не написали комментарий.');
        return false;
    }
    if (text.length>2000){
        alert('Длина комментария ('+text.length+') не может превышать 2000 символов.');
        return false;
    }
    var email = Comments.Trim($container.find('input[name$=txbEmail]').val());
    if ( email !== '' && !email.match(/^\w+([\-+\.]\w+)*@\w+([\-\.]\w+)*\.\w+([\-\.]\w+)*$/)){
        alert('Вы указали некорректный адрес электронной почты.');
        return false;
    }
    return true;
};
Comments.AddCommentCheckReg = function() {
    var $container = $(this).closest('.comments_container');
    var text = FCKeditorAPI.GetInstance($container.find('input[name$=fckCommentTextReg]').attr('id')).GetXHTML(true);
    if (Comments.Trim(text)===''){
            alert('Вы не написали комментарий.');
            return false;
    }
    if (text.length>2000){
        alert('Длина комментария ('+text.length+') не может превышать 2000 символов.');
        return false;
    }
    return true;
};
Comments.Init = function() {
    $('.comments_avatarselect').change(Comments.AvatarSelected);
    $('.comments_showadd').click(Comments.AddClick);
    $('.comments_saveclick').click(Comments.AddCommentCheck);
    $('.comments_saveclickreg').click(Comments.AddCommentCheckReg);
    $('.comments_showedit').click(Comments.ShowEdit);
    $('.comments_showreply').click(Comments.ShowReply);
    $('.comments_cancelclick').click(Comments.CancelClick);
    $('.comments_deleteclick').click(Comments.DeleteClick);
    $('.comments_deleteallclick').click(Comments.DeleteAllClick);
    $('.comments_restoreclick').click(Comments.RestoreClick);
    Comments.AvatarSelected();
    if (/#commentadd$/.test(document.location.href)) {
        $('.comments_add').show().appendTo($container.find('.comments_addcontainer'));
    }
};
//Конец модуля "комментарии"
var MainSlide = function (){
    var num = parseInt($(this).attr('data-num'),10);
    var max = parseInt($(this).attr('data-maxnum'),10);
    var $container = $(this).closest('.main_container');
    var inc = 0; var c = '';
    if ($(this).attr('class').indexOf('main_prev')>=0) {
     inc = -1; c = '-=50'; 
    }
    if ($(this).attr('class').indexOf('main_next')>=0) {
     inc = +1; c = '+=50'; 
    }
    $container.find('.main_prev').hide();
    $container.find('.main_next').hide();
    $container.find('.main_num[data-num='+num+']').animate({
                                    "opacity": 0.25,
                                    "margin-left": c
                                  }, 'fast', function() {
        $container.find('.main_num[data-num='+num+']').hide();
        num += inc;
        if (num < 1) { num = max; }
        if (num > max) { num = 1; }
        $container.find('.main_prev').attr('data-num', num);
        $container.find('.main_next').attr('data-num', num);
        $container.find('.main_num[data-num='+num+']').show()
            .css('opacity',0.25).css('margin-left',-50*inc).animate({
                                            "opacity": 1,
                                            "margin-left": c
                                          }, 'fast', function() {                                            
                                            $container.find('.main_prev').show();
                                            $container.find('.main_next').show();
                                          });
    });
    return false;        
};

var Main = {};
Main.Num = 0;
Main.ShowSlide = function (){
    $('.main_linesnum').animate(
        {
        "opacity": 0.25
        }
        , 500
        , function(){          
            $('.main_linesnum').hide();
            $('.main_linesnum[data-num='+Main.Num+']').show()
                .css('opacity',0.25)
                .animate({
                    "opacity": 1
                  }, 500, null);
         }
     );

    $('.main_linestopage').removeClass('main_linesactive');
    $('.main_linestopage[href=#'+Main.Num+']').addClass('main_linesactive');
};
Main.StopShow = false;

$(function(){
    //Подключаем title = alt
    $('img[alt]').each(function(){
        if (!$(this).attr('title')){
            $(this).attr('title',  $(this).attr('alt'));
        }        
    });
    //комментарии
    Comments.Init();
    
    //Popup галерея
    $("a[rel^='prettyPhoto']").prettyPhoto({overlay_gallery: false, changepicturecallback: function(){
        if ($('#fullResImage').length>0) {
            var src = $('#fullResImage').attr('src');
            src = src.substring(src.indexOf('guid='));
            $('.pp_content').height($('.pp_content').height()+60);        
            $('.pp_description').html('<div style="float:left"><iframe frameborder="0" class="votingframefoto" src="'+FullPrefix+'Modules/Photos/Components/Voting.aspx?'+src+'"/></div><br clear="all"/>');
        }
    }});

    
    //скрипт для голосований        
    $('.votingquestionresults').hide();
    $('.votingdovoting').hide();
    $('.votingdoresults').show();
    
    $('.votingdoresults').click(function(){
        $item = $(this).closest('.votingitemcontainer');
        $item.find('.votingquestionresults').show();
        $item.find('.votingdovoting').show();
        $item.find('.votingquestionvoting').hide();
        $item.find('.votingdoresults').hide();
        return false;
    });
    
    $('.votingdovoting').click(function(){
        $item = $(this).closest('.votingitemcontainer');
        $item.find('.votingquestionresults').hide();
        $item.find('.votingdovoting').hide();
        $item.find('.votingquestionvoting').show();
        $item.find('.votingdoresults').show();
        return false;
    });
    
    $('.votinginfolink').click(function(){        
        $(this).closest('.votingitemcontainer').find('.hiddeninfo').show();
        return false;
    }); 
    
    $('.votinghideinfo').click(function(){        
        $(this).closest('.votingitemcontainer').find('.hiddeninfo').hide();
        return false;
    });      


    $('.votingfirststep').click(function(){        
        $(this).closest('.votingitemcontainer').find('.hiddendialog').show();
        $(this).closest('.votingitemcontainer').find('.votingfirststep').hide();
        $('.backgroundoverlay').show();
        return false;
    });

    $('.votingcancel').click(function(){        
        $(this).closest('.votingitemcontainer').find('.hiddendialog').hide();
        $(this).closest('.votingitemcontainer').find('.votingfirststep').show();
        $('.backgroundoverlay').hide();
        return false;
    });
    
    //"главное" на главной
    $('.main_linestopage').click(function(){
        Main.Num = $(this).attr('href').substring(1);
        Main.ShowSlide();
        Main.StopShow = true;
        return false;
    });
    
    //новости и мероприятия на главной
    $('.main_shownews').click(function(){
        $('.main_linesevents').hide();
        $('.main_linesnews').show();
        return false;
    });
    $('.main_showevents').click(function(){
        $('.main_linesnews').hide();
        $('.main_linesevents').show();
        return false;
    });
    //видео на главной
    $('.main_prev').add('.main_next').click(MainSlide);
});
