var prev = 1;

function logPage(_url) {
    return;
	try {
		var pageTracker = _gat._getTracker('UA-2505861-1'); 
		pageTracker._trackPageview(_url);
        
	} catch(e){}
}

function slideshow(cont, value, current) {
	if(value.length <= 0) return;
	
	document.getElementById(cont).src = value;
	
	try {
		document.getElementById("slsh" + prev).className = "slshDeselected";
	} catch(e){}
	
	try {
		document.getElementById("slsh" + current).className = "slshSelected";
		prev = parseInt(current);
	} catch(e){}
	
	if(document.getElementById("slsh_img" + (parseInt(prev)))) {
		document.getElementById(cont).onclick = function() {
			var nextSrc = "";
			try {
				var name = "slsh_img" + (parseInt(prev));
				nextSrc = document.getElementById(name).getAttribute("__next");
				slideshow('slideshowCont', nextSrc, parseInt(prev) + 1);
			} catch(e){
				alert(name);
				alert(e);
			}
		}
	}
}

function go(uri)
{
    location.href = uri;
};

function openPopup(uri)
{
    var height = screen.height * 0.8;
    var width = screen.width * 0.7;
    
    var left = ( document.documentElement.clientWidth - width ) / 2;
    var top = ( window.outerHeight - height ) / 2;
    
    window.open(uri, '_blank', 'left='+left+',top='+top+',height='+height+',width='+width+'location=no,menubar=no,resizable=yes,scrollbars=yes,toolbar=no,titlebar=yes');
};

function closeReloadParent()
{
    window.opener.location.reload();
    window.close();
};

function closeFocusParent()
{
    window.opener.focus();
    window.close();
};

function showElement(el_id)
{
    var el = document.getElementById(el_id);
    
  $(document).ready(function(){
	$(el).show();
	$(el).css("opacity", 0);
	if (el_id == "bbg") $(el).animate({opacity: 0.63}, 500);
	else	
	$(el).animate({opacity: 1}, 500);
  });
    
 };

function showNonBlockElement(el_id)
{
    var el = document.getElementById(el_id);
    el.style.display = 'block';
};

function hideElement(el_id)
{
    var el = document.getElementById(el_id);
    if(el)
    	el.style.display = 'none';
};

function toogleElementDisplay(el_id)
{
    var el = document.getElementById(el_id);
    el.style.display = (el.style.display == 'none' ? 'block' : 'none');
};

function dropAllOptionsFromSelect(el_id)
{
    var el = document.getElementById(el_id);
    while(el.options.length > 0)
    {
        el.remove(0);
    };
};

function enableButton(b_id, callback)
{
    var b_el = document.getElementById(b_id);
    b_el.disabled = false;
    b_el.onclick = callback;
};

function disableButton(b_id)
{
    var b_el = document.getElementById(b_id);
    b_el.disabled = true;
    b_el.onclick = void(0);
};

function setFormFieldAsNormal(fld_el)
{
    fld_el.className = trim(fld_el.className.replace('form_field_incorrect',''));
};

function setFormFieldAsIncorrect(fld_el)
{
    if(fld_el.className.indexOf('form_field_incorrect') == -1)
    {
        fld_el.className += ' form_field_incorrect';
    };
};

function getCheckedElementsIDs(e_name, e_prefix)
{
    var els = document.getElementsByName(e_name);
    var e_ids = new Array();
    
    for(i = 0; i < els.length; i++)
    {
        if(els[i].checked)
        {
            e_ids.push(els[i].id.replace(e_prefix, ''));
        };
    };
    
    return e_ids;
};

function getUnCheckedElementsIDs(e_name, e_prefix)
{
    var els = document.getElementsByName(e_name);
    var e_ids = new Array();
    
    for(i = 0; i < els.length; i++)
    {
        if(!els[i].checked)
        {
            e_ids.push(els[i].id.replace(e_prefix, ''));
        };
    };
    
    return e_ids;
};

function toogleAllElements(e_name, status)
{
    var els = document.getElementsByName(e_name);
    
    for(i = 0; i < els.length; i++)
    {
        els[i].checked = status;
    };
};

function trim(stringToTrim)
{
    return stringToTrim.replace(/^\s+|\s+$/g,"");
};

