var activeContainer = null;
var lightboxId = 'lightbox';
var defaultLightboxId = 'lightbox';
var isMessageInputed = false;
var isRulesSelected = false;
var isPermPage = false;

function login(networkId, element, icon, title)
{
    if (activeContainer == 'networks_list') {
        closeNetworksList();
        isPermPage = true;
    }

    var login = getCookie('network_login_' + networkId);
    activeContainer = 'login_form';
    $('login_form').down('div.lightbox-title').down('span').innerHTML = title;
    $('login_form').down('#icon').src = icon;

    if (login != null) {
        $('login_form').down('#data_login').value = login;
    }

    $('login_form').down('#data_network_id').value = networkId;
    $('login_form').show();
    showLightbox();
}

function loginForum(networkId, element, icon, title)
{
    if (activeContainer == 'networks_list') {
        closeNetworksList();
        isPermPage = true;
    }

    var login = getCookie('network_login_' + networkId);
    var url = getCookie('network_url_forum_' + networkId);
    activeContainer = 'login_form_forum';
    $('login_form_forum').down('div.lightbox-title').down('span').innerHTML = title;
    $('login_form_forum').down('#icon').src = icon;
    lightboxId = 'lightbox-login-forum';
    if (login != null) {
        $('login_form_forum').down('#data_login').value = login;
    }
    if (url != null) {
        $('login_form_forum').down('#data_url').value = url;
    }
    $('login_form_forum').down('#data_network_id').value = networkId;
    $('login_form_forum').show();
    showLightbox();
}

function networksList()
{
    activeContainer = 'networks_list';
    lightboxId = 'lightbox-login';
    $('networks_list').show();
    showLightbox('');
}

function invite()
{
    activeContainer = 'invite_form';
    lightboxId = 'lightbox-invite';
    $('invite_form').show();
    showLightbox('');
}

function viewOriginalMessage(id)
{
    activeContainer = 'original_message';
    lightboxId = 'lightbox-original';

    $('original_message').show();
    showLightbox('');

    showProcessing();

    new Ajax.Request('/original-message', {
        method: 'post',
          parameters: {id: id},
          onSuccess: function(transport){
              var response = transport.responseText;
              $('original_message').down('#original_shout').update(response);
              hideProcessing();
          }
    });
}

function closeViewOriginalMessage()
{
    $('original_message').hide();

    hideLightbox();
    lightboxId = defaultLightboxId;
}

function closeNetworksList()
{
    $('networks_list').hide();

    hideLightbox();
    lightboxId = defaultLightboxId;
}

function help(id, errors)
{

    activeContainer = 'lightbox-help-int';
    lightboxId = 'lightbox-help';

    $('lightbox-help-int').show();
    $('lightbox-help-int').down('#' + id).show();
    showLightbox('');

    var li02 = $('lightbox-help-int').down('#' + id).down('li.help-li02-act');

    if (!Object.isUndefined(li02)) {
        li02.removeClassName('help-li02-act');
        li02.addClassName('help-li02');
    }
    else {

        var li02 = $('lightbox-help-int').down('#' + id).down('li.help-li02');
    }

    var li01 = $('lightbox-help-int').down('#' + id).down('li.help-li01-act');

    if (!Object.isUndefined(li01)) {
	    li01.removeClassName('help-li01-act');
	    li01.addClassName('help-li01');
    }
    else {
        var li01 = $('lightbox-help-int').down('#' + id).down('li.help-li01');
    }

    if (Object.isUndefined(errors.rules) && !Object.isUndefined(errors.message)) {
        li02.removeClassName('help-li02');
        li02.addClassName('help-li02-act');
    }
    else if(!Object.isUndefined(errors.rules) && Object.isUndefined(errors.message)) {
        li01.removeClassName('help-li01');
        li01.addClassName('help-li01-act');
    }
}

