/* Add your Application JavaScript */
$(function() {
  $("div[data-toggle=fieldset]").each(function() {
    var $this = $(this);

    //Add new entry
    $this.find("button[data-toggle=fieldset-add-row]").click(function() {
      var target = $($(this).data("target"))
      console.log(target);
      var oldrow = target.find("[data-toggle=fieldset-entry]:last");
      var row = oldrow.clone(true, true);
      console.log(row.find(":input")[0]);
      var elem_id = row.find(":input")[0].id;
      var elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1;
      row.attr('data-id', elem_num);
      row.find(":input").each(function() {
        console.log(this);
        var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + (elem_num) + '-');
        $(this).attr('name', id).attr('id', id).val('').removeAttr("checked");
      });
      oldrow.after(row);
    }); //End add new entry

    //Remove row
    $this.find("button[data-toggle=fieldset-remove-row]").click(function() {
      if ($this.find("[data-toggle=fieldset-entry]").length > 1) {
        var thisRow = $(this).closest("[data-toggle=fieldset-entry]");
        thisRow.remove();
      }
    }); //End remove row
  });
});


$(function() {
  $("#draggable").draggable();
  $("#droppable").droppable({
    drop: function(event, ui) {
      $(this)
        .addClass("ui-state-highlight")
        .find("p")
        .html("Dropped!");
    }
  });
});

$("#title_xppl").click(function() {
  generateTitle(this);
});

$(document).ready(function() {
  generateTitle("#title_xppl");
});

function generateTitle(elem) {
  var x = ["XPERIMENTAL"]
  var p1 = ["POTENTIAL", "PUBLIC", "POST", "PI", "PLATFORM FOR", "PRETENTIOUS"]
  var p2 = ["PIRATE", "PERFORMATIVE", "PUBLIC", "PUBLISHING", "POTENTIAL"]
  var l = ["LIBRARY", "LIAISON", "LAB", "LEGALITY", "LABOUR"]

  $(elem).text(x[Math.floor(Math.random() * x.length)] + " " + p1[Math.floor(Math.random() * p1.length)] + " " + p2[Math.floor(Math.random() * p2.length)] + " " + l[Math.floor(Math.random() * l.length)]);

}

$(function() {
  $("#tabs").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
  $("#tabs li").removeClass("ui-corner-top").addClass("ui-corner-left");
});




$(".no_cover").each(function() {
  var string = $(this).attr('id')
  var randomColor = colorHash(string).rgb

  $(this).css({
    'background-color': randomColor,
  });

})

function colorHash(inputString) {
  var sum = 0;

  for (var i in inputString) {
    sum += inputString.charCodeAt(i);
  }

  r = ~~(('0.' + Math.sin(sum + 1).toString().substr(6)) * 256);
  g = ~~(('0.' + Math.sin(sum + 2).toString().substr(6)) * 256);
  b = ~~(('0.' + Math.sin(sum + 3).toString().substr(6)) * 256);

  var rgb = "rgb(" + r + ", " + g + ", " + b + ")";

  var hex = "#";

  hex += ("00" + r.toString(16)).substr(-2, 2).toUpperCase();
  hex += ("00" + g.toString(18)).substr(-2, 2).toUpperCase();
  hex += ("00" + b.toString(20)).substr(-2, 2).toUpperCase();

  return {
    r: r,
    g: g,
    b: b,
    rgb: rgb,
    hex: hex
  };
}



//newsticker

$('.marquee').marquee({
  duplicated: true,
  pauseOnHover: true
});

$( document ).ready(function() {

  update();
    function update() {
      $.ajax({
               url: "/updates",
               type: 'GET',
               async: false,
               success : function(text)
                {
             response = text;
             $('.marquee').marquee('destroy')
             $('.marquee-text').text(response)
             $('.marquee').marquee({
               duplicated: true,
               pauseOnHover: true,
               duration: 7000,
               speed: 30,
               gap: 200,
               startVisible:true
             });
             console.log(response)
              },
               cache: false,
               contentType: false,
               processData: false
               });
    }

  });

$(document).ready(function()
    {
      $('.messages').scrollTop($('.messages')[0].scrollHeight)

        $("#table").tablesorter();

    }

);

// Autocomplete for search - Contact Joca in case of trouble

$('#search').on("input", function() {
  var query = this.value;


  $.ajax({
    url: "/autocomplete_suggestions",
    data: $('form').serialize(),
    type: "POST",
    success: function(response) {
      //console.log("Got your query!");
    }
  });

  function getData() {
    var deferredData = new jQuery.Deferred();

    $.ajax({
      type: "GET",
      url: "/autocomplete_suggestions",
      dataType: "json",
      success: function(data) {
        deferredData.resolve(data);
      }
    });
    return deferredData; // contains the passed data
  };

    var dataDeferred = getData();

  $.when(dataDeferred).done( function( data ) {
    var suggestion_list = data;
    console.log(suggestion_list);
    $().ready(function() {
        // search only, if the regexp matches
        var suggestions = data;

        // Defines for the example the match to take which is any word (with Umlauts!!).
        function _leftMatch(string, area) {
            //return string.substring(0, area.selectionStart).match(/[\wäöüÄÖÜß]+$/)
            //console.log(string.substring(string.lastIndexOf(" ")+1).match(/[\wäöüÄÖÜß]+$/))
            return string.substring(string.lastIndexOf(" ")+1).match(/[\wäöüÄÖÜß]+$/)

        }

        function _setCursorPosition(area, pos) {
            if (area.setSelectionRange) {
                area.setSelectionRange(pos, pos);
            } else if (area.createTextRange) {
                var range = area.createTextRange();
                range.collapse(true);
                range.moveEnd('character', pos);
                range.moveStart('character', pos);
                range.select();
            }
        }



        $("#search").autocomplete({
            position: { my : "right top", at: "right bottom" },
            source: function(request, response) {
                var str = _leftMatch(request.term, $("#search")[0]);
                str = (str != null) ? str[0] : "";
                console.log(str);
                response($.ui.autocomplete.filter(
                        suggestions, str));
            },
            minLength: 1,  // does have no effect, regexpression is used instead
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            // Insert the match inside the ui element at the current position by replacing the matching substring
            select: function(event, ui) {
                //alert("completing "+ui.item.value);},
                var m = _leftMatch(this.value, this)[0];
                var beg = this.value.substring(0, this.selectionStart - m.length);
                this.value = beg + ui.item.value + this.value.substring(this.selectionStart, this.value.length);
                var pos = beg.length + ui.item.value.length;
                _setCursorPosition(this, pos);
                return false;
            },
            search:function(event, ui) {
                var m = _leftMatch(this.value, this);
                return (m != null )
            }

        });
    })

  });

});