function ltrim(stringToTrim)
{
    return stringToTrim.replace(/^\s+/,"");
};

function rtrim(stringToTrim)
{
    return stringToTrim.replace(/\s+$/,"");
};

function dropAllOptions(dd_el, leave_first)
{
    var i = (leave_first ? 1 : 0);
    
    while(dd_el.options.length > i)
    {
        dd_el.remove(i);
    };
};

function array_search(a, e)
{
    for(i = 0; i < a.length; i++)
    {
        if(a[i] == e)
        {
            return i;
        };
    };
    
    return -1;
};

function in_array(a, e)
{
    for(i = 0; i < a.length; i++)
    {
        if(a[i] == e)
        {
            return true;
        };
    };
    
    return false;
};

function blockToWindowCenter(block_id)
{
	
    var el = document.getElementById(block_id);
    var el_top2 = ( document.documentElement.clientHeight - el.clientHeight ) / 2; // + $(document).scrollTop();
    var el_top3 = ( document.documentElement.clientHeight - el.clientHeight ) / 2 + $(document).scrollTop();
    var el_top = (el.clientHeight) / 2; 
    
    var el_left2 = (el.clientWidth) /2; 
    var el_left = ( document.documentElement.clientWidth - el.clientWidth ) / 2;
    
    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        el.style.position = 'absolute';
        el.style.top = el_top3+'px';
        el.style.margin = '0px 0px 0px -25%';
    
     	 $(window).scroll(function () { 
		  	offset1 = el_top2 + $(document).scrollTop() + "px";
		 	$('.popup').animate({top:offset1},{duration:500,queue:false});
	     });
      
    }
    else
    {
        el.style.position = 'fixed';
        el.style.top = '50%';
        /*el.style.margin = '-'+el_top+'px 0px 0px -'+el_left2+'px';*/
        el.style.margin = '-'+el_top+'px 0px 0px -25%';
    }
    
    
/*    el.style.left = el_left+'px';*/
};

function feetToWindow(block_id)
{
    var el = document.getElementById(block_id);
    with(document.documentElement)
    {
        var fHeight = scrollHeight > clientHeight ? scrollHeight : clientHeight;
    };

    el.style.height = fHeight+'px';
    el.style.width = '100%';
};

function addToFavor(url, title)
{
    if (window.sidebar)
    { // Mozilla Firefox Bookmark
        window.sidebar.addPanel(title, url, "");
    }
    else if( window.external )
    { // IE Favorite
        window.external.AddFavorite(url, title);
    }
    else if(window.opera && window.print)
    { // Opera Hotlist
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    };
};

function addToFavor2(post_id)
{
    jQuery.getJSON('ajax/addfavor', {post_id: post_id},
        function(data)
        {
            if(data.add_result == 'ok')
            {
                showPopupAdded2Favor();
            };
        }
    );
};

function submitCommentForm(form_id)
{
    var frm = document.forms[form_id];
    
    if(frm.comment_text.value == '')
    {
        frm.comment_text.focus();
        return false;
    };

    frm.submit();
};

function __submitCommentForm(form_id) {
    var frm = document.forms[form_id];

    if(frm.captcha.value == '')
    {
    	showCommentFormMessage("Captcha введена не правильно!");
        frm.captcha.focus();
        return false;
    };

    
    if(frm.comment_text.value == '')
    {
        showCommentFormMessage("Заполните сообщение!");
        frm.comment_text.focus();
        return false;
    };

    jQuery.getJSON('ajax/checkcaptcha/', {captcha: frm.captcha.value},
        function(data)
        {
            if(data.result == 'Y')
            {
                logPage("/add/newcomment/");
                    
                frm.submit();
            } else {
            	showCommentFormMessage("Captcha введена не правильно!");
            }
        }
    );
    
    return false;
}

function showCommentFormMessage(message) {
	document.getElementById("commentFormMessages").innerHTML = message;
	document.getElementById("commentFormMessages").style.display = "block";
}

function reloadCaptcha() {
	document.getElementById('captcha').src = "captcha.php?rand=" + Math.random();
}