function closeHelp()
{
    $('lightbox-help-int').hide();

    $('lightbox-help-int').down('#no-text').hide();
    $('lightbox-help-int').down('#no-criteria').hide();

    hideLightbox();
    lightboxId = defaultLightboxId;
}

function lightboxErrors()
{
    activeContainer = 'errors_content';
    lightboxId = 'lightbox-errors';
    $('errors_content').show();
    showLightbox();
}

function closeLightboxErrors()
{
    $('errors_content').hide();

    hideLightbox();
    lightboxId = defaultLightboxId;
}

function markAsSpam(shoutId, link)
{
    var content = $('shout_item-'+shoutId).down('.userinfo').innerHTML;
       /*
    if (Object.isElement($('shout_item-'+shoutId).down('.shout-tags').next('a.shout-user'))) {
        $('mark_as_spam_form').down('.user-spam').href = $('shout_item-'+shoutId).down('.shout-tags').next('a.shout-user').href;
        $('mark_as_spam_form').down('.user-spam').innerHTML = content;
        $('mark_as_spam_form').down('.user-spam').show();
        $('mark_as_spam_form').down('.user-spam').next('span').hide();
    }
    else {    */
        $('mark_as_spam_form').down('.user-spam').hide();
        $('mark_as_spam_form').down('.user-spam').next('span').show();
        $('mark_as_spam_form').down('.user-spam').next('span').update(content);
        $('mark_as_spam_form').down('.user-spam').next('span').down('a').className = 'user-spam';
    //}

    activeContainer = 'mark_as_spam_form';
    $('mark_as_spam_form').show();
    $('mark_as_spam_form').down('#data_shout_id').value = shoutId;

    lightboxId = 'lightbox-mark-as-spam';
    showLightbox('');
}

function closeMarkAsSpamForm()
{
    activeContainer = null;
    $("mark_as_spam_form").hide();

    clearForm('mark_as_spam_form');

    hideLightbox();
    lightboxId = defaultLightboxId;
}

function clearForm(form)
{
    var elements = $(form).down('form').getElements();
    elements.each(function(element){
        if (element.type !== 'submit') {
            element.value = '';
        }
    });

     var elements = $(form).select('.rowerror');
     elements.each(function(element){
         element.removeClassName('rowerror');
         element.addClassName('row');
     });

    $(form).down('div.lberrordiv').update('');
    //$(form).down('#message').update('');
}

function closeLoginForm()
{
    activeContainer = null;
    $("login_form").hide();

    var elements = $("login_form_element").getElements();
    elements.each(function(element){
        if (element.type !== 'submit') {
            element.value = '';
        }
    });

    $("login_form").down('div.lberrordiv').update('');
    //$("login_form").down('div.message_form').update('');

    hideLightbox();

    if (isPermPage) {
        networksList();
    }
}

function closeLoginForumForm()
{
    activeContainer = null;
    $("login_form_forum").hide();

    var elements = $("login_form_forum_element").getElements();
    elements.each(function(element){
        if (element.type !== 'submit') {
            element.value = '';
        }
    });

    $("login_form_forum").down('div.lberrordiv').update('');
    //$("login_form").down('div.message_form').update('');

    hideLightbox();

    if (isPermPage) {
        networksList();
    }
}

function closeFeedbackForm()
{
    hideProcessing();
    $("feedback_form").hide();
    hideLightbox();
    var elements = $("feedback_form").down('form').getElements();
    elements.each(function(element){
        if (element.type !== 'submit' && element.name != 'data[name]' && element.name != 'data[your_name]') {
            element.value = '';
        }
    });

    $("feedback_form").down('div.lberrordiv').update('');
    //$("feedback_form").down('#message').update('');

    lightboxId = defaultLightboxId;
    activeContainer = null;
}


function closeInviteForm()
{
    hideProcessing();
    $("invite_form").hide();
    hideLightbox();
    var elements = $("invite_form").down('form').getElements();
    elements.each(function(element){
        if (element.type !== 'submit' && element.name != 'data[name]' && element.name != 'data[your_name]') {
            element.value = '';
        }
    });

    $("invite_form").down('div.lberrordiv').update('');
    //$("invite_form").down('#message').update('');

    lightboxId = defaultLightboxId;
}

