/**
 * @author Sicabol
 */
var anr_focus = "";
var articles_datatable;
var search_datatable;
var max_profiles = 0;
var is_validator = 0;
var is_deleter = 0;
var is_setter = 0;
var has_newsletters = 0;

$(document).ready(function() {
    resize_views();

    jQuery.expr[':'].text_search = function(elem, index, match){
        var search = match[3];
        if (!search) return false;
        search = new RegExp("\\b(" + search + ")\\w*\\b", "gi");
        return eval(search).test($(elem).text());
    };

    $('a.external').attr('target', '_blank');
    $("a[href^='mailto']").css('font-weight', 'bold');

    $('#search_engine').focus(show_search_options).mouseenter(show_search_options).keypress(show_search_options).blur(hide_search_options).mouseleave(hide_search_options);
    $('#search_engine_options input[type=checkbox]').change(function(){
        $('#search_engine_options input:checked').prop('checked', false);
        $(this).prop('checked', true);
    });

    $('.hidden_buttons_trigger').mouseenter(function() {
        $(this).children('.hidden_button').removeClass('hidden_button').addClass('shown_button');
    }).mouseleave(function() {
        $(this).children('.shown_button').removeClass('shown_button').addClass('hidden_button');
    });

    $('.required').mark_required();
    
    $('body').append('<div id="fadingalert" class="ui-widget"><div id="fadingalertdiv" class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;"><p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span><span id="fadingalertmsg"></span></p></div></div>');

    $(window).bind('keydown', function(event){
        if (anr_focus == ''){
            switch (event.keyCode) {
                case 27:
                    hide_article_view();
                    break;
            }
        }
    });
});

function fadingalert(msg, is_error) {
    if (is_error != undefined) {
        $('#fadingalertdiv').removeClass('ui-state-highlight').addClass('ui-state-error');
    } else {
        $('#fadingalertdiv').removeClass('ui-state-error').addClass('ui-state-highlight');
    }
    $('#fadingalertmsg').html(msg);
    $('#fadingalert').fadeTo(500, 0.9).delay(4000).fadeOut(500);
}

function exit_alert(){
    if ($('#article_view').is(':visible')) {
        return "IMPORTANT : L'interface Ask'n'Read est sur le point de fermer. Si ce n'est pas une demande de votre part, il est préférable de cliquer sur le bouton \"Annuler\" ou \"Non\" ci-dessous. Merci de votre compréhension.";
    }
}
window.onbeforeunload = exit_alert;

$.fn.tagName = function() {
    return this.get(0).tagName.toLowerCase();
}

function valid_email(email) {
    var reg = /^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,3}$/;
    return (reg.exec(email) != null);
}

function valid_password(username) {
    var reg = /^[a-zA-Z0-9_-]{4,32}$/;
    return (reg.exec(username) != null);
}

function is_array(input){
    return typeof(input)=='object'&&(input instanceof Array);
}

$.fn.draw_date_groups = function(oSettings) {
    resize_views();
    if (oSettings.aiDisplay.length == 0) {
        return;
    }
    var nTrs = $('tbody tr', $(this));
    var iColspan = nTrs.eq(0).children('td').length;
    var sLastGroup = "";
    for (var i = 0; i < nTrs.length; i++) {
        nTrs.eq(i).addClass('article_' + nTrs.eq(i).children('.link_id').text()).addClass('article_from_list');
        var sGroup = oSettings.aoData[oSettings.aiDisplay[i]]._aData[1];
        if (sGroup != sLastGroup) {
            var nGroup = $('<tr></tr>');
            var nCell = $('<td></td>');
            nCell.attr('colspan', iColspan).addClass("date_group").html(sGroup);
            nGroup.append(nCell).insertBefore(nTrs.eq(i));
            sLastGroup = sGroup;
        }
    }
}

$.fn.mark_required = function() {
    var id = $(this).attr('id');
    if (id != undefined) {
        var label = $('label[for=' + id + ']');
        if (label.length && label.data('required_tag') == undefined) {
            var title = "Mandatory value";
            label.data('required_tag', true).html(label.html() + ' *').attr('title', title);
            $(this).attr('title', title);
        }
    }
}