function showRegisterForm()
{
    showFade();
    reloadCaptcha();
    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        var el_ie6 = document.getElementById('register_form_ie6');
        if(!el_ie6)
        {
            var el = document.getElementById('register_form');
            el_ie6 = el;
        
            el_ie6.id = 'register_form_ie6';
        
            document.body.appendChild(el_ie6);
        };
        
        showElement('register_form_ie6');
        blockToWindowCenter('register_form_ie6');
    }
    else
    {
        showElement('register_form');
        blockToWindowCenter('register_form');
    };
};

function hideRegisterForm()
{
    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        hideElement('register_form_ie6');
    }
    else
    {
        hideElement('register_form');
    };
    
    hideFade();
};



function showForgotPasswdForm()
{
    showFade();

    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        var el_ie6 = document.getElementById('forgot_passwd_form_ie6');
        if(!el_ie6)
        {
            var el = document.getElementById('forgot_passwd_form');
            el_ie6 = el;
        
            el_ie6.id = 'forgot_passwd_form_ie6';
        
            document.body.appendChild(el_ie6);
        };
        
        showElement('forgot_passwd_form_ie6');
        blockToWindowCenter('forgot_passwd_form_ie6');
    }
    else
    {
        showElement('forgot_passwd_form');
        blockToWindowCenter('forgot_passwd_form');
    };
};

function hideForgotPasswdForm()
{
    hideElement('new_passwd_send_msg');

    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        hideElement('forgot_passwd_form_ie6');
    }
    else
    {
        hideElement('forgot_passwd_form');
    };
    
    hideFade();
};

function showFade()
{
    var fade = document.getElementById('bbg');
    if(!fade)
    {
        fade = document.createElement('div');
        fade.className = 'black_overlay';
        fade.id = 'bbg';
        fade.style.display = 'none';
        
        document.body.appendChild(fade);
    };
    
    showElement('bbg');
    feetToWindow('bbg');
    
    

};

function hideFade()
{
   /* hideElement('bo_fade');*/
       $("#bbg").animate({opacity: 0}, 500,	
		function () {
			$("#bbg").hide();
	});
};

function tryRegister()
{
    var reg_frm = document.forms['RegisterForm'];
    
    setFormFieldAsNormal(reg_frm.login);
    setFormFieldAsNormal(reg_frm.email);
    setFormFieldAsNormal(reg_frm.password);
    setFormFieldAsNormal(reg_frm.repassword);
    setFormFieldAsNormal(reg_frm.captcha);
    
    var errors = new Array();
    var emsgs = new Array();
    
    if(trim(reg_frm.login.value) == '')
    {
        errors.push('login');
        emsgs.push('Пустое имя');
    };
    
    if(trim(reg_frm.email.value) == '')
    {
        errors.push('email');
        emsgs.push('Пустой e-mail');
    };
    /*
    if(reg_frm.password.value == '' || reg_frm.password.value != reg_frm.repassword.value)
    {
        errors.push('password');
        errors.push('repassword');
        emsgs.push('Некорректный пароль');
    };
    */
    if(errors.length > 0)
    {
        for(i=0; i<errors.length; i++)
        {
            setFormFieldAsIncorrect(reg_frm.elements[errors[i]]);
        };
        
        document.getElementById('regform_errmsg').innerHTML = emsgs.join('<br/>');
        
        return;
    };
    
    document.getElementById('regform_errmsg').innerHTML = '';
    
    var params = {
        'login': reg_frm.login.value
       ,'password': reg_frm.password.value
       ,'repassword': reg_frm.repassword.value
       ,'email': reg_frm.email.value
       ,'captcha': reg_frm.captcha.value
    };
   
    jQuery.getJSON('/ajax/register', params,
        function(data)
        {
            if(data.reg_result.length > 0)
            {
                for(i=0; i<data.reg_result.length; i++)
                {
                    setFormFieldAsIncorrect(reg_frm.elements[data.reg_result[i]]);
                    
                    switch(data.reg_result[i])
                    {
                        case 'login': emsgs.push('Такой пользователь уже есть'); break;
                        case 'email': emsgs.push('Некорректный e-mail'); break;
                        case 'password': emsgs.push('Некорректный пароль'); break;
                        case 'captcha': emsgs.push('Не правильно введена CAPTCHA'); break;
                    };
                };
                
//                reg_frm.captcha.value = "";
//                reloadCaptcha();
                
                document.getElementById('regform_errmsg').innerHTML = emsgs.join('<br/>');
            }
            else
            {            	
                //  google analitycs
                logPage("/add/newuser/");

                go('/confirm_registration');
            };
        } 
    );
};