function feedback()
{
    lightboxId = 'lightbox-feedback';
    activeContainer = 'feedback_form';
    $(activeContainer).show();
    showLightbox('');
}

function submitForm(form, isShowProcessing, isHighlightFieldWithError, isShowErrorInLightbox)
{
	var form = $(form.id);

	if (form.id != 'add_rule_form' && isHighlightFieldWithError == false) {
	if (Object.isElement(form.previous('div.lberrordiv'))) {
    	form.previous('div.lberrordiv').update('');
	}
    }

    //form.previous('#message').update('');

    if (isHighlightFieldWithError) {
        var elements = form.select('.rowerror');
        elements.each(function(element){
            element.className='row';
        });
    }

    if (isShowProcessing) {
        showProcessing();
    }

    var params = form.serialize();

    new Ajax.Request(form.action, {
        method: 'post',
          parameters: params,
          onSuccess: function(transport){
            var response = transport.responseText;

            if (transport.responseText.isJSON()) {
                var response = transport.responseText.evalJSON();

                if (response.is_error) {
                    if (!isHighlightFieldWithError && form.id != 'add_rule_form') {
	                    var errors = response.errors.map(function(error){
	                       return error;
	                    }).join('<br/>');

                        if (isShowErrorInLightbox){
                            $('errors_content').down('div.lberrordiv').update(errors);
                            lightboxErrors();
                        }
                        else {
	                       form.previous('div.lberrordiv').update(errors);
	                    }
                    }
                    else if (form.id == 'add_rule_form') {
                        if (!Object.isUndefined(response.errors.message)) {
                            help('no-text', response.errors);
                        }
                        else {
                            help('no-criteria', response.errors);
                        }
                    }
                    else {
                        $H(response.errors).each(function(error){
                           if (error.key == 'recaptcha_response_field') {
                               form.down('#recaptcha_response_field').up('td.lbtd04').up('tr').removeClassName('row');
                               form.down('#recaptcha_response_field').up('td.lbtd04').up('tr').addClassName('rowerror');
                               Recaptcha.reload();
                           }
                           else {
                               form.down('#data_' + error.key).up('tr').removeClassName('row');
                               form.down('#data_' + error.key).up('tr').addClassName('rowerror');
                           }
                        });
                    }

                    if (isShowProcessing) {
                        hideProcessing();
                    }
                }
                else {

                    if (!Object.isUndefined(response.redirect_to)) {
                        window.location = response.redirect_to + '/update/' + Math.random();
                        window.location = response.redirect_to;
                        return false;
                    }
                    else if (!Object.isUndefined(response.message)) {

                        var elements = form.getElements();
                        elements.each(function(element){
                            if (element.type !== 'submit') {
                                element.value = '';
                            }
                        });

                        //form.previous('#message').update(response.message);
                    }
                    else if (!Object.isUndefined(response.function_name)) {
                        var functionName = response.function_name;
                        setTimeout(functionName + '()', 10);
                    }
                    else if (isShowProcessing) {
                        hideProcessing();
                    }
                }
            }

        },
          onFailure: function(){
             if (isShowProcessing) {
                 hideProcessing();
             }

             hideLightbox();

             alert('Connection failed, please try again');
          }
    });

}

function showLightbox(content)
{
    $(lightboxId).update(content);
    $(lightboxId).show();
    $('overlay').show();
}

function showProcessing()
{
    $(lightboxId).hide();
    $('lightbox-processing').show();
    $('lightbox-processing-int').show();
    $(activeContainer).hide();
}

function hideProcessing()
{
    $('lightbox-processing').hide();
    $('lightbox-processing-int').hide();
    $(lightboxId).show();
    $(activeContainer).show();
}

function hideLightbox()
{
    $(lightboxId).hide();
    $('overlay').hide();
}

