/* Cookie functions, copied from CMFPlone */
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    } else {
        expires = ""; 
    }   
    document.cookie = name+"="+escape(value)+expires+"; path=/;";
};

function readCookie(name, default_val) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }   
        if (c.indexOf(nameEQ) == 0) {
            return unescape(c.substring(nameEQ.length,c.length));
        }   
    }   
    return default_val;
};

function interpolate_url(model, obj) {
    return model.replace(/%s/g, function(match){return String(obj.shift())});
}

/* - select_all.js - */
function select_all() {
    $('.copiable').each(function() {
        $(this).addClass("copied");
    });
    update_buttons();
}

function deselect_all() {
    $('.copiable').each(function() {
        $(this).removeClass("copied");
    });
    update_buttons();
}

function count_selected() {
    return $('.copied').length;
}

function update_buttons() {
    // Copy, delete need at least one selected
    var num_sel = count_selected();
    if (num_sel > 0) {
        $('input#copy, input#delete').attr("disabled", false);
    } else {
        $('input#copy, input#delete').attr("disabled", true);
    }
    if (num_sel > 1) {
        $('input#compare').attr("disabled", false);
    } else {
        $('input#compare').attr("disabled", true);
    }
}

function get_selected_ids() {
    var ids_list = [];
    $('.copied').each(function() {
        ids_list.push($(this).attr('id'));
    });
    return ids_list;
}

function compare_selected() {
    var full_ids = get_selected_ids();
    var ids = [];
    // Check if same type
    var brain_type = '';
    for (var i=0; i<full_ids.length; i++) {
        if (ids.length > 5) {
            alert(gettext("Only the first 6 selected objects will be compared."));
            break;
        }
        if (brain_type == '') brain_type = full_ids[i].split('-')[0];
        else {
            if (full_ids[i].split('-')[0] != brain_type) {
                alert(gettext("Sorry, you can only compare objects of the same type."));
                return false;
            }
        }
        ids.push(full_ids[i].split('-')[1]);
    }
    document.location.href = interpolate_url(url_compare, [brain_type, ids.join('-')]);
    return false;
}

function paste_in_list() {
    // get number of objects to copy
    var num_obj = $.ajax({ type: "GET", url: url_copy_number, async: false }).responseText;
    if (num_obj == 0) {
        alert(gettext("Sorry, there are no copied object."));
        return false;
    }
    msg = gettext("Do you really want to copy %s object(s) into this list?");
    rep = confirm(interpolate(msg, [num_obj]));
    if (rep) {
        post_action(interpolate_url(url_paste, [brain_id]), '', '', reload_page);
    }
    return false;
}

/* TODO: make value divs an object?
var value_div = { // or function ValueDiv() {}
  f1: function() {},
  f2: function() {}
}*/

function setup_editable_td(selector) {
    $(selector).hoverIntent(function() {
        // Display add button
        var descr_id = $(this).attr('id').split('-')[1];
        $(this).append("<div class='add_button'><a href='.' class='add_link'><img class='edit_icon' src='"+static_url+"img/add_icon.gif' height='14' title='"+gettext('Add value')+"' alt='add icon' /></a></div>");
        $('.add_link', this).click(function (ev) { ev.preventDefault(); get_newvalue_widget(descr_id); });
    }, function() {
        // Hide button
        $('.add_button', this.parent).remove();
    });
}

function setup_value_div(selector) {
    $(selector).each(function(index) {
        if ($(this).hasClass('editable')) {
            $(this).hoverIntent(function() {
                // Display edit buttons
                var value_id = $(this).attr('id').split('-', 2)[1];
                var buttons_div = "<div class='edit_buttons'><a href='.' class='edit_link'><img class='edit_icon' src='"+static_url+"img/edit_icon.gif' height='10' title='"+gettext('Edit')+"' alt='edit icon' /></a>";
                if ($(this).hasClass('deletable'))
                    buttons_div += "&nbsp;<a href='.' class='delete_link'><img class='edit_icon' src='"+static_url+"img/delete_icon.gif' height='10' title='"+gettext('Delete')+"' alt='delete icon' /></a></div>";
                $(this).append(buttons_div);
                $('.edit_link', this).click(function (ev) { ev.preventDefault(); get_value_widget(value_id); });
                $('.delete_link', this).click(function (ev) { ev.preventDefault(); return delete_value(value_id); });
            }, function() {
                // Hide edit buttons
                $('.edit_buttons', this).remove();
            });
        };
        var exclude = [];
        var classes = ['editable','searchable','addable','deletable'];
        for (var i=0; i < classes.length; i++) {
            if (! $(this).hasClass(classes[i])) exclude.push(classes[i]);
        }
        $(this).contextMenu({menu: 'ctxt_menu'}, exclude, function(action, el, pos) {
            var value_id = el.attr('id').split('-', 2)[1];
            if (action == 'edit')   get_value_widget(value_id);
            else if (action == 'add')   {
                var descr_id = el.closest('td').attr('id').split('-')[1];
                get_newvalue_widget(descr_id);
            }
            else if (action == 'delete')    delete_value(value_id);
            else if (action == 'search')    {
                var descr_name = el.closest('tr').attr('id').split('-', 2)[1];
                window.location = interpolate_url(url_search_by_descr, [descr_name]) + '?' + $.param({'same_as': value_id});
            }
        });
        //jQuery.extend($this), value_div)
    });
}