function sendFP()
{
    hideElement('new_passwd_send_msg');
    hideElement('user_not_found');
    hideElement('fp_submit');
    document.getElementById('fp_login').disabled = true;

    var fp_login = trim(document.getElementById('fp_login').value);
    
    setFormFieldAsNormal(document.getElementById('fp_login'));
    
    jQuery.getJSON('/ajax/forgotpasswd', {'fp_login': fp_login},
        function(data)
        {
            if(data.fp_result == 'invalid_login')
            {
            	showElement('user_not_found');
                setFormFieldAsIncorrect(document.getElementById('fp_login'));
                showElement('fp_submit');
                document.getElementById('fp_login').disabled = false;
            }
            else if(data.fp_result == 'ok')
            {
                showElement('new_passwd_send_msg');
                showElement('fp_close');
            };
        }
    );
};

function showEditCommentForm(comment_id)
{
    showFade();
    showElement('edit_comment_form');
    blockToWindowCenter('edit_comment_form');
    document.getElementById('edit_comment_content').value = strip_tags(document.getElementById('comment_'+comment_id).innerHTML);
    document.getElementById('edit_comment_id').value = comment_id;
};

function hideEditCommentForm()
{
    hideElement('edit_comment_form');
    hideFade();
};

function strip_tags(text) {
	return text.replace(/<\/?[^>]+>/gi,'');
}


function saveComment()
{
    var comment_id = document.getElementById('edit_comment_id').value;
    var content = document.getElementById('edit_comment_content').value;
    jQuery.getJSON('/ajax/savecomment', {'comment_id': comment_id, 'content': content},
        function(data)
        {
            if(data.save_result == 'ok')
            {
            	
                document.getElementById('comment_'+comment_id).innerHTML = data.content;
            };
            hideEditCommentForm();
        }
    );
};

function deleteComment(comment_id)
{
    if(!confirm('Удалить этот комментарий?'))
    {
        return;
    };
    
    jQuery.getJSON('/ajax/deletecomment', {comment_id: comment_id},
        function(data)
        {
            if(data.delete_result == 'ok')
            {
                window.location.reload();
            };
        }
    );
};

function restoreComment(comment_id)
{
    if(!confirm('Восстановить этот комментарий?'))
    {
        return;
    };
    
    jQuery.getJSON('/ajax/restorecomment', {comment_id: comment_id},
        function(data)
        {
            if(data.restore_result == 'ok')
            {
                window.location.reload();
            };
        }
    );
};

function nl2br(str)
{
    return str.replace(/(\n)/g, '<br>\n');
};

function addChildPost(parent_id)
{
    var frm = document.createElement('form');
    frm.action = '/addpost';
    frm.method = 'post';
    
    var pid = document.createElement('input');
    pid.type = 'hidden';
    pid.name = 'parent_id';
    pid.value = parent_id;
    
    frm.appendChild(pid);
    
    document.body.appendChild(frm);
    
    frm.submit();
};

function toUnderBlock(block_id, ub_id)
{
     var ub_pos = getAbsPosition(ub_id);
     
     var b = document.getElementById(block_id);
     
     b.style.position = 'absolute';
     b.style.left = ub_pos.left+'px';
     b.style.top = ub_pos.top+document.getElementById(ub_id).clientHeight+'px';
};

function getAbsPosition(block_id)
{
    var b = document.getElementById(block_id);
    
    var left = b.offsetLeft;
    var top = b.offsetTop;
    
    var obj = b;
    while(obj.offsetParent)
    {
        obj = obj.offsetParent;
        left += obj.offsetLeft;
        top += obj.offsetTop;
    };
    
    return {left: left, top: top};
};