function observeRules(containerId)
{
    var container = $(containerId);
    var elements = container.select('span');

    elements.each(
        function(element){
            $(element).observe('click', function(event) {
                hideAllMatches();
                addRule(Event.element(event), true);
            });

            $(element).observe('mouseover', function(event) {
                Event.element(event).addClassName('rule_mouseover');
            });

            $(element).observe('mouseout', function(event) {
                Event.element(event).removeClassName('rule_mouseover');
            });
        }
    );
}

function observeLabels(containerId)
{
    var container = $(containerId);
    var elements = container.select('b.lb');

    elements.each(
        function(element){
            
            $(element).observe('click', function(event) {
		var subElements = determineSubElements(Event.element(event));
		subElements.each(function(element){
                	addRule(element, true);
		});
            });

            $(element).observe('mouseover', function(event) {
		var subElements = determineSubElements(Event.element(event));
		subElements.each(function(element){
                	element.addClassName('rule_mouseover');
		});
            });

            $(element).observe('mouseout', function(event) {
		var subElements = determineSubElements(Event.element(event));
		subElements.each(function(element){
                	element.removeClassName('rule_mouseover');
		});
            });
        }
    );
}

function determineSubElements(element)
{
	var subElements = Array();
	
	var i = 100;
	var el = element.next('span');
	while(i > 0) {
	subElements[subElements.length] = el;
	el = el.next();
	if (el.id == '') {
		break;
	}
	i--;
	}
	return subElements;
}

function addRule(element, isReplaceDoublingValue)
{

    if (element.innerHTML == '') {
        return false;
    }
    //alert(element.innerHTML);
    element.addClassName('rule_selected');

    var inputElement = $('add_rule_form').down('#data_rules');
    var addedRules = $F(inputElement);

    if (addedRules != '' && addedRules.isJSON()) {
        addedRules = addedRules.evalJSON();
    }
    else {
        addedRules = {rules:[]};
    }

    var res = extractFieldName(element.id);
    var fieldName = res.fieldName;
    var isListRules = res.isListRules;

    var newArray = {rules:[]};
    var fieldRemoved = false;
    var isRulesSet = false;
    var valueSet = false;

    addedRules.rules.each(
        function(e) {
            if (e.field != fieldName) {
                newArray.rules[newArray.rules.length] = e;
                isRulesSet = true;
            }
            else {
                if (isListRules == true) {
                    var value = element.innerHTML;

                    if (!isInt(value)) {
                        value = value.toLowerCase();
                    }

                    if (value != '') {
                        var pattern = new RegExp(''+value+ ',');

                        if (e.value.match(pattern) !== null) {
                            if (isReplaceDoublingValue) {
	                            findMatchValueInField(fieldName, value, function(element){ element.removeClassName('rule_selected'); });
	                            value = e.value.replace(''+value+',', '');
	                            e.value = value;
	                            if(e.value !='' && e.value!=' ') {
	                                newArray.rules[newArray.rules.length] = e;
	                            }
	                            fieldRemoved = true;
                            }
                        }
                        else {
                            findMatchValueInField(fieldName, value, function(element){ element.addClassName('rule_selected'); });
                            e.value = e.value + value + ',';
                            newArray.rules[newArray.rules.length] = e;
                            isRulesSet = true;
                            valueSet = true;
                        }
                    }
                }
                else {
                    fieldRemoved = true;
                    element.removeClassName('rule_selected');
                }
            }
        }
    );

    addedRules = newArray;

    if (!fieldRemoved && !valueSet) {
        isRulesSet = true;
        var backendMark = '';

        if (isListRules) {
            backendMark = ',';
        }

        var value = element.innerHTML;
        value = value.toLowerCase();

        findMatchValueInField(fieldName, value, function(element){ element.addClassName('rule_selected'); });
        addedRules.rules[addedRules.rules.length] = {field: fieldName, value: value + backendMark};
    }

    if (!Object.isUndefined(addedRules.rules) && addedRules.rules.length > 0) {
        if ($('add_rule_form').down('#data_parent_id').value == '') {
            $('link_remove_rules').show();
        }

        isRulesSelected = true;
    }
    else {

        isRulesSelected = false;
        $('link_remove_rules').hide();
    }

    checkMessageAndRules();

    if (addedRules.rules.length > 0) {
        inputElement.value = Object.toJSON(addedRules);
    }
    else {
        inputElement.value = '';
    }

    new Ajax.Request('/save-selected-rules', {
        method: 'post',
          parameters: 'rules=' + $F(inputElement),
          onSuccess: function(transport){
          }
    });
}