function change_content_state(widget) {
    var url = widget.options[widget.selectedIndex].value;
    return post_action(url, 'selected', '', reload_page);
}

function delete_value(val_id) {
    var msg = gettext("Do you really want to delete this value?");
    return post_action(url_delete_value, val_id, msg, function(data) {
        $("div#value-"+data).remove();
    });
}

function has_file_input(form) {
    var file_input = false;
    $(':input', form).each(function(idx) {
        if (this.type == "file")
           file_input = true;
    });
    return file_input;
}

function get_value_widget(val_id) {
    $.get(interpolate_url(url_edit_value, [val_id]), function(data) {
        // Insert edit form in value div
        var val_div = $("div#value-"+val_id);
        var prev_content = val_div.html();
        val_div.html(data);
        val_div.unbind('mouseover').unbind('mouseout');
        active_calendar_icon(".calendar_icon");
        var form = $('form:first', val_div);
        form.submit(function(ev) {
            if (!has_file_input(form)) {
                ev.preventDefault();
                save_value(form, val_div);
            }
        });
        $('img.cancel', val_div).click(function(ev) {
            ev.preventDefault();
            val_div.html(prev_content).unbind();
            $('.edit_buttons', val_div).remove();
            setup_value_div(val_div);
        });
        $('img.save', val_div).click(function(ev) {
            ev.preventDefault();
            form.submit();
        });
    });
}

function get_newvalue_widget(descr_id) {
    $.get(interpolate_url(url_add_value, [brain_type, brain_id, descr_id]), function(data) {
        var val_td = $("td#descr-"+descr_id);
        $('.add_button', val_td).remove();
        val_td.append(data);
        active_calendar_icon(".calendar_icon");
        $('img.cancel', val_td).click(function(ev) {
            ev.preventDefault();
            $('form', val_td).remove();
        });
        $('img.save', val_td).click(function(ev) {
            ev.preventDefault();
            var form = $('form:first', val_td);
            if (has_file_input(form)) form.submit();
            else save_value(form, null);
        });
    });
}

function active_calendar_icon(selector) {
  $(selector).click(function() {
        $(this).hide();
        var next_span = $(this).next();
        next_span.show();
        $(".year", next_span).focus();
    });
}

function save_value(form, val_div) {
    $.ajax({
        type: "POST", url: form.attr('action'),
        data: form.serialize(), async: false,
        success: function(data){
            // Show new value
            var td_div = form.closest('td');
            if (val_div != null) {
              val_div.replaceWith(data);
              val_div = td_div.find('#'+val_div.attr('id'));
            } else {
              form.remove();
              td_div.append(data);
              val_div = td_div.find('div.value:last');
            }
            setup_value_div(val_div);
        }
    });
}

function post_action(url, param, conf_msg, callback) {
    // Returns true if the action has been executed without errors
    if (param == 'selected') {
        param = get_selected_ids().join("|");
        if (param == "") {
            alert(gettext("Sorry, there are no selected object."));
            return false;
        }
    }
    // Optional confirm message
    if (conf_msg && conf_msg != "" && conf_msg != "None") {
        var answer = confirm(conf_msg);
        if (!answer) { return false; }
    }
    $.ajax({
        type: "POST",
        url: url,
        data: "param="+param,
        async: false,
        success: function(data){
            if (typeof callback != 'undefined') callback(data);
        }
    });
    return false;
}

function reload_page(data) {
    // Used as callback to post_action
    if (data != "" && (data.substring(0,7)=="http://" || data.substring(0,1)=="/"))
        window.location = data;
    else window.location = window.location.href;
}

/* Functions to dynamically delete a form from a formset
   http://djangosnippets.org/snippets/1389/
*/
function updateElementIndex(el, prefix, ndx) {
    var id_regex = new RegExp('(' + prefix + '-\\d+)');
    var replacement = prefix + '-' + ndx;
    if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
    if (el.id) el.id = el.id.replace(id_regex, replacement);
    if (el.name) el.name = el.name.replace(id_regex, replacement);
}

function deleteForm(form_row, prefix) {
    form_row.remove();
    var forms = $('.dynamic-form');
    $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
    $('#id_' + prefix + '-INITIAL_FORMS').val(forms.length -1); // or - extra forms
    for (var i=0, formCount=forms.length; i<formCount; i++) {
        $("*", forms[i]).filter(":input").each(function() {
            updateElementIndex(this, prefix, i);
        });
    }
    return false;
}


$(document).ready(function() {
  if ($(".action_menu_header").length) {
    $(".action_menu_header").toggle(function() {
        // Hide all then show this one
        $('.action_menu_content').css('display', 'none');
        $(this).next('.action_menu_content').css('display', 'block');
    }, function() {
        $(this).next('.action_menu_content').css('display', 'none');
    });
  }
  $(document).ajaxError(function(ev, xhr, settings, thrownError) {
    var error_details = "";
    if (xhr.status == 404) error_details = " (404)";
    if (xhr.responseText.length < 100 && xhr.responseText.length > 0)
        error_details += "\n" + xhr.responseText;
    alert(gettext("Sorry, an error occurred.") + error_details);
  });
});