function getTagList(str)
{
    if(trim(str) == '')
    {
        hideElement('tag_list_div');
        return;
    };
    
    jQuery.getJSON('/ajax/subjecttaglist', {str: trim(str)},
        function(data)
        {
            if(data.tag_list.length == 0)
            {
                hideElement('tag_list_div');
                return;
            };
            
            var tbl = document.getElementById('tag_list');
            while(tbl.rows.length > 0)
            {
                tbl.deleteRow(0);
            };
            
            $('#tag_list').removeAttr('position');

            var prevType = '';

            for(i=0, n = 0; i<data.tag_list.length; i++, n++)
            {

                if(prevType != data.tag_list[i].type) {
                    prevType = data.tag_list[i].type;
                    
                    var row = tbl.insertRow(n);
                    var cell0 = row.insertCell(0);
                    var cell1 = row.insertCell(1);

                    cell0.style.background = "#BCBCBC";
                    cell1.style.background = "#BCBCBC";

                    if(data.tag_list[i].type == "post")
                        cell0.innerHTML = "<b>Заметки</b>";
                    else if(data.tag_list[i].type == "tag")
                        cell0.innerHTML = "<b>Теги</b>";
                    n++;
                    
                    row.className = 'item-title';
                }

                var row = tbl.insertRow(n);
                var cell0 = row.insertCell(0);
                var cell1 = row.insertCell(1);
                
                cell0.innerHTML = data.tag_list[i].name;
                cell1.innerHTML = data.tag_list[i].count;
                
                cell1.style.textAlign = 'right';
                cell1.style.color = 'green';
                
                row.xtag_id   = data.tag_list[i].id;
                row.xtag_name = data.tag_list[i].name;
                row.onclick = function() {
                    onSearchClick(this.xtag_id.toString(), 'subject_tagid', this.xtag_name.toString());
                };
                row.onmouseover = function() {
                	$('#tag_list tr').removeClass('item-hover');
                	$('#tag_list').removeAttr('position');
                }
            };
            
            showElement('tag_list_div');
            //toUnderBlock('tag_list_div', 'search');
            var ub_pos = getAbsPosition('search');
		     var b = document.getElementById('tag_list_div');
		     
		     b.style.position = 'absolute';
		     b.style.left = ub_pos.left+'px';
		     b.style.top = '50px';
        }
    );
};

function onSearchClick(search_string, search_by, search_str)
{
    if(trim(search_string) == '')
    {
        return;
    };

    var frm = document.createElement('form');
    frm.action = '/search';
    frm.method = 'get';
    
    var hf1 = document.createElement('input');
    hf1.type = 'hidden';
    hf1.name = 'search_string';
    hf1.value = search_string;
    
    var hf2 = document.createElement('input');
    hf2.type = 'hidden';
    hf2.name = 'search_by';
    hf2.value = search_by;
    
    if(search_string && search_str) {
	    var hf3 = document.createElement('input');
	    hf3.type = 'hidden';
	    hf3.name = 'search_str';
        
	    hf3.value = search_str;
	    frm.appendChild(hf3);
	}
	
    frm.appendChild(hf1);
    frm.appendChild(hf2);
    
    
    document.body.appendChild(frm);
    //return;
    frm.submit();
};

function onSearchFieldKeyDown(e)
{
    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;

    if(code == 13) // Enter
    {
    	if ($('#tag_list') && $('#tag_list').attr('position') && $('#tag_list').find('tr:eq(' + $('#tag_list').attr('position') + ')').length > 0)
    	{
    		$('#tag_list').find('tr:eq(' + $('#tag_list').attr('position') + ')').click();	
    	}
    	else
    	{
        	onSearchClick(document.getElementById('search_string').value, 'text');
    	}
    };
};

function onSearchFieldKeyUp(e)
{
    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;

    switch (code)
    {
    	case 37:
    	case 39:
    		break;
    	case 38:
    		moveUpOnTagList();
    		break;
    	case 40:
    		moveDownOnTagList();
    		break;
    	default:
    		getTagList(document.getElementById('search_string').value);
    		break;
    }
};

function moveDownOnTagList()
{
	tag_list_obj = $('#tag_list');
	if (tag_list_obj)
	{
		tag_list_items_count = tag_list_obj.find('tr').length;
				
		position = tag_list_obj.attr('position') ? tag_list_obj.attr('position') : -1;
		do
		{
			position++;
		}
		while ((!tag_list_obj.find('tr:eq(' + position + ')') || tag_list_obj.find('tr:eq(' + position + ')').hasClass('item-title')) && position < tag_list_items_count);
		
		if (tag_list_obj.find('tr:eq(' + position + ')').length == 0) position = 1;
		
		setItemOnTagList(position);
	}
};