function findMatchValueInField(fieldName, value, func)
{
    for (var i=0; ; i++) {
        var element = $(fieldName + '['+i+']');

        if (Object.isElement(element)) {
            var strValue = element.innerHTML;
            //alert(strValue.toLowerCase() + '=' + value.toLowerCase());

            if (!isInt(strValue)) {
                strValue = strValue.toLowerCase();
            }

            if (!isInt(value)) {
                value = value.toLowerCase();
            }

            if (strValue == value) {

                func(element);
            }
        }
        else {
            break;
        }
    }
}

function extractFieldName(fieldName)
{
    var pattern = new RegExp(/[a-z_]{1,}\[[0-9]{1,}\]/i);
    var res = fieldName.match(pattern);
    var isListRules = false;

    if (res !== null) {
        isListRules = true
        var pattern = new RegExp(/[a-z_]{1,}/i);
        fieldName = fieldName.match(pattern);
        fieldName = fieldName[0];
    }

    return {'fieldName': fieldName, 'isListRules': isListRules};
}

function stripMarks(value)
{
    return value.replace(/\.|\?|!|,/, '');
}

function hMatch(element)
{
    element.addClassName('rule_match');
}

function findMatches(matches, func)
{
    var rulesContainer = $('rules');
    var ruleElements = rulesContainer.select('span');

    ruleElements.each(function(element){
        var res = extractFieldName(element.id);
        var fieldValue = element.innerHTML;

        $H(matches).each(function(match){
            if (res.fieldName == match.key) {
                var value = match.value;

	            if (!isInt(fieldValue)) {
	                fieldValue = fieldValue.toLowerCase();
	            }

	            if (!isInt(value)) {
	                value = value.toLowerCase();
	            }

                if (fieldValue == value && !res.isListRules) {
                    func(element);
                }
                else if(res.isListRules) {
                    var value = match.value;
                    var values = value.split(',');

                    values.each(function(value){
                        if (fieldValue.toLowerCase() == value.toLowerCase()) {
                            func(element);
                        }
                    });
                }
            }
        });
    });
}

function showMatches(matches, link)
{
    findMatches(matches, function(element){ hMatch(element) });
    $('hide_all_matches_link').show();
    link.up('div').hide();
    link.up('div').next('div#hide_matches').show();
}

function hideAllMatches()
{
    var rulesContainer = $('rules');
    var ruleElements = rulesContainer.select('span.rule_match');

    ruleElements.each(function(element){
        element.removeClassName('rule_match');
    });

    $('hide_all_matches_link').hide();

    var elements = $('shouts_list').select('div#show_matches');
    elements.each(function(element){
        element.show();
    });

    var elements = $('shouts_list').select('div#hide_matches');
    elements.each(function(element){
        element.hide();
    });
}

function hideMatches(matches, link)
{
    findMatches(matches, function(element){ element.removeClassName('rule_match'); });

    var rulesContainer = $('rules');
    var ruleElements = rulesContainer.select('span.rule_match');
    var hideAll = true;

    ruleElements.each(function(element){
        hideAll = false;
    });

    if (hideAll) {
        hideAllMatches();
    }

    link.up('div').hide();
    link.up('div').previous('div#show_matches').show();
}

