(function ($) {

/**
* @file
* Javascript support files.
*
*/

Drupal.behaviors.twitter_bootstrap_modal = {
  attach: function (context, settings) {
    // Actions to make link Twitter Bootstrap Modal
    var TBtrigger = Drupal.settings.jquery_ajax_load.TBtrigger;
    // Puede ser más de un valor, hay que usar foreach()
    $(TBtrigger).once(function() {
      var html_string = $(this).attr( 'href' );
      // Hay que validar si la ruta trae la URL del sitio
      $(this).attr( 'href' , '/jquery_ajax_load/get' + html_string );
      $(this).attr( 'data-target' , '#jquery_ajax_load');
      $(this).attr( 'data-toggle' , 'modal' );
    });
    var TBmodaltrigger = Drupal.settings.jquery_ajax_load.TBmodaltrigger;
    $(TBmodaltrigger).once(function() {
      $(this).click(openDialog);
    });
  }
}

var openDialog = function() {
  var TBpath = Drupal.settings.jquery_ajax_load.TBpath;
  var html_string = TBpath + 'bs_modal' + $(this).attr( 'href' );
  $('#jquery_ajax_load').remove();
  twitter_bootstrap_modal_create_modal();
  $('#jquery_ajax_load').modal({
    remote: html_string
  });
  return false;
}

function twitter_bootstrap_modal_create_modal() {
  var modal_name = Drupal.settings.jquery_ajax_load.TBname;
  var modal_module = Drupal.settings.jquery_ajax_load.TBmodule;
  $('body').append('<div id="jquery_ajax_load" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">');
  $('#jquery_ajax_load').append('<div class="modal-dialog" />');
  $('#jquery_ajax_load .modal-dialog').append('<div class="modal-content" />');
  $('#jquery_ajax_load .modal-content').append('<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 class="modal_title">' + modal_name + '</h3></div>');
  $('#jquery_ajax_load .modal-content').append('<div class="modal-body"><span class="text-warning">' + Drupal.t('Loading') + '... </span><img src="/' + modal_module + '/twitter_bootstrap_modal_loading.gif"></div>');
  $('#jquery_ajax_load .modal-content').append('<div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">' + Drupal.t('Close') + '</button></div>');
}

}(jQuery));

;