function moveUpOnTagList()
{
	tag_list_obj = $('#tag_list');
	if (tag_list_obj)
	{
		tag_list_items_count = tag_list_obj.find('tr').length;
				
		position = tag_list_obj.attr('position') ? tag_list_obj.attr('position') : tag_list_items_count;
		do
		{
			position--;
		}
		while ((!tag_list_obj.find('tr:eq(' + position + ')') || tag_list_obj.find('tr:eq(' + position + ')').hasClass('item-title')) && position < tag_list_items_count);
		
		if (tag_list_obj.find('tr:eq(' + position + ')').length == 0) position = tag_list_items_count - 1;
		
		setItemOnTagList(position);
	}
};

function setItemOnTagList(_position)
{
	tag_list_obj = $('#tag_list');
	if (tag_list_obj)
	{
		tag_list_obj.find('tr').removeClass('item-hover');
		tag_list_obj.find('tr:eq(' + _position + ')').addClass('item-hover');
		
		tag_list_obj.attr('position', _position);
	}
}

function scrollToAuthBox()
{
    if(window.location.href.indexOf('#auth_box') == -1)
    {
        window.location.href += "#auth_box";
    }
    else
    {
        window.location.reload();
    };
};

function showPopupAuth()
{
    showFade();
    
    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        var el_ie6 = document.getElementById('popup_auth_ie6');
        if(!el_ie6)
        {
            var el = document.getElementById('popup_auth');
            el_ie6 = el;
        
            el_ie6.id = 'popup_auth_ie6';
        
            document.body.appendChild(el_ie6);
        };
        
        showElement('popup_auth_ie6');
        blockToWindowCenter('popup_auth_ie6');
    }
    else
    {
        showElement('popup_auth');
        blockToWindowCenter('popup_auth');
    };
};

function hidePopupAuth()
{
    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        hideElement('popup_auth_ie6');
    }
    else
    {
        hideElement('popup_auth');
    };
    
    hideFade();
};

function showPopupAuthForm()
{
    showFade();
    
    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        var el_ie6 = document.getElementById('popup_authform_ie6');
        if(!el_ie6)
        {
            var el = document.getElementById('popup_authform');
            el_ie6 = el;
        
            el_ie6.id = 'popup_authform_ie6';
        
            document.body.appendChild(el_ie6);
        };
        
        showElement('popup_authform_ie6');
        blockToWindowCenter('popup_authform_ie6');
    }
    else
    {
        showElement('popup_authform');
        blockToWindowCenter('popup_authform');
    };
};

function hidePopupAuthForm()
{
    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        hideElement('popup_authform_ie6');
    }
    else
    {
        hideElement('popup_authform');
    };
    
    hideFade();
};

function showPopupAdded2Favor()
{
    showFade();
    
    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        var el_ie6 = document.getElementById('popup_added2favor_ie6');
        if(!el_ie6)
        {
            var el = document.getElementById('popup_added2favor');
            el_ie6 = el;
        
            el_ie6.id = 'popup_added2favor_ie6';
        
            document.body.appendChild(el_ie6);
        };
        
        showElement('popup_added2favor_ie6');
        blockToWindowCenter('popup_added2favor_ie6');
    }
    else
    {
        showElement('popup_added2favor');
        blockToWindowCenter('popup_added2favor');
    };
    
    if(window.location.href.indexOf('/post/') != -1)
    {
        document.getElementById('added2favot_type').innerHTML = 'Образец';
    };
};

function hidePopupAdded2Favor()
{
    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        hideElement('popup_added2favor_ie6');
    }
    else
    {
        hideElement('popup_added2favor');
    };
    
    hideFade();
};

function onSignOutClick() {
	setCookie("USK", '', -60, "/");
}