function replyShout(matches, id, parentId, isDirectReply)
{
    var shout = $('shout_item-' + id).innerHTML;
//alert(shout);
    $('reply_shout').update(shout);

    ['div.shout-bg-01', 'div.shout-bg', 'div.shout-bg-02', 'div.reply-bg-01', 'div.reply-bg', 'div.reply-bg-02'].each(function(selector) {
        var element = $('reply_shout').down(selector);

        if (Object.isElement(element)) {
            selector = selector.replace(/div\./, '');
            element.removeClassName(selector);
            var className = selector.replace(/reply-/, 'shoutreply-');
            className = className.replace(/shout-/, 'shoutreply-');
            element.addClassName(className);
        }
    });

    $('reply_shout').down('div.shout-manage').hide();
    $('add_rule_form').down('#data_parent_id').value = parentId;
    $('add_rule_form').down('div.saybox-textarea').down('textarea').value = '';
    $('add_rule_form').down('div.saybox-textarea').down('textarea').focus();

    $('direct_reply_checkbox').show();
    $('say_title').hide();
    $('reply_title').show();

    hideAllMatches();
    removeSelectedRules();

    if (isDirectReply) {
        $('add_rule_form').down('#data_is_direct_reply').checked = true;
    }
    else {
        $('add_rule_form').down('#data_is_direct_reply').checked = false;
    }

    findMatches(matches, function(element){ addRule(element, false)});

    $('cancel_reply').show();
    $('reply_shout').show();

    new Ajax.Request('/save-selected-replay-shout', {
        method: 'post',
          parameters: 'shout_id='+parentId,
          onSuccess: function(transport){
          }
    });
}

function replyCancel()
{
    removeSelectedRules();

    $('add_rule_form').down('#data_parent_id').value = '';
    $('add_rule_form').down('div.saybox-textarea').down('textarea').value = '';
    $('reply_shout').hide();
    $('cancel_reply').hide();
    $('direct_reply_checkbox').hide();
    $('say_title').show();
    $('reply_title').hide();

    //$('add_rule_form').previous('div.lberrordiv').update('');
    //$('add_rule_form').previous('#message').update('');

    new Ajax.Request('/remove-selected-replay-shout', {
        method: 'post',
          parameters: '',
          onSuccess: function(transport){
          }
    });
}

function removeSelectedRules()
{
    var rulesContainer = $('rules');
    var ruleElements = rulesContainer.select('span.rule_selected');

    ruleElements.each(function(element){
        element.removeClassName('rule_selected');
    });

    $('add_rule_form').down('#data_rules').value = '';
    $('link_remove_rules').hide();

    new Ajax.Request('/remove-selected-rules', {
        method: 'post',
          parameters: '',
          onSuccess: function(transport){
          }
    });
    isRulesSelected = false;
    checkMessageAndRules();
}

function setDefaultRules(rules)
{
    findMatches(rules, function(element){ addRule(element, false)});
}

function autoRefresh(status)
{
    if (status == 1) {
        $('refresh_on').hide();
        $('refreshing').show();
        startTimer();
        $('refresh_off').show();
        $('refresh_status').update('On');
        saveParam('refresh_status', 1);
    }
    else {
        $('refresh_on').show();
        stopTimer();
        $('refresh_off').hide();
        $('refreshing').hide();
        $('refresh_status').update('Off');

        saveParam('refresh_status', 0);
    }
}

var timerID = 0;
var tStart  = null;
var refreshTime = 15;

function updateTimer()
{
    if (timerID) {
        clearTimeout(timerID);
        clockID  = 0;
    }

    if (!tStart)
      tStart   = new Date();

    var tDate = new Date();
    var tDiff = tDate.getTime() - tStart.getTime();

    tDate.setTime(tDiff);
    var sec = tDate.getSeconds();
    var tLeft = refreshTime - sec;

    if (tLeft == 0) {
        $('refreshing').down('#timer').innerHTML = ' 0 sec';
        stopTimer();
        startTimer();
        refreshShoutList();
    }
    else {
        $('refreshing').down('#timer').innerHTML = ' ' + tLeft + ' sec';
        timerID = setTimeout("updateTimer()", 1000);
    }
}