$.fn.resize_title = function() {
    $(this).each(function() {
        while ($(this)[0].scrollHeight > $(this).height()) {
            $(this).text($(this).text().substring(0, $(this).text().lastIndexOf(' ')) + "…");
        }
    });
}

function test_role(role) {
    $.ajax({
        url: site_domain + "account/test_role/" + role,
        type: "GET",
        dataType: "json",
        cache: false,
        success: function(data){
            if ( ! data || data.response == false) {
                self.location.replace(site_domain);
            } else {
                setTimeout(function() {test_role(role);}, 300000);
            }
        }
    });
}

function resize_views() {
    if ($('#global_content_basic').length) {
        $('#global_content_basic').height($(window).height() - $('#footer').outerHeight() - $('#global_content_basic').offset().top - 25);
    }
    if ($('#menu_profiles_content').length) {
        $('#profile_content_view').height($(window).height() - $('#footer').outerHeight() - $('#profile_content_view').offset().top);
        $('#menu_profiles_content').height($(window).height() - 131);
        $('#liste_profiles').height($('#profiles_buttons').offset().top - $('#liste_profiles').offset().top);
    }
    if ($('#search_view').is(':visible')) {
        $('#search_view').height($(window).height() - 72);
        $('#search_content_view').height($(window).height() - 136);
    }
    if ($('#article_view').is(':visible')) {
        var hauteur_view = $(window).height() - 72;
        $('#article_view').height(hauteur_view);
        $('iframe#article_preview_browser').height(hauteur_view - 51);
    }
}
$(window).resize(resize_views);

var Utf8 = {
    // Encodage en UTF-8
    encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else
                if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
                else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
        }
        return utftext;
    },

    // Décodage en UTF-8
    decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else
                if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                }
                else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
        }
        return string;
    }
}

function escapeUTF8(s) {
    return escape(Utf8.encode(s).replace(/\+/, '%2B'));
}

function unescapeUTF8(s) {
    return Utf8.decode(unescape(s));
}

function array_unique(arrayName) {
    if (arrayName != null){
        var newArray = new Array();
        label:for(var i = 0; i < arrayName.length; i++){
            for(var j = 0; j < newArray.length; j++ ){
                if (newArray[j] == arrayName[i])
                    continue label;
            }
            newArray.push(arrayName[i]);
        }
        return newArray;
    } else {
        return arrayName;
    }
}

function array_trim(arrayName) {
    var newArray = [];
    if (arrayName != null) {
        for (var i = 0; i < arrayName.length; i++) {
            var value = $.trim(arrayName[i]);
            if (value != '') {
                newArray.push(value);
            }
        }
    }
    return newArray;
}

function in_array(needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack)
            if (haystack[key] === needle)
                return true;
    }
    else {
        for (key in haystack)
            if (haystack[key] == needle)
                return true;
    }
    return false;
}