function onSignInClick(src_form, c_error_id)
{
    var frm = document.forms[src_form];
    
    var params = {
        login:    trim(frm.elements['login'].value)
       ,password: frm.elements['password'].value
       ,remember: frm.elements['remember'].checked
    };
    
    setFormFieldAsNormal(frm.elements['login']);
    setFormFieldAsNormal(frm.elements['password']);

    var el = document.getElementById(c_error_id);
    el.innerHTML = ''; 
    
    jQuery.getJSON('ajax/signin', params,
        function(data)
        {
    		
            if(data.errors.length == '')
            {           	
                window.location.reload();
            };
            
            for(i=0; i<data.errors.length; i++)
            {
                setFormFieldAsIncorrect(frm.elements[data.errors[i]]);
                switch(data.errors[i])
                {
                    case 'login':
                        el.innerHTML = '<h3 style="color: #CC0000;">У нас нет такого сотрудника</h3>'; 
                        break;
                    case 'password':
                        el.innerHTML = '<h3 style="color: #CC0000;">Неверный пароль</h3>';
                        break;
                };
            };
        }
    );
};

function signByEnter(e, form_name, emsg_id)
{
    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;

    if(code == 13) // Enter
    {
        onSignInClick(form_name, emsg_id);
    };
};

function regByEnter(e)
{
    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;

    if(code == 13) // Enter
    {
        tryRegister();
    };
};

function showPopupErrorMsg(msg)
{
    showFade();
    
    document.getElementById('popup_errormsg_content').innerHTML = msg;
    
    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        var el_ie6 = document.getElementById('popup_errormsg_ie6');
        if(!el_ie6)
        {
            var el = document.getElementById('popup_errormsg');
            el_ie6 = el;
        
            el_ie6.id = 'popup_errormsg_ie6';
        
            document.body.appendChild(el_ie6);
        };
        
        showElement('popup_errormsg_ie6');
        blockToWindowCenter('popup_errormsg_ie6');
    }
    else
    {
        showElement('popup_errormsg');
        blockToWindowCenter('popup_errormsg');
    };
};

function hidePopupErrorMsg()
{
    if(navigator.userAgent.indexOf('MSIE 6') != -1)
    {
        hideElement('popup_errormsg_ie6');
    }
    else
    {
        hideElement('popup_errormsg');
    };
    
    hideFade();
};

function showPreviewMem() {
	var frm = document.forms['AddForm'];
	var act = frm.action;
	
	frm.action = "cms/addmem/preview";
	frm.target="_blank";
	
	frm.submit();
	
	frm.action = act;
	frm.target = "";
}