function startTimer() {
    tStart   = new Date();
    $('refreshing').down('#timer').innerHTML = ' ' + refreshTime +' sec';
    timerID  = setTimeout('updateTimer()', 1000);
}

function stopTimer() {
    if (timerID) {
        clearTimeout(timerID);
        timerID  = 0;
    }

    tStart = null;
}

function refreshShoutList()
{
    new Ajax.Request('/refresh-shout', {
        method: 'post',
          parameters: '',
          onSuccess: function(transport){

            if (transport.responseText.isJSON()) {
                var response = transport.responseText.evalJSON();
                window.location = response.redirect_to;
            }

            new Ajax.Updater('tab_shouts_all', '/shouts-all-list', {
              parameters: {}
            });
            new Ajax.Updater('tab_shouts_replies', '/shouts-replies-list', {
              parameters: {}
            });
          }
    });
}

function updateShoutList(type, page, link, typeNav)
{
    if (type == 'all') {
        var action = '/shouts-all-list';
        var containerId = 'tab_shouts_all';
    }
    else {
        var action = '/shouts-replies-list';
        var containerId = 'tab_shouts_replies';
    }

    if (!Object.isUndefined(typeNav) && (typeNav == 'next' || typeNav == 'prev')) {
        link.className = 'paging-process';
        $('page-process-image').show();
    }
    else {
        link.innerHTML = '...';
        link.className = 'page-clicked';
    }

    new Ajax.Request(action, {
        method: 'post',
          parameters: { page: page },
          onSuccess: function(transport){
            if (transport.responseText.isJSON()) {
                var response = transport.responseText.evalJSON();
                window.location = response.redirect_to;
            }
            else {
                $(containerId).update(transport.responseText);
                new Effect.ScrollTo('shouts_list', {duration: 0.1});
            }
          }
    });
}

function replaceMarkersInMatches()
{
    var matchesList = $('shouts').select('#matches_str');
    var pattern = new RegExp(/, ;/i);

    matchesList.each(function(element) {
        var value = element.innerHTML;
        value = value.replace(/, ;/, ';');
        value = value.replace(/, ; /, ';');

        element.innerHTML = value;
    });
}

function showAllBloggerBlogs()
{
    activeContainer = 'blogger_form';
    lightboxId = 'lightbox';
    $('blogger_form').show();
    showLightbox('');
}

function closeBloggerForm()
{
    activeContainer = null;
    $("blogger_form").hide();

    var elements = $("blogger_form").down('form').getElements();
    elements.each(function(element){
        if (element.type !== 'submit') {
            element.value = '';
        }
    });

    $("blogger_form").down('div.lberrordiv').update('');
    //$("blogger_form").down('#message').update('');

    hideLightbox();
    window.location = '/shouts';
}

function showFullMessage(link, id)
{
    $('shout_brief_message_'+id).hide();
    $('shout_full_message_'+id).show();
}

function showBriefMessage(link, id)
{
    $('shout_brief_message_'+id).show();
    $('shout_full_message_'+id).hide();
}

function updateTextCounter(value, e) {
    value = value.stripTags();

    len = value.length;
    $('text_counter').update(len);

    if (len > 1500) {
        $('text_counter').className = 'wrong_counter';
    }
    else {
        $('text_counter').className = '';
    }

    if (len > 0 && len < 1500) {
        isMessageInputed = true;
    }
    else {
        isMessageInputed = false;
    }

    checkMessageAndRules();
}