function correct_inputs() {
    $('input[type="text"]').each(function(){
        $(this).val($(this).val().replace(/&amp;/g, '&').replace(/&#039;/g, '\'').replace(/&quot;/g, '"'));
    });
}


// * MES DOSSIERS *****
function refresh_content(articles_list) {
    articles_list = $(articles_list);
    if (articles_list.hasClass('datatable')) {
        articles_list.dataTable().fnClearTable().fnDraw();
    } else {
        $('#menu_profiles_content li.opened a').eq(0).trigger('click');
    }
}

function get_opened_profile_id() {
    var opened_profile = $('#liste_profiles .opened');
    if (opened_profile.length) {
        return opened_profile.attr('id').substring(13);
    } else {
        return false;
    }
}

function move_profile(direction){
    var profile = $('#liste_profiles .opened');
    if (profile.length) {
        id = profile.attr('id').substring(13);
        var tmp_liste_profiles = $('ul#liste_profiles');
        var index = $('li', tmp_liste_profiles).index(profile);
        if (index != -1) {
            var profile2 = (direction == 'up' ? profile.prev() : profile.next());
            if (profile2.length) {
                var id2 = profile2.attr('id').substring(13);
                $.post(site_domain + 'account/folders/move_profile?user=' + preview_user, {
                    'id1': id,
                    'id2': id2
                }, function(data){
                    if (data != 'OK') {
                        alert("An error occurred…");
                    }
                });
                if (direction == 'up') {
                    $(profile).insertBefore($(profile2));
                }
                else {
                    $(profile).insertAfter($(profile2));
                }
            }
        }
    }
}

function new_profile() {
    var nb_profiles = $('ul#liste_profiles .menu_profiles').length;
    if (nb_profiles < max_profiles) {
        $('#dialog_new_profile').dialog('open');
    } else {
        var msg = "You have reached the limit of _XXXX_ folders.";
        alert(msg.replace(/_XXXX_/gi, max_profiles));
        return false;
    }
}

function del_profile(){
    var profile = $('#liste_profiles .opened');
    if (profile.length) {
        profile_id = profile.attr('id').substring(13);
        var profile_title = $('a .menu_profile_title', profile).text();
        var msg = "Etes-vous sûr de vouloir supprimer définitivement votre dossier \"_XXXX_\" ?";
        $('#dialog_del_profile').html(msg.replace(/_XXXX_/gi, profile_title)).dialog('open');
    }
    return false;
}

function display_glimpse() {
    var elem = $('#profile_content');
    $('#profile_content_title').html($('.menu_profile_glimpse').text());
    $('#profile_content_subtitle').text('');
    $("#profile_content_view").html('<span class="wait">Please wait…</span>').css('padding-left', 34);
    $('#profile_content').css('background-position', '-50px bottom');
    $('#menu_profiles_content li.opened').removeClass('opened').find('.menu_profile_links').slideUp(500);
    $('#menu_profiles_content li.menu_profile_glimpse').addClass('opened');
    $("#profile_content_view").load(site_domain + 'account/folders/glimpse?user=' + preview_user);
    $('#profile_content_icon').attr('class', 'icon_glimpse');
}

function display_last_minute() {
    var elem = $('#profile_content');
    $('#profile_content_title').html($('.menu_profile_last_minute').text());
    $('#profile_content_subtitle').text('');
    $("#profile_content_view").html('<span class="wait">Please wait…</span>').css('padding-left', 34);
    $('#profile_content').css('background-position', '-50px bottom');
    $('#menu_profiles_content li.opened').removeClass('opened').find('.menu_profile_links').slideUp(500);
    $('#menu_profiles_content li.menu_profile_last_minute').addClass('opened');
    $("#profile_content_view").load(site_domain + 'account/folders/last_minute?user=' + preview_user);
    $('#profile_content_icon').attr('class', 'icon_last_minute');
}

function display_last_archives() {
    var elem = $('#profile_content');
    $('#profile_content_title').html($('.menu_profile_last_archives').text());
    $('#profile_content_subtitle').text('');
    $("#profile_content_view").html('<span class="wait">Please wait…</span>').css('padding-left', 34);
    $('#profile_content').css('background-position', '-50px bottom');
    $('#menu_profiles_content li.opened').removeClass('opened').find('.menu_profile_links').slideUp(500);
    $('#menu_profiles_content li.menu_profile_last_archives').addClass('opened');
    $("#profile_content_view").load(site_domain + 'account/folders/last_archives?user=' + preview_user);
    $('#profile_content_icon').attr('class', 'icon_last_archives');
}

function display_sendings() {
    var elem = $('#profile_content');
    $('#profile_content_title').html($('.menu_profile_sendings').text());
    $('#profile_content_subtitle').text('');
    $("#profile_content_view").html('<span class="wait">Please wait…</span>').css('padding-left', 34);
    $('#profile_content').css('background-position', '-50px bottom');
    $('#menu_profiles_content li.opened').removeClass('opened').find('.menu_profile_links').slideUp(500);
    $('#menu_profiles_content li.menu_profile_sendings').addClass('opened');
    $("#profile_content_view").load(site_domain + 'account/folders/sendings?user=' + preview_user);
    $('#profile_content_icon').attr('class', 'icon_sendings');
}

function change_profile_content(id, type, article_id, article_host) {
    var elem = $('#profile_content');
    var profile;
    if (id == 0) {
        profile = $('#liste_profiles .opened');
        if (profile.length) {
            id = profile.attr('id').substring(13);
        }
    } else {
        profile = $('#menu_profile_' + id);
    }
    if (profile.length) {
        $('#profile_content_title').html($('a span.menu_profile_title', profile).text());
        $('#profile_content_subtitle').text($('.menu_profile_' + type, profile).text());
        $("#profile_content_view").html('<span class="wait">Please wait…</span>').css('padding-left', 70);
        $('.articles_count').html('');
        $('#profile_content').css('background-position', '-1px bottom');
        if ($('#menu_profiles_content li.opened').attr('id') != 'menu_profile_' + id) {
            $('#menu_profiles_content li.opened').removeClass('opened').find('.menu_profile_links').slideUp(500);
            profile.addClass('opened').find('.menu_profile_links').slideDown(500, function() {
                show_profile_in_menu();
            });
        }
        $('.profile_actions li.selected_view').removeClass('selected_view');
        $('.profile_actions li.profile_actions_' + type).addClass('selected_view');
        $('#profile_content_info h4').html($('div#profile_content_buttons ul li.profile_actions_' + type + ' a span').text());
        switch (type) {
            case 'settings':
                $("#profile_content_view").load(site_domain + 'account/folders/settings/' + id + '?user=' + preview_user, function() {
                    correct_inputs();
                    show_query_helper();
                });
                break;
            default:
                $("#profile_content_view").load(site_domain + 'account/folders/' + type + '/' + id + '?user=' + preview_user);
                break;
        }
        $('#profile_content_icon').attr('class', 'icon_folder');
    }
}

function show_profile_in_menu() {
    var profile = $('#liste_profiles .opened');
    if (profile.length) {
        var liste_profiles = $('#liste_profiles');
        var delta_moins = liste_profiles.offset().top - profile.offset().top + 30;
        if (delta_moins > 0) {
            liste_profiles.animate({
                'scrollTop': '-=' + delta_moins + 'px'
            }, 'slow');
        } else {
            var delta_plus = profile.offset().top - liste_profiles.offset().top + profile.height() - liste_profiles.height() + 30;
            if (delta_plus > 0) {
                liste_profiles.animate({
                    'scrollTop': '+=' + delta_plus + 'px'
                }, 'slow');
            }
        }
    }
}

function toggle_query_helper(){
    if ($('#db_query').is(':visible')) {
        show_query_helper();
    }
    else {
        query_helper_ok();
    }
}

function parenthesis_to_brackets(query){
    var tmp_flag = 0;
    var tmp_flag_quotes = 0;
    query = query.replace(/\s+/g, ' ');
    for (i = 0; i < query.length; i++) {
        switch (query.substring(i, i + 1)){
            case '(' :
                query = query.substring(0, i) + '[' + query.substring(i + 1, query.length);
                tmp_flag ++;
                break;
            case ')' :
                query = query.substring(0, i) + ']' + query.substring(i + 1, query.length);
                tmp_flag --;
                break;
            case '|' :
                if (tmp_flag)
                    query = query.substring(0, i) + '§' + query.substring(i + 1, query.length);
                break;
            case '"' :
                query = query.substring(0, i) + '`' + query.substring(i + 1, query.length);
                tmp_flag_quotes = (tmp_flag_quotes) ? false : true;
                break;
            case ' ' :
                if (tmp_flag_quotes || tmp_flag)
                    query = query.substring(0, i) + '_' + query.substring(i + 1, query.length);
                break;
        }
    }
    return query;
}
function brackets_to_parenthesis(query){
    return query.replace(/\[/g, '(').replace(/\]/g, ')').replace(/[§|]/g, ' | ').replace(/`/g, '"').replace(/_/g, ' ').replace(/\s+/g, ' ');
}

function get_words(query){
    query = ' ' + query + ' ';
    return array_trim(query.replace(/(\s+)?\|(\s+)?/g, '|').replace(/(\s+)?>>(\s+)?/g, '>>').replace(/\s+/g, ' ').replace(/" "/g, '"  "').replace(/" \(/g, '"  (').replace(/\) "/g, ')  "').match(/[+-=]?(\(.*?\)\s|".*?"(~\d+)?\s|".*?"(\/\d+)?\s|\S+)/g));
}

function show_query_helper(){
    $('#db_query').slideUp('slow', function(){
        $('#query_helper').slideDown('slow');
    });
    $('#query_must, #query_may, #query_must_not').val('');
    var query = parenthesis_to_brackets($('#profile_query').val()).replace(/\s+/g, ' ');
    var words = get_words(query);

    var query_may = new Array(), query_must = new Array(), query_must_not = new Array();
    if (words != null) {
        for (var i = words.length - 1; i >= 0; i--) {
            if (words[i].indexOf('+') == 0) {
                query_must.push(words[i].substring(1, words[i].length));
            }
            else
            if (words[i].indexOf('-') == 0) {
                query_must_not.push(words[i].substring(1, words[i].length));
            }
            else
            if (words[i].indexOf('|') != -1 && query_may == '') {
                query_may = words[i].split('|');
            }
            else {
                query_must.push(words[i]);
            }
        }
    }
    $('#query_must').val($.trim(brackets_to_parenthesis(query_must.reverse().join(";"))).replace(/;/g, "\n"));
    $('#query_may').val($.trim(brackets_to_parenthesis(query_may.join(";"))).replace(/;/g, "\n"));
    $('#query_must_not').val($.trim(brackets_to_parenthesis(query_must_not.reverse().join(";"))).replace(/;/g, "\n"));

    $('#query_helper_mode_toggle a').children('span').html("Expert mode");
    $('label[for=profile_query_button]').text("Requête (mode simplifié)");
    sicabol_tip_update();
}

function query_helper_ok(){
    var query = '';
    var query_must = $.trim(parenthesis_to_brackets($('#query_must').val()).replace(/(\s+)?\|(\s+)?/g, '|').replace(/[,;\n]/g, ' ')).toLowerCase();
    var query_may = $.trim(parenthesis_to_brackets($('#query_may').val()).replace(/(\s+)?\|(\s+)?/g, '|').replace(/[,;\n]/g, ' ')).toLowerCase();
    var query_must_not = $.trim(parenthesis_to_brackets($('#query_must_not').val()).replace(/(\s+)?\|(\s+)?/g, '|').replace(/[,;\n]/g, ' ')).toLowerCase();
    var words_must = array_unique(get_words(query_must));
    if (words_must != null) {
        if (words_must.length > 3)
            alert("Attention : vous avez paramétré plus de 3 termes qui doivent obligatoirement se trouver dans les résultats (champ \"Les pages doivent contenir TOUS les mots suivants\"), il est fort probable que peu ou pas de liens vous soient proposés dans l'actualité. Vérifiez si quelques uns de ces termes ne devraient pas se trouver dans le champ \"Les pages doivent contenir AU MOINS UN des mots suivants\".");
        query = words_must.join(' ');
    }
    var sub_query = '';
    var words_may = array_unique(get_words(query_may));
    if (words_may != null) {
        query = $.trim(query + ' ' + words_may.join(' | '));
    }
    var words_must_not = array_unique(get_words(query_must_not));
    if (words_must_not != null) {
        for (var i = 0; i < words_must_not.length; i++) {
            if (words_must_not[i][0] != '+' && words_must_not[i][0] != '-')
                words_must_not[i] = '-' + words_must_not[i];
            query = $.trim(query + ' ' + words_must_not[i]);
        }
    }
    query = brackets_to_parenthesis(query);
    $('#profile_query').val(query.replace(/\|/g, ' | ').replace(/\s+/g, ' '));
    hide_query_helper();
}

function hide_query_helper(){
    $('#query_helper').slideUp('slow', function(){
        $('#db_query').slideDown('slow');
    });
    $('#query_helper_mode_toggle a').children('span').html("Switch to simplified mode");
    $('label[for=profile_query_button]').text("Requête (mode expert)");
    sicabol_tip_update();
}

function update_settings(profile_id){
    var form = $('form#settings_' + profile_id);
    var profile_title_field = $('input#profile_title', form);
    var profile_title = $.trim(profile_title_field.val());
    if (profile_title != '' && profile_title_field.hasClass('default_field_value') == false) {
        $('#menu_profile_' + profile_id + ' .menu_profile_title, #profile_content_title').html(profile_title);
        if ($('#query_helper:visible').length > 0) {
            query_helper_ok();
        }
        var profile_query = $.trim($('#profile_query', form).val());
        if (profile_query == '' && profile_title != "New folder" && $('.profile_partner:checked').length == 0 && $('.profile_category:checked').length == 0) {
            profile_query = (profile_title.indexOf(' ') != -1) ? '"' + profile_title + '"' : profile_title;
        }
        var langs = new Array();
        $('.profile_lang:checked', form).each(function() {
            langs.push($(this).val());
        });
        var partners = new Array();
        $('.profile_partner:checked', form).each(function() {
            partners.push($(this).val());
        });
        var categories = new Array();
        $('.profile_category:checked', form).each(function() {
            categories.push($(this).val());
        });
        var not_categories = new Array();
        $('.profile_not_category:checked', form).each(function() {
            not_categories.push($(this).val());
        });
        $.post(site_domain + 'account/folders/update_settings/' + profile_id + '?user=' + preview_user, {
            'title': profile_title,
            'query': profile_query,
            'partners': partners,
            'categories': categories,
            'not_categories': not_categories,
            'langs': langs,
            'alerts': $('.profile_alert:checked', form).length
        }, function(data){
            if (data.substring(0, 3) == 'OK*') {
                var profile_id = data.substring(data.indexOf('*') + 1);
                change_profile_content(profile_id, 'news');
            } else {
                alert("An error occurred…")
            }
        });
    } else {
        alert("Please enter a title.");
        $('input#profile_title', form).focus();
    }
}

function toggle_check_all(){
    $('input[type=checkbox]', $('#profile_content_view')).prop('checked', ($('input[type=checkbox]:checked', $('#profile_content_view')).length == $('input[type=checkbox]', $('#profile_content_view')).length) ? false : true);
}
// * FIN MES DOSSIERS *****

// * RECHERCHE *****
function check_search_visible() {
    var flag = 1;
    $('#search_engine_options input[type=checkbox]').each(function() {
        if (flag && $(this).parent().css('display') != 'none') {
            flag = 0;
            $(this).trigger('change');
        }
    });
}

function show_search_options() {
    var elem = $('#search_query');
    if (elem.hasClass('search_query_defaut')) {
        elem.removeClass('search_query_defaut').val('').focus();
        $('#search_engine_options').css({
            top: elem.outerHeight()
        }).slideDown('slow');
    }
}

function hide_search_options() {
    if ($.trim($('#search_query').val()) == '') {
        $('#search_query').addClass('search_query_defaut').val("Search…");
        $('#search_engine_options').slideUp('slow');
    }
}

function do_search() {
    hide_article_view();
    search_datatable = null;
    if (!$('input.search_query_defaut').length) {
        var profile_id = get_opened_profile_id();
        if (profile_id == undefined) {
            profile_id = '';
        }
        var query = $.trim($('#search_query').val());
        if (query != "") {
            var hauteur_view = parseInt($(window).height(), 10) - 72;
            var largeur_view = parseInt($(window).width(), 10);
            $('#search_view').appendTo('body').show().width('100%').html("Please wait…").animate({
                height: hauteur_view + 'px'
            }, 1500, '', function(){
                $(this).show();
            });
            $.post(site_domain + 'account/folders/search?user=' + preview_user, {
                'query': query,
                'options': $('#search_engine_options input:checked').val(),
                'profile_id': profile_id
            }, function(data){
                $('#search_view').html(data);
                resize_views();
            });
        }
    }
}

function get_similars(crc32) {
    hide_article_view();
    search_datatable = null;
    var hauteur_view = parseInt($(window).height(), 10) - 72;
    var largeur_view = parseInt($(window).width(), 10);
    $('#search_view').appendTo('body').show().width('100%').html("Please wait…").animate({
        height: hauteur_view + 'px'
    }, 1500, '', function(){
        $(this).show();
    });
    $.post(site_domain + 'account/folders/similars?user=' + preview_user, {
        'crc32': crc32
    }, function(data){
        $('#search_view').html(data);
        resize_views();
    });
}

function hide_search_view() {
    hide_article_view();
    $('#search_view').animate({
        height: '0px'
    }, 1500, function(){
        $(this).hide();
    });
    $('#search_query').val('');
    hide_search_options();
}
// * FIN RECHERCHE *****

// * ARTICLE *****
function show_article(article_id, profile_ids_init, host, article_title, articles_list, is_archived) {
    window.onbeforeunload = exit_alert;
    profile_ids = profile_ids_init.split(',');
    var is_news_list = (articles_list == '#articles_table' || articles_list.substring(0, 13) == '#last_minute_') ? true : false;
    var profile_titles = new Array();
    for (var i = 0; i < profile_ids.length; i ++) {
        profile_titles[i] = $('#menu_profile_' + profile_ids[i] + ' .menu_profile_title').text();
    }
    var profile_title = profile_titles.join('&nbsp;| ');
    var hauteur_view = parseInt($(window).height(), 10) - 72;
    var largeur_view = parseInt($(window).width(), 10);
    var frame_url = site_domain + 'account/folders/article/' + article_id;
    article_view_moving = true;
    var msg_bannir = "Ban _XXXX_";
    var msg_bannir_alt = 'Do not take into account information from _XXXX_';
    var code = '<div id="article_view_infos"><div id="article_view_listname">' + profile_title + '</div><div id="article_view_title">' + article_title + '</div></div>';
    code += '<div id="article_view_actions">';
        code += '<div id="article_view_actions_close"><a onclick="hide_article_view()" title="Close the viewing window and return to the list of information">Close</a></div>';
        code += '<div id="article_view_actions_navigate">';
            code += '<a id="article_view_actions_navigate_next" href="#" onclick="show_other_article(\'' + articles_list + '\', 1);" title="Open the next info">&gt;</a>';
            code += '<a id="article_view_actions_navigate_prev" href="#" onclick="show_other_article(\'' + articles_list + '\', -1);" title="Open the previous info">&lt;</a>';
        code += '</div>';
        code += '<div id="article_view_actions_buttons">';
            code += '<div class="article_view_actions_buttons_row">';
                if (!is_archived && is_news_list && is_validator)
                    code += '<div id="article_view_actions_valider"><a href="#" onclick="set_article(1, \'' + profile_ids_init + '\', \'' + article_id + '\', \'' + articles_list + '\');" title="Validate info">Validate</a></div>';
                if (is_validator && has_newsletters)
                    code += '<div id="article_view_actions_newsletters"' +  ((is_archived) ? '' : ' style="display:none;"') + '><a href="#" onclick="add_to_newsletters(\'' + article_id + '\');" title="Add this information in next newsletters">Newsletters</a></div>';
                code += '<div id="article_view_actions_window"><a href="#" onclick="open_tab_article(\'' + article_id + '\');" title="Open the page in a new browser window">Open a new window</a></div>';
            code += '</div>';
            code += '<div class="article_view_actions_buttons_row">';
                if (is_deleter)
                    code += '<div id="article_view_actions_delete"><a href="#" onclick="set_article(0, \'' + profile_ids_init + '\', \'' + article_id + '\', \'' + articles_list + '\')" title="Delete info and open the next one ">Delete</a></div>';
                if (is_mail_sender)
                    code += '<div id="article_view_actions_email"><a href="#" onclick="open_sendbymail(\'' + article_id + '\', \'' + profile_ids_init + '\');" title="Send link information by e-mail">Send by e-mail</a></div>';
                if (is_news_list && is_validator)
                    code += '<div id="article_view_actions_ban"><a href="#" onclick="ban_site(\'' + host + '\', \'' + article_id + '\', \'' + articles_list + '\')" title="' + msg_bannir_alt.replace(/_XXXX_/gi, host) + '">' + msg_bannir.replace(/_XXXX_/gi, host) + '</a></div>';
            code += '</div>';
        code += '</div>';
    code += '</div>';
    code += '<iframe id="article_preview_browser" name="article_preview_browser" src="' + frame_url + '" height="' + (hauteur_view - 51) + '" width="100%" marginheight="0" marginwidth="0" frameborder="0"></iframe>';
    $('#article_view').appendTo('body').width('100%').show().attr({
        'article_id': article_id
    }).html(code).animate({
        height: hauteur_view + 'px'
    }, 1500, '', function(){
        $(this).css('display', 'block');
        $('#article_view iframe').show();
        article_view_moving = false;
    });

    var elem = $('#article_view .article_view_actions');
    $('.article_preview_dialog_close a', elem).click(function(){
        $(this).parents('.article_preview_dialog').slideUp('slow');
    });
}

function open_sendbymail(article_id, profile_ids) {
    $('#sendto_article_id').val(article_id);
    $('#sendto_profile_ids').val(profile_ids);
    $('#dialog_sendbymail #sendto_comment').val('');
    $('#dialog_sendbymail').dialog('open');
}

function show_other_article(articles_list, direction) {
    var articles_list = $(articles_list);
    var article_id = $('#article_view').attr('article_id');
    liste_articles = $('.article_from_list', articles_list);
    var article = liste_articles.filter('.article_' + article_id);
    var article_index = liste_articles.index(article) + direction;
    article = liste_articles.eq(liste_articles.index(article) + direction);
    if (article_index >= 0 && article.length > 0) {
        article.find('a[onclick^="show_article("]').trigger('click');
    }
    else {
        hide_article_view();
    }
}

function hide_article_view() {
    $('#article_view iframe').remove();
    $('#article_view').animate({
        height: '0px'
    }, 1500, function(){
        $(this).hide();
    });
}

function open_tab_article(article_id) {
    window.open(site_domain + 'account/folders/article/' + article_id);
}

function add_to_newsletters(article_id) {
    $.post(site_domain + 'account/folders/add_article_to_newsletters?user=' + preview_user, {
            'article_id': article_id
        }, function(data) {
            if (data.substring(0, 2) != 'OK') {
                if (data.substring(0, 3) == 'WRN') {
                    fadingalert(data.substring(3, data.length), 1);
                } else {
                    alert("An error occurred…");
                }
            } else {
                fadingalert("The info is available in the newsletters.");
            }
        });
}

function set_article(status, profile_ids, article_id, articles_list) {
    if ( ! status) {
        var open_next_flag = (parseInt($('#article_view').css('height'), 10) > 0) ? true : false;
        if (open_next_flag) {
            show_other_article(articles_list, 1);
        }
    }
    $.post(site_domain + 'account/folders/set_articles_status?user=' + preview_user, {
            'status': status,
            'article_profile_ids': new Array(article_id + ',' + profile_ids)
        }, function(data) {
            if (data.substring(0, 2) != 'OK') {
                alert("An error occurred…");
            } else {
                fadingalert("The info has been validated.");
                if ($('#article_view').attr('article_id') == data.substring(2, data.length)) {
                    $('#article_view_actions_valider').hide();
                    $('#article_view_actions_newsletters').show();
                }
                refresh_content(articles_list);
            }
        });
    if (( ! status) && ( ! open_next_flag)) {
        hide_article_view();
    }
}

function set_articles(status) {
    var checked_articles = $('input.check_article:checked');
    if (checked_articles.length) {
        var ids = new Array();
        checked_articles.each(function() {
            ids.push($(this).val());
        });
        $.post(site_domain + 'account/folders/set_articles_status?user=' + preview_user, {
            'status': status,
            'article_profile_ids': ids
        }, function(data) {
            if (data.substring(0, 2) != 'OK') {
                alert("An error occurred…");
            } else {
                articles_datatable.fnClearTable().fnDraw();
            }
        });
    }
}

function ban_site(host, article_id, articles_list){
    $.post(site_domain + 'account/folders/ban_site?user=' + preview_user, {
            'host': host,
            'article_id': (article_id != undefined) ? article_id : null
        }, function(data){
        if (data != 'OK') {
            alert("An error occurred…")
        } else {
            refresh_content(articles_list);
        }
    });
    hide_article_view();
}
// * FIN ARTICLE *****

// * ENVOIS *****
function delete_sendings() {
    var checked_articles = $('input.check_article:checked');
    if (checked_articles.length) {
        var ids = new Array();
        checked_articles.each(function() {
            ids.push($(this).val());
        });
        $.post(site_domain + 'account/folders/delete_sendings?user=' + preview_user, {
            'status': status,
            'ids': ids
        }, function(data) {
            if (data.substring(0, 2) != 'OK') {
                alert("An error occurred…");
            } else {
                sendings_datatable.fnClearTable().fnDraw();
            }
        });
    }
}

function send_mails() {
    $.post(site_domain + 'account/folders/send_mails?user=' + preview_user, {}, function(data) {
        if (data.substring(0, 2) == 'OK') {
            alert("The postponed mails have been sent.");
            sendings_datatable.fnClearTable().fnDraw();
        } else if (data.substring(0, 1) == '0') {
            alert("No mail is to be sent.");
            sendings_datatable.fnClearTable().fnDraw();
        } else {
            alert("An error occurred…");
        }
    });
}
// * FIN ENVOIS *****