function setCookie (name, value, expires, path, domain, secure) {

      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function checkSections(obj) {
	var els = document.getElementById("sectionList").getElementsByTagName("input");
	var selected = 0;
	//obj.checked = !obj.checked;
	for(var i =0; i < els.length; i++) {
		if(els[i].type == "checkbox" && els[i].checked == true) {
			selected++;
		}
	}
	
	if(selected > 2) {
		obj.checked = false;
		alert("Образец может относиться не более чем к двум категориям!");
	}
	return !(selected > 2);
}

  $(document).ready(function(){

  	$("#bbg").click(function() {
		hideFade();
		$(".popup").hide();
  	});

  });

function video_missing_notification(_obj, _video_url) {
	if (confirm('Вы действительно хотите отправить уведомление о недоступности ролика?')) {
		$.ajax({
			url: '/ajax/missingvideonotification/',
			type: 'POST',
			data: {'video_url': _video_url}
		});
		$(_obj).html('Спасибо, уведомление отправлено редакторам!');
	}
}

var TagInputHelper = function(_obj_id)
{
	var instance = this;
	
	this.input_obj = $('#' + _obj_id);
	this.dropdown_obj = false;
	
	this.generateDropDown();
	
	this.list_position = -1;
	this.list_length = -1;
	
	this.min_litters = 1;
	
	this.is_preventing_submit = false;
	
	this.input_obj.parents('form').submit(
		function(e)
		{
			if (instance.is_preventing_submit)
			{
				return false;
			}
		}
	);
	
	this.input_obj.keydown(
		function(e)
		{
			var code;
		    if (!e) var e = window.event;
		    if (e.keyCode) code = e.keyCode;
		    else if (e.which) code = e.which;
		    
		    if (code == 13)
		    {
		    	instance.is_preventing_submit = true;
	    		setTimeout(
	    			function()
	    			{
	    				instance.is_preventing_submit = false;
	    			},
	    			500
	    		);
		    }
		}
	);
	
	this.input_obj.keyup(
		function(e)
		{
			var code;
		    if (!e) var e = window.event;
		    if (e.keyCode) code = e.keyCode;
		    else if (e.which) code = e.which;
					    
		    switch (code)
		    {
		    	
		    	case 37:
		    	case 39:
		    		break;
		    		
		    	case 38:
		    		instance.moveUpOnList();
		    		break;
		    		
		    	case 40:
		    		instance.moveDownOnList();
		    		break;
		    		
		    	case 13:
		    		instance.dropdown_obj.find('ul li:eq(' + instance.list_position + ')').click();
		    		break;
		    		
		    	case 27:
		    		instance.hideDropDown();
		    		break;
		    		
		    	default:
		    		instance.hideDropDown();
		    		if (instance.getCurrentValue().length >= instance.min_litters)
					{
						instance.updateList();
					}
		    		break;
		    		
		    }
		}
	);
}

TagInputHelper.prototype =
{
	
	generateDropDown: function()
	{
		var instance = this;
		
		this.dropdown_obj = $('<div class="tag-input-helper-dropdown" style="display: none;"><ul></ul></div>');
		
		this.dropdown_obj.mouseout(
			function()
			{
				$(this).find('ul li').removeClass('selected');
			}
		);
		
		this.dropdown_obj.bind('clickoutside',
			function(event) 
			{
				instance.hideDropDown();
			}
		);

		$('body').prepend(this.dropdown_obj);
	},
		
	showDropDown: function()
	{
		this.dropdown_obj.css('top', this.input_obj.offset().top + this.input_obj.outerHeight() + 'px');
		this.dropdown_obj.css('left', this.input_obj.offset().left + 'px');
		this.dropdown_obj.show();
	},
	
	hideDropDown: function()
	{
		this.dropdown_obj.hide();
		this.list_position = -1;
	},
	
	getCurrentValue: function()
	{
		return this.getInputValue().split(/,[\s]*/).pop();
	},
	
	setCurrentValue: function(_value)
	{
		tags = this.getInputValue().split(/,[\s]*/);
		tags.pop()
		tags.push(_value);
		this.setInputValue(tags.join(', ') + ', ');
	},
	
	getInputValue: function()
	{
		return this.input_obj.val();
	},
	
	setInputValue: function(_value)
	{
		this.input_obj.val(_value);
	},
	
	updateList: function()
	{
		var instance = this;
		$.getJSON(
			'ajax/taglist',
			{'str': instance.getCurrentValue()},
			function (_data)
			{
				instance.clearList();
				instance.list_position = -1;
				instance.list_length = _data['tag_list'].length;
				
				if (instance.list_length > 0)
				{
					for (i in _data['tag_list'])
					{
						instance.addListItem(_data['tag_list'][i]['name']);
					}
					instance.showDropDown();
				}
			}
		);
	},
	
	clearList: function()
	{
		this.dropdown_obj.find('ul li').remove();
	},
	
	addListItem: function(_tag)
	{
		var instance = this;
		
		obj = $('<li>' + _tag + '</li>');
		obj.click(
			function()
			{
				instance.setCurrentValue($(this).text());
				instance.input_obj.focus();
				instance.hideDropDown();
			}
		);
		obj.mouseover(
			function()
			{
				instance.dropdown_obj.find('ul li').removeClass('selected');
				$(this).addClass('selected');
			}
		);
		
		this.dropdown_obj.find('ul').append(obj);
		return obj;
	},
	
	moveUpOnList: function()
	{
		position = this.list_position;
		do
		{
			position--;
		}
		while (!this.dropdown_obj.find('ul li:eq(' + position + ')') && position > 0);
		
		if (this.dropdown_obj.find('ul li:eq(' + position + ')').length == 0) position = this.list_length - 1;
		
		this.setPositionOnList(position);
	},
	
	moveDownOnList: function()
	{
		position = this.list_position;
		do
		{
			position++;
		}
		while (!this.dropdown_obj.find('ul li:eq(' + position + ')') && position < this.list_length);
		
		if (this.dropdown_obj.find('ul li:eq(' + position + ')').length == 0) position = 0;
		
		this.setPositionOnList(position);
	},
	
	setPositionOnList: function(_position)
	{
		this.list_position = _position;
		this.dropdown_obj.find('ul li').removeClass('selected');
		this.dropdown_obj.find('ul li:eq(' + _position + ')').addClass('selected');
	}
}