function showShoutsList(type, link)
{
    if (type == 'all') {
        //link.removeClassName('alllink');
        link.className = 'alllink-act';

        var linkPrev = document.getElementsByClassName('replieslink-act')[0];
        //alinkPrev.removeClassName('replieslink-act');
	if (!Object.isUndefined(linkPrev)) {
            linkPrev.className = 'replieslink';
        }

        //var activeTab = $('shouts_list').down('#tab_replies');
        var container = $('shouts').down('#tab_shouts_all');
        var activeContainer = $('shouts').down('#tab_shouts_replies');
        saveParam('active_tab', 'tab_shouts_all');
    }
    else {
        link.className = 'replieslink-act';

        var linkPrev = document.getElementsByClassName('alllink-act')[0];

	if (!Object.isUndefined(linkPrev)) {
        	linkPrev.className = 'alllink';
        }
        var container = $('shouts').down('#tab_shouts_replies');
        var activeContainer = $('shouts').down('#tab_shouts_all');
        saveParam('active_tab', 'tab_shouts_replies');
    }

    activeContainer.hide();

    container.show();
    activeContainer.hide();
    container.show();
}

function saveParam(paramName, paramValue)
{
    new Ajax.Request('/shout/save-param', {
        method: 'post',
          parameters: {param_name: paramName, param_value: paramValue },
          onSuccess: function(transport){
          }
    });
}

function isInt(value)
{
   var y = parseInt(value);
   if (isNaN(y)) return false;
   return value == y && value.toString() == y.toString();
}

function checkMessageAndRules()
{
    if (isMessageInputed && isRulesSelected) {
        //$('add_rule_form').down('#submit').writeAttribute('disabled', false);
        $('add_rule_form').down('#submit').removeClassName('senditbutton-disabled');
        $('add_rule_form').down('#submit').addClassName('senditbutton');
    }
    else {

        //$('add_rule_form').down('#submit').writeAttribute('disabled', true);
        $('add_rule_form').down('#submit').removeClassName('senditbutton');
        $('add_rule_form').down('#submit').addClassName('senditbutton-disabled');
    }
}


function getCookie(name)
{
    var results = document.cookie.match ('(^|;) ?' + name + '=([^;]*)(;|$)');

    if (results) {
        return (unescape(results[2]));
    }
    else {
        return null;
    }
}

function showImage(src, width, height)
{
    activeContainer = 'lightbox_image';
    lightboxId = 'lightbox-custom';

    $('lightbox_image').show();
    $('image_body').update('<img src="'+src.replace(' ', '')+'">');

    if (width < 500) {
        width=500;
	$('lightbox_image').down('ul').setStyle({left:'500px'});
    }
    else {
        $('lightbox_image').down('ul').setStyle({left:width+'px'});
    }

    height = height+110;
    width = width+60;
    $('lightbox-custom-int').setStyle({width: width+'px', height: height+'px'});

    width = width+21;
    height = height+21;

    $('lightbox-custom').setStyle({width: width+'px', height: height+'px'});

    showLightbox('');

}

function closeImageBlock()
{
    $('lightbox_image').hide();

    hideLightbox();
    lightboxId = defaultLightboxId;
}

function useEditor(status)
{
    if (status == 1) {
        $('editor_on').hide();
        $('editor_off').show();
	saveParam('editor_status', 1);


	tinyMCE.init({
		mode : "textareas",
		theme : "simple",
		//editor_selector : "mceEditor",
                //editor_deselector : "mceNoEditor",
		setup: function(ed) {
                  if (ed.id == 'data_message')
		  {
                   //alert('ssas');
		  }
                  else {
                    ed.remove();
                  }
		}
	});

	setTimeout('observeEditor()', 1000);
	$('editor_status').update('On');
    }
    else {
        $('editor_on').show();
        $('editor_off').hide();
	$('editor_status').update('Off');
        saveParam('editor_status', 0);

        tinyMCE.activeEditor.remove();
    }
}

function observeEditor()
{
    if ($('editor_off').style.display != 'none') {
	$('add_rule_form').down('textarea').value = tinyMCE.activeEditor.getContent({format : 'text'});
	updateTextCounter(tinyMCE.activeEditor.getContent({format : 'text'}));
	setTimeout('observeEditor()', 100);
    }
}
