// -*- coding: utf-8 -*-
$(document).ready(function(){
    
    $("form").bind("keypress", function (e) {
        if (e.keyCode == 13) {
            return false;
        }
    });
    
    $(".remove-ds-from-folder").on( "click", function(e) {
        var li = e.target.parentNode;
        var dsid = li.getAttribute("data-dsid");
        var list = $("#ds_ids").val().split(",");
        var index = list.indexOf(dsid);
        if (index > -1) {
            list.splice(index, 1);
            li.parentNode.removeChild(li);
        }
        $("#ds_ids").val( list.join(",") );
    });
    
    function loadDatasheets(url, data){
        $.ajax({
            url: url,
            type: 'GET',
            data: data,
            // bug with jquery >= 1.5, "json" adds a callback so we don't specify dataType
            //dataType: 'json',
            success: function(msg, textStatus, XMLHttpRequest) {
                $('#ds-search-list').html(msg);
                $(".ajax-link").click(function(e){
                    e.preventDefault();
                    loadDatasheets(e.target.getAttribute("href"));
                });
                $(".result_link").click(function(e){
                    var dsid = e.target.getAttribute("data-dsid");
                    // add datasheet id to the folder's list
                    $("#ds_ids").val( $("#ds_ids").val() + (($("#ds_ids").val()=="") ? "" : ",") + dsid );
                    // add datasheet id to the folder's list
                    var newds = $("#ds-list").append('<li data-dsid="' + dsid + '">' + e.target.innerHTML + ' <span class="remove-ds-from-folder hand_cursor">X</span></li>');
                });
            },
            error: function(jqXHR, textStatus, errorThrown) {
                resp = $.parseJSON(jqXHR.responseText);
                alert(resp.message);
            }
        });
    }
    
    $("#ok_search").click(function(){
        if($("#ds-search").val()!=""){
            loadDatasheets(search_url, { q:$('#ds-search').val() });
        }
    });
    
});