(function ($) {
namespace('Drupal.media.browser');

Drupal.behaviors.mediaLibrary = {
  attach: function (context, settings) {
    var library = new Drupal.media.browser.library(Drupal.settings.media.browser.library);
    $('#media-browser-tabset').bind('tabsshow', function (event, ui) {
      if (ui.tab.hash === '#media-tab-library') {
        // Grab the parameters from the Drupal.settings object
        var params = {};
        for (var parameter in Drupal.settings.media.browser.library) {
          params[parameter] = Drupal.settings.media.browser.library[parameter];
        }
        library.start($(ui.panel), params);
        $('#scrollbox').bind('scroll', library, library.scrollUpdater);
      }
    });
  }
};

Drupal.media.browser.library = function (settings) {
  this.settings = Drupal.media.browser.library.getDefaults();
  $.extend(this.settings, settings);

  this.done = false; // Keeps track of if the last request for media returned 0 results.

  this.cursor = 0; // keeps track of what the last requested media object was.
  this.mediaFiles = []; // An array of loaded media files from the server.
  this.selectedMediaFiles = [];
};

Drupal.media.browser.library.getDefaults = function () {
  return {
    emtpyMessage: Drupal.t('There is nothing in your media library. Select the Upload tab above to add a file.'),
    limit: 15
  };
};

Drupal.media.browser.library.prototype.start = function (renderElement, params) {
  this.renderElement = renderElement;
  this.params = params;
  // Change the behavior dependent on multiselect
  if (params.multiselect) {
    this.clickFunction = this.multiSelect;
  } else {
    this.clickFunction = this.singleSelect;
  }
  this.loadMedia();
};

/**
 * Appends more media onto the list
 */
Drupal.media.browser.library.prototype.loadMedia = function () {
  var that = this;
  $('#status').text(Drupal.t('Loading...')).show();
  $.extend(this.params, {start: this.cursor, limit: this.settings.limit});

  var gotMedia = function (data, status) {
    $('#status').text('').hide();
    if (data.media.length < that.params.limit) {
      // We remove the scroll event listener, nothing more to load after this.
      $('#scrollbox').unbind('scroll');
    }
    that.mediaFiles = that.mediaFiles.concat(data.media);
    that.render(that.renderElement);
    // Remove the flag that prevents loading of more media
    that.loading = false;
  };

  var errorCallback = function () {
    alert(Drupal.t('Error getting media.'));
  };

  $.ajax({
    url: this.settings.getMediaUrl,
    type: 'GET',
    dataType: 'json',
    data: this.params,
    error: errorCallback,
    success: gotMedia
  });
};

Drupal.media.browser.library.prototype.scrollUpdater = function (e){
  if (!e.data.loading) {
    var scrollbox = $('#scrollbox');
    var scrolltop = scrollbox.attr('scrollTop');
    var scrollheight = scrollbox.attr('scrollHeight');
    var windowheight = scrollbox.attr('clientHeight');
    var scrolloffset = 20;

    if(scrolltop >= (scrollheight - (windowheight + scrolloffset))) {
      // Set a flag so we don't make multiple concurrent AJAX calls
      e.data.loading = true;
      // Fetch new items
      e.data.loadMedia();
    }
  }
};

/**
 * Fetches the next media object and increments the cursor.
 */
Drupal.media.browser.library.prototype.getNextMedia = function () {
  if (this.cursor >= this.mediaFiles.length) {
    return false;
  }
  var ret = this.mediaFiles[this.cursor];
  this.cursor += 1;
  return ret;
};

Drupal.media.browser.library.prototype.render = function (renderElement) {

  if (this.mediaFiles.length < 1) {
    $('<div id="media-empty-message" class="media-empty-message"></div>').appendTo(renderElement)
      .html(this.emptyMessage);
    return;
  }
  else {
    var mediaList = $('#media-browser-library-list', renderElement);
    // If the list doesn't exist, bail.
    if (mediaList.length === 0) {
      throw('Cannot continue, list element is missing');
    }
  }

  while (this.cursor < this.mediaFiles.length) {
    var mediaFile = this.getNextMedia();

    var data = {};
    data.obj = this;
    data.file = mediaFile;

    var listItem = $('<li></li>').appendTo(mediaList)
      .attr('id', 'media-item-' + mediaFile.fid)
      .html(mediaFile.preview)
      .bind('click', data, this.clickFunction);
  }
};

Drupal.media.browser.library.prototype.mediaSelected = function (media) {
  Drupal.media.browser.selectMedia(media);
};

Drupal.media.browser.library.prototype.singleSelect = function (event) {
  var lib = event.data.obj;
  var file = event.data.file;
  event.preventDefault();
  event.stopPropagation();

  $('.media-item').removeClass('selected');
  $('.media-item', $(this)).addClass('selected');
  lib.mediaSelected([event.data.file]);
  return false;
}

Drupal.media.browser.library.prototype.multiSelect = function (event) {
  var lib = event.data.obj
  var file = event.data.file;
  event.preventDefault();
  event.stopPropagation();

  // Turn off or on the selection of this item
  $('.media-item', $(this)).toggleClass('selected');

  // Add or remove the media file from the array
  var index = $.inArray(file, lib.selectedMediaFiles);
  if (index == -1) {
    // Media file isn't selected, add it
    lib.selectedMediaFiles.push(file);
  } else {
    // Media file has previously been selected, remove it
    lib.selectedMediaFiles.splice(index, 1);
  }

  // Pass the array of selected media files to the invoker
  lib.mediaSelected(lib.selectedMediaFiles);
  return false;
}

}(jQuery));
;

