/* CSRFToken management */
$.ajaxSetup({
beforeSend: function(xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
}});
function manage_async_link(event){
    event.preventDefault();
    var url = $(this).attr('href');
    var target = $(this).attr('data-target');
    $.get(url, function(data) {
        $(target).html(data);
    });
}
/* default function to prevent undefined */
function get_next_table_id(){}
function get_previous_table_id(){}
var shortcut_url = '';
var get_file_url = '/get-file-shortcut/';
var get_own_file_url = '/get-file-shortcut/own/';
var get_operation_url = '/get-operation-shortcut/';
var get_own_operation_url = '/get-operation-shortcut/own/';
var get_contextrecord_url = '/get-contextrecord-shortcut/';
var get_own_contextrecord_url = '/get-contextrecord-shortcut/own/';
var get_find_url = '/get-find-shortcut/';
var get_own_find_url = '/get-find-shortcut/own/';
var shortcut_get_attr = '?submited=1&page=1&rows=10&cached_label=';
var current_file_change = function(){
    $.post('/' + url_path + 'update-current-item/',
           {item:'file', value:$("#current_file").val()},
           load_shortcut_menu
    );
};
var current_operation_change = function(){
    $.post('/' + url_path + 'update-current-item/',
           {item:'operation', value:$("#current_operation").val()},
           load_shortcut_menu
    );
};
var current_contextrecord_change = function(){
    $.post('/' + url_path + 'update-current-item/',
           {item:'contextrecord', value:$("#current_contextrecord").val()},
           load_shortcut_menu
    );
};
var current_find_change = function(){
    $.post('/' + url_path + 'update-current-item/',
           {item:'find', value:$("#current_find").val()},
           load_shortcut_menu
    );
};
function init_shortcut_fields(){
    var is_own = $('.activate_all_search').hasClass('disabled');
    var file_url = get_file_url;
    if (is_own) file_url = get_own_file_url;
    chosen_ajaxify("current_file", file_url + shortcut_get_attr,
                   current_file_change);
    var operation_url = get_operation_url;
    if (is_own) operation_url = get_own_operation_url;
    chosen_ajaxify("current_operation", operation_url + shortcut_get_attr,
                   current_operation_change);
    var contextrecord_url = get_contextrecord_url;
    if (is_own) contextrecord_url = get_own_contextrecord_url;
    chosen_ajaxify("current_contextrecord", contextrecord_url + shortcut_get_attr,
                   current_contextrecord_change);
    var find_url = get_find_url;
    if (is_own) find_url = get_own_find_url;
    chosen_ajaxify("current_find", find_url + shortcut_get_attr,
                   current_find_change);
}
function init_shortcut_menu(html){
    $("#progress").hide();
    $("#context_menu").html(html);
    $(".chosen-select").chosen();
    init_shortcut_fields();
}
function display_info(msg){
    $('#message .information .content').html(msg);
    $('#message').fadeIn('slow');
    $('#message .information').fadeIn('slow');
    setTimeout(
        function(){
            $('#message .information').fadeOut('slow');
            $('#message').fadeOut('slow');
        }, 5000);
}
function load_shortcut_menu(){
    if (!shortcut_url) return;
    $("#progress").show();
    $.ajax({
        url: shortcut_url,
        cache: false,
        success:function(html){
            init_shortcut_menu(html);
        },
        error:function(XMLHttpRequest, textStatus, errorThrows){
            $("#progress").hide();
        }
    });
}
$(document).ready(function(){
    $("#main_menu > ul > li > ul").hide();
    $("#main_menu ul ul .selected").parents().show();
    var items = new Array('file', 'operation');
    if ($(document).height() < 1.5*$(window).height()){
        $('#to_bottom_arrow').hide();
        $('#to_top_arrow').hide();
    }
    $('#language_selector').change(function(){
        $('#language_form').submit();
    });
    load_shortcut_menu();
    if ($.isFunction($(".prettyPhoto a").prettyPhoto)){
        $(".prettyPhoto a").prettyPhoto({'social_tools':''});
    }
    $('#current_items select').change(function(){
        $(this).attr('class', $(this).children("option:selected").attr('class'));
    });
    $("a.async-link").click(manage_async_link);
    $(".chosen-select").chosen();
});
$(document).on("click", '#to_bottom_arrow', function(){
  $("html, body").animate({ scrollTop: $(document).height() }, 1000);
});
$(document).on("click", '#to_top_arrow', function(){
  $("html, body").animate({ scrollTop: 0}, 1000);
});
$(document).on("click", '.check-all', function(){
  $(this).closest('table'
        ).find('input:checkbox'
        ).attr('checked', $(this).is(':checked'));
});
$(document).on("click", '#main_menu ul li', function(){
    var current_id = $(this).attr('id');
    console.log(current_id);
    $("#main_menu ul ul").not($(this).parents('ul')).not($(this).find('ul')
                        ).hide('slow');
    $(this).find('ul').show('slow');
});
/* manage help texts */
$(document).on("click", '.help_display', function(){
    var help_text_id = $(this).attr("href") + "_help";
    $(help_text_id).toggle();
});
$(document).on("click", '#progress-content', function(){
    $('#progress').hide();
});
function long_wait(){
    $('#progress').addClass('long');
    $('#progress').show();
    $('.progress-1').show('slow');
    setTimeout(function(){
        $('.progress-1').hide('slow');
        $('.progress-2').show('slow');
    }, 60000);
    setTimeout(function(){
        $('.progress-2').hide('slow');
        $('.progress-3').show('slow');
    }, 120000);
    setTimeout(function(){
        $('.progress-3').hide('slow');
        $('.progress-4').show('slow');
    }, 180000);
    setTimeout(function(){
        $('.progress-4').hide('slow');
        long_wait();
    }, 240000);
}
var last_window;
function load_window(url, speed, on_success){
    $("#progress").show();
    $.ajax({
        url: url,
        cache: false,
        success:function(html){
            $("#progress").hide();
            $("#window").append(html);
            $("#"+last_window).show();
            $("a[rel^='prettyPhoto']").prettyPhoto({'social_tools':''});
            if (on_success) on_success();
        },
        error:function(XMLHttpRequest, textStatus, errorThrows){
            $("#progress").hide();
        }
    });
}
function load_current_window(url, model_name){
    var id = $("#current_" + model_name).val();
    if (!id) return;
    url = url.split('/');
    url[url.length - 1] = id;
    url.push('');
    return load_window(url.join('/'));
}
function load_url(url){
    $("#progress").show();
    $.ajax({
        url: url,
        cache: false,
        success:function(html){
            $("#progress").hide();
        },
        error:function(XMLHttpRequest, textStatus, errorThrows){
            $("#progress").hide();
        }
    });
}
function open_window(url){
    var newwindow = window.open(url, '_blank',
                                'height=400,width=600,scrollbars=yes');
    if (window.focus) {newwindow.focus()}
    return false;
}
function save_and_close_window(name_label, name_pk, item_name, item_pk){
  var main_page = opener.document;
  jQuery(main_page).find("#"+name_label).val(item_name);
  jQuery(main_page).find("#"+name_pk).val(item_pk);
  opener.focus();
  self.close();
}
function save_and_close_window_many(name_label, name_pk, item_name, item_pk){
  var main_page = opener.document;
  var lbl_ = jQuery(main_page).find("#"+name_label);
  var val_ = jQuery(main_page).find("#"+name_pk);
  if (val_.val()){
    var v = lbl_.val();
    v = v.slice(0, v.lastIndexOf(","));
    lbl_.val(v + ", " + item_name + ", ");
    val_.val(val_.val() + ", " + item_pk);
    lbl_.change();
  } else {
    jQuery(main_page).find("#"+name_label).val(item_name);
    jQuery(main_page).find("#"+name_pk).val(item_pk);
  }
  opener.focus();
  self.close();
}
function multiRemoveItem(selItems, name, idx){
    for(id in selItems){
        if(selItems[id] == idx){
            selItems.splice(id, 1);
        }
    }
    jQuery("#selected_"+name+"_"+idx).remove();
}
function closeAllWindows(){
    jQuery("#window > div").hide("slow");
    jQuery("#window").html("");
}
function show_hide_flex(id){
    if ($(id).is(':hidden')){
        $(id).css('display', 'flex');
    } else {
        $(id).hide();
    }
}
var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();
function chosen_ajaxify(id, ajax_url, current_change_callback){
    $('div#' + id + '_chosen .chosen-search input').keyup(function(){
        var keyword = $('div#' + id + '_chosen .chosen-search input').val();
        var keyword_pattern = new RegExp(keyword, 'gi');
        $('div#' + id + '_chosen ul.chosen-results').empty();
        $("#"+id).empty();
        delay(function(){
            $.ajax({
                url: ajax_url + keyword,
                dataType: "json",
                success: function(response){
                    $('#'+id).append('');
                    if ('rows' in response){
                        $.map(response['rows'], function(item){
                            $('#'+id).append('');
                        });
                    }
                    $("#"+id).trigger("chosen:updated");
                    $('div#' + id + '_chosen .chosen-search input').val(keyword);
                    $('div#' + id + '_chosen').removeClass('chosen-container-single-nosearch');
                    $('div#' + id + '_chosen .chosen-search input').removeAttr('readonly');
                    $('div#' + id + '_chosen .chosen-search input').focus();
                    $('div#' + id + '_chosen .active-result').each(function(){
                        var html = $('div#' + id + '_chosen ul.chosen-results').html();
                        $('div#' + id + '_chosen ul.chosen-results').html(html.replace(keyword_pattern, function(matched){
                            return '' + matched + '';
                        }));
                    });
                    $("#" + id).change(current_change_callback);
                }
            });
        }, 1000);
    });
}
var activate_all_search_msg = "Searches in the shortcut menu deals with all items.";
var activate_own_search_msg = "Searches in the shortcut menu deals with only your items.";
function activate_all_search(){
    $('.activate_all_search').removeClass('disabled');
    $('.activate_own_search').addClass('disabled');
    init_shortcut_fields();
    display_info(activate_all_search_msg);
    return false;
}
function activate_own_search(){
    $('.activate_own_search').removeClass('disabled');
    $('.activate_all_search').addClass('disabled');
    init_shortcut_fields();
    display_info(activate_own_search_msg);
    return false;
}