(function ($) {
namespace('Drupal.media.browser');

Drupal.media.browser.selectedMedia = [];
Drupal.media.browser.mediaAdded = function () {};
Drupal.media.browser.selectionFinalized = function (selectedMedia) {
  // This is intended to be overridden if a callee wants to be triggered
  // when the media selection is finalized from inside the browser.
  // This is used for the file upload form for instance.
};

Drupal.behaviors.experimentalMediaBrowser = {
  attach: function (context) {
    if (Drupal.settings.media.selectedMedia) {
      Drupal.media.browser.selectMedia(Drupal.settings.media.selectedMedia);
      // Fire a confirmation of some sort.
      Drupal.media.browser.finalizeSelection();
    }
    $('#media-browser-tabset').tabs({
      load: Drupal.media.browser.resizeIframe
    });

    $('.media-browser-tab').each( Drupal.media.browser.validateButtons );

    Drupal.media.browser.selectErrorTab();

  }
  // Wait for additional params to be passed in.
};

Drupal.media.browser.launch = function () {

};

Drupal.media.browser.validateButtons = function() {
  // The media browser runs in an IFRAME. The Drupal.media.popups.mediaBrowser()
  // function sets up the IFRAME and "OK" and "Cancel" buttons that are outside
  // of the IFRAME, so that their click handlers can destroy the IFRAME while
  // retaining information about what media items were selected. However,
  // Drupal UI convention is to place all action buttons on the same "line"
  // at the bottom of the form, so if the form within the IFRAME contains a
  // "Submit" button or other action buttons, then the "OK" and "Cancel"
  // buttons below the IFRAME break this convention and confuse the user.
  // Therefore, we add "Submit" and "Cancel" buttons inside the IFRAME, and
  // have their click action trigger the click action of the corresonding
  // "OK" and "Cancel" buttons that are outside the IFRAME. media.css contains
  // CSS rules that hide the outside buttons.
  //
  // We don't add a "Submit" button if the form already has one, since in these
  // cases, another round-trip to the server is needed before the user's
  // selection is finalized. For these cases, when the form's real Submit
  // button is clicked, the server either returns another form for the user to
  // fill out, or else a completion page that contains or sets the
  // Drupal.media.browser.selectedMedia variable. If the latter, then
  // Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad() auto-triggers the
  // "OK" button action to finalize the selection and remove the IFRAME.
  //
  // @todo An alternate, less hacky solution would be most welcome.
  if (!($('.form-submit', this).length > 0)) {
    $('<a class="button button-yes fake-ok">' + Drupal.t('Submit') + '</a>').appendTo(this).bind('click', Drupal.media.browser.submit);
    if (!($('.fake-cancel', this).length > 0)) {
      $('<a class="button button-no fake-cancel">' + Drupal.t('Cancel') + '</a>').appendTo(this).bind('click', Drupal.media.browser.submit);
    }
  } else if (!($('.fake-cancel', this).length > 0)) {
    var parent = $('.form-actions', this);
    if (!parent.length) {
      parent = $('form > div', this);
    }
    $('<a class="button button-no fake-cancel">' + Drupal.t('Cancel') + '</a>').appendTo(parent).bind('click', Drupal.media.browser.submit);
  }
};

Drupal.media.browser.submit = function () {
  // @see Drupal.media.browser.validateButtons().
  var buttons = $(parent.window.document.body).find('#mediaBrowser').parent('.ui-dialog').find('.ui-dialog-buttonpane button');
  if ($(this).hasClass('fake-cancel')) {
    buttons[1].click();
  } else {
    buttons[0].click();
  }
}

Drupal.media.browser.selectMedia = function (selectedMedia) {
  Drupal.media.browser.selectedMedia = selectedMedia;
};

Drupal.media.browser.finalizeSelection = function () {
  if (!Drupal.media.browser.selectedMedia) {
    throw new exception(Drupal.t('Cannot continue, nothing selected'));
  }
  else {
    Drupal.media.browser.selectionFinalized(Drupal.media.browser.selectedMedia);
  }
};

Drupal.media.browser.resizeIframe = function (event) {
  var h = $('body').height();
  $(parent.window.document).find('#mediaBrowser').height(h);
};

Drupal.media.browser.selectErrorTab = function() {
  //Find the ID of a tab with an error in it
  var errorTabID = $('#media-browser-tabset')
    .find('.error')
    .parents('.media-browser-tab')
    .attr('id');

  if (errorTabID !== undefined) {
    //Find the Tab Link with errorTabID
    var tab = $('a[href="#' + errorTabID + '"]');
    //Find the index of the tab
    var index = $('#media-browser-tabset a').index(tab);
    //Select the tab
    $('#media-browser-tabset').tabs('select', index)
  }
}

}(jQuery));
